blob: d1567c8d6cca6d5ac8e7b52b39f67d9df9a04dfa [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
Nico Weber11d1a692012-05-20 01:27:21 +0000382 if (!getLangOpts().RTTI) {
383 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
384 }
385
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000386 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000387
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000388 if (isType) {
389 // The operand is a type; handle it as such.
390 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000391 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
392 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000393 if (T.isNull())
394 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000395
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000396 if (!TInfo)
397 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000398
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000399 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000400 }
Mike Stump1eb44332009-09-09 15:08:12 +0000401
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000402 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000403 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000404}
405
Francois Pichet6915c522010-12-27 01:32:00 +0000406/// Retrieve the UuidAttr associated with QT.
407static UuidAttr *GetUuidAttrOfType(QualType QT) {
408 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000409 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000410 if (QT->isPointerType() || QT->isReferenceType())
411 Ty = QT->getPointeeType().getTypePtr();
412 else if (QT->isArrayType())
413 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
414
Francois Pichet8db75a22011-05-08 10:02:20 +0000415 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichet6915c522010-12-27 01:32:00 +0000416 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet8db75a22011-05-08 10:02:20 +0000417 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
418 E = RD->redecls_end(); I != E; ++I) {
419 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichet6915c522010-12-27 01:32:00 +0000420 return Uuid;
Francois Pichet6915c522010-12-27 01:32:00 +0000421 }
Francois Pichet8db75a22011-05-08 10:02:20 +0000422
Francois Pichet6915c522010-12-27 01:32:00 +0000423 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000424}
425
Francois Pichet01b7c302010-09-08 12:20:18 +0000426/// \brief Build a Microsoft __uuidof expression with a type operand.
427ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
428 SourceLocation TypeidLoc,
429 TypeSourceInfo *Operand,
430 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000431 if (!Operand->getType()->isDependentType()) {
432 if (!GetUuidAttrOfType(Operand->getType()))
433 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
434 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000435
Francois Pichet01b7c302010-09-08 12:20:18 +0000436 // FIXME: add __uuidof semantic analysis for type operand.
437 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
438 Operand,
439 SourceRange(TypeidLoc, RParenLoc)));
440}
441
442/// \brief Build a Microsoft __uuidof expression with an expression operand.
443ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
444 SourceLocation TypeidLoc,
445 Expr *E,
446 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000447 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000448 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000449 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
450 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
451 }
452 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000453 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
454 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000455 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000456}
457
458/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
459ExprResult
460Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
461 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000462 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000463 if (!MSVCGuidDecl) {
464 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
465 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
466 LookupQualifiedName(R, Context.getTranslationUnitDecl());
467 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
468 if (!MSVCGuidDecl)
469 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000470 }
471
Francois Pichet01b7c302010-09-08 12:20:18 +0000472 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000473
Francois Pichet01b7c302010-09-08 12:20:18 +0000474 if (isType) {
475 // The operand is a type; handle it as such.
476 TypeSourceInfo *TInfo = 0;
477 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
478 &TInfo);
479 if (T.isNull())
480 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000481
Francois Pichet01b7c302010-09-08 12:20:18 +0000482 if (!TInfo)
483 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
484
485 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
486 }
487
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000488 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000489 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
490}
491
Steve Naroff1b273c42007-09-16 14:56:35 +0000492/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000493ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000494Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000495 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000496 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000497 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
498 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000499}
Chris Lattner50dd2892008-02-26 00:51:44 +0000500
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000501/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000502ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000503Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
504 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
505}
506
Chris Lattner50dd2892008-02-26 00:51:44 +0000507/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000508ExprResult
Douglas Gregorbca01b42011-07-06 22:04:06 +0000509Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
510 bool IsThrownVarInScope = false;
511 if (Ex) {
512 // C++0x [class.copymove]p31:
513 // When certain criteria are met, an implementation is allowed to omit the
514 // copy/move construction of a class object [...]
515 //
516 // - in a throw-expression, when the operand is the name of a
517 // non-volatile automatic object (other than a function or catch-
518 // clause parameter) whose scope does not extend beyond the end of the
519 // innermost enclosing try-block (if there is one), the copy/move
520 // operation from the operand to the exception object (15.1) can be
521 // omitted by constructing the automatic object directly into the
522 // exception object
523 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
524 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
525 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
526 for( ; S; S = S->getParent()) {
527 if (S->isDeclScope(Var)) {
528 IsThrownVarInScope = true;
529 break;
530 }
531
532 if (S->getFlags() &
533 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
534 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
535 Scope::TryScope))
536 break;
537 }
538 }
539 }
540 }
541
542 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
543}
544
545ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
546 bool IsThrownVarInScope) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000547 // Don't report an error if 'throw' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +0000548 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000549 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000550 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregorbca01b42011-07-06 22:04:06 +0000551
John Wiegley429bb272011-04-08 18:41:53 +0000552 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregorbca01b42011-07-06 22:04:06 +0000553 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley429bb272011-04-08 18:41:53 +0000554 if (ExRes.isInvalid())
555 return ExprError();
556 Ex = ExRes.take();
557 }
Douglas Gregorbca01b42011-07-06 22:04:06 +0000558
559 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
560 IsThrownVarInScope));
Sebastian Redl972041f2009-04-27 20:27:31 +0000561}
562
563/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000564ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
565 bool IsThrownVarInScope) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000566 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000567 // A throw-expression initializes a temporary object, called the exception
568 // object, the type of which is determined by removing any top-level
569 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000570 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000571 // or "pointer to function returning T", [...]
572 if (E->getType().hasQualifiers())
John Wiegley429bb272011-04-08 18:41:53 +0000573 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000574 E->getValueKind()).take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000575
John Wiegley429bb272011-04-08 18:41:53 +0000576 ExprResult Res = DefaultFunctionArrayConversion(E);
577 if (Res.isInvalid())
578 return ExprError();
579 E = Res.take();
Sebastian Redl972041f2009-04-27 20:27:31 +0000580
581 // If the type of the exception would be an incomplete type or a pointer
582 // to an incomplete type other than (cv) void the program is ill-formed.
583 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000584 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000585 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000586 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000587 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000588 }
589 if (!isPointer || !Ty->isVoidType()) {
590 if (RequireCompleteType(ThrowLoc, Ty,
Douglas Gregord10099e2012-05-04 16:32:21 +0000591 isPointer? diag::err_throw_incomplete_ptr
592 : diag::err_throw_incomplete,
593 E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000594 return ExprError();
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000595
Douglas Gregorbf422f92010-04-15 18:05:39 +0000596 if (RequireNonAbstractType(ThrowLoc, E->getType(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +0000597 diag::err_throw_abstract_type, E))
John Wiegley429bb272011-04-08 18:41:53 +0000598 return ExprError();
Sebastian Redl972041f2009-04-27 20:27:31 +0000599 }
600
John McCallac418162010-04-22 01:10:34 +0000601 // Initialize the exception result. This implicitly weeds out
602 // abstract types or types with inaccessible copy constructors.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000603
604 // C++0x [class.copymove]p31:
605 // When certain criteria are met, an implementation is allowed to omit the
606 // copy/move construction of a class object [...]
607 //
608 // - in a throw-expression, when the operand is the name of a
609 // non-volatile automatic object (other than a function or catch-clause
610 // parameter) whose scope does not extend beyond the end of the
611 // innermost enclosing try-block (if there is one), the copy/move
612 // operation from the operand to the exception object (15.1) can be
613 // omitted by constructing the automatic object directly into the
614 // exception object
615 const VarDecl *NRVOVariable = 0;
616 if (IsThrownVarInScope)
617 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
618
John McCallac418162010-04-22 01:10:34 +0000619 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000620 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregorbca01b42011-07-06 22:04:06 +0000621 /*NRVO=*/NRVOVariable != 0);
John Wiegley429bb272011-04-08 18:41:53 +0000622 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000623 QualType(), E,
624 IsThrownVarInScope);
John McCallac418162010-04-22 01:10:34 +0000625 if (Res.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000626 return ExprError();
627 E = Res.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000628
Eli Friedman5ed9b932010-06-03 20:39:03 +0000629 // If the exception has class type, we need additional handling.
630 const RecordType *RecordTy = Ty->getAs<RecordType>();
631 if (!RecordTy)
John Wiegley429bb272011-04-08 18:41:53 +0000632 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000633 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
634
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000635 // If we are throwing a polymorphic class type or pointer thereof,
636 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000637 MarkVTableUsed(ThrowLoc, RD);
638
Eli Friedman98efb9f2010-10-12 20:32:36 +0000639 // If a pointer is thrown, the referenced object will not be destroyed.
640 if (isPointer)
John Wiegley429bb272011-04-08 18:41:53 +0000641 return Owned(E);
Eli Friedman98efb9f2010-10-12 20:32:36 +0000642
Richard Smith213d70b2012-02-18 04:13:32 +0000643 // If the class has a destructor, we must be able to call it.
644 if (RD->hasIrrelevantDestructor())
John Wiegley429bb272011-04-08 18:41:53 +0000645 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000646
Sebastian Redl28357452012-03-05 19:35:43 +0000647 CXXDestructorDecl *Destructor = LookupDestructor(RD);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000648 if (!Destructor)
John Wiegley429bb272011-04-08 18:41:53 +0000649 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000650
Eli Friedman5f2987c2012-02-02 03:46:19 +0000651 MarkFunctionReferenced(E->getExprLoc(), Destructor);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000652 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000653 PDiag(diag::err_access_dtor_exception) << Ty);
Richard Smith213d70b2012-02-18 04:13:32 +0000654 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
John Wiegley429bb272011-04-08 18:41:53 +0000655 return Owned(E);
Chris Lattner50dd2892008-02-26 00:51:44 +0000656}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000657
Eli Friedman72899c32012-01-07 04:59:52 +0000658QualType Sema::getCurrentThisType() {
659 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000660 QualType ThisTy = CXXThisTypeOverride;
Richard Smith7a614d82011-06-11 17:19:42 +0000661 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
662 if (method && method->isInstance())
663 ThisTy = method->getThisType(Context);
Richard Smith7a614d82011-06-11 17:19:42 +0000664 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000665
Richard Smith7a614d82011-06-11 17:19:42 +0000666 return ThisTy;
John McCall5808ce42011-02-03 08:15:49 +0000667}
668
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000669Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
670 Decl *ContextDecl,
671 unsigned CXXThisTypeQuals,
672 bool Enabled)
673 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
674{
675 if (!Enabled || !ContextDecl)
676 return;
677
678 CXXRecordDecl *Record = 0;
679 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
680 Record = Template->getTemplatedDecl();
681 else
682 Record = cast<CXXRecordDecl>(ContextDecl);
683
684 S.CXXThisTypeOverride
685 = S.Context.getPointerType(
686 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
687
688 this->Enabled = true;
689}
690
691
692Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
693 if (Enabled) {
694 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
695 }
696}
697
Douglas Gregora1f21142012-02-01 17:04:21 +0000698void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) {
Eli Friedman72899c32012-01-07 04:59:52 +0000699 // We don't need to capture this in an unevaluated context.
Douglas Gregora1f21142012-02-01 17:04:21 +0000700 if (ExprEvalContexts.back().Context == Unevaluated && !Explicit)
Eli Friedman72899c32012-01-07 04:59:52 +0000701 return;
702
703 // Otherwise, check that we can capture 'this'.
704 unsigned NumClosures = 0;
705 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000706 if (CapturingScopeInfo *CSI =
707 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
708 if (CSI->CXXThisCaptureIndex != 0) {
709 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman72899c32012-01-07 04:59:52 +0000710 break;
711 }
Douglas Gregora1f21142012-02-01 17:04:21 +0000712
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000713 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000714 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregora1f21142012-02-01 17:04:21 +0000715 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
716 Explicit) {
717 // This closure can capture 'this'; continue looking upwards.
Eli Friedman72899c32012-01-07 04:59:52 +0000718 NumClosures++;
Douglas Gregora1f21142012-02-01 17:04:21 +0000719 Explicit = false;
Eli Friedman72899c32012-01-07 04:59:52 +0000720 continue;
721 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000722 // This context can't implicitly capture 'this'; fail out.
Douglas Gregora1f21142012-02-01 17:04:21 +0000723 Diag(Loc, diag::err_this_capture) << Explicit;
Eli Friedman72899c32012-01-07 04:59:52 +0000724 return;
725 }
Eli Friedman72899c32012-01-07 04:59:52 +0000726 break;
727 }
728
729 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
730 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
731 // contexts.
732 for (unsigned idx = FunctionScopes.size() - 1;
733 NumClosures; --idx, --NumClosures) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000734 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Eli Friedman668165a2012-02-11 02:51:16 +0000735 Expr *ThisExpr = 0;
Douglas Gregor999713e2012-02-18 09:37:24 +0000736 QualType ThisTy = getCurrentThisType();
Eli Friedman668165a2012-02-11 02:51:16 +0000737 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
738 // For lambda expressions, build a field and an initializing expression.
Eli Friedman668165a2012-02-11 02:51:16 +0000739 CXXRecordDecl *Lambda = LSI->Lambda;
740 FieldDecl *Field
741 = FieldDecl::Create(Context, Lambda, Loc, Loc, 0, ThisTy,
742 Context.getTrivialTypeSourceInfo(ThisTy, Loc),
743 0, false, false);
744 Field->setImplicit(true);
745 Field->setAccess(AS_private);
746 Lambda->addDecl(Field);
747 ThisExpr = new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/true);
748 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000749 bool isNested = NumClosures > 1;
Douglas Gregor999713e2012-02-18 09:37:24 +0000750 CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
Eli Friedman72899c32012-01-07 04:59:52 +0000751 }
752}
753
Richard Smith7a614d82011-06-11 17:19:42 +0000754ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000755 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
756 /// is a non-lvalue expression whose value is the address of the object for
757 /// which the function is called.
758
Douglas Gregor341350e2011-10-18 16:47:30 +0000759 QualType ThisTy = getCurrentThisType();
Richard Smith7a614d82011-06-11 17:19:42 +0000760 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000761
Eli Friedman72899c32012-01-07 04:59:52 +0000762 CheckCXXThisCapture(Loc);
Richard Smith7a614d82011-06-11 17:19:42 +0000763 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000764}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000765
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000766bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
767 // If we're outside the body of a member function, then we'll have a specified
768 // type for 'this'.
769 if (CXXThisTypeOverride.isNull())
770 return false;
771
772 // Determine whether we're looking into a class that's currently being
773 // defined.
774 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
775 return Class && Class->isBeingDefined();
776}
777
John McCall60d7b3a2010-08-24 06:29:42 +0000778ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000779Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000780 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000781 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000782 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000783 if (!TypeRep)
784 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000785
John McCall9d125032010-01-15 18:39:57 +0000786 TypeSourceInfo *TInfo;
787 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
788 if (!TInfo)
789 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000790
791 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
792}
793
794/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
795/// Can be interpreted either as function-style casting ("int(x)")
796/// or class type construction ("ClassType(x,y,z)")
797/// or creation of a value-initialized type ("int()").
798ExprResult
799Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
800 SourceLocation LParenLoc,
801 MultiExprArg exprs,
802 SourceLocation RParenLoc) {
803 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000804 unsigned NumExprs = exprs.size();
805 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000806 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000807
Sebastian Redlf53597f2009-03-15 17:47:39 +0000808 if (Ty->isDependentType() ||
Ahmed Charles13a140c2012-02-25 11:00:22 +0000809 CallExpr::hasAnyTypeDependentArguments(
810 llvm::makeArrayRef(Exprs, NumExprs))) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000811 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Douglas Gregorab6677e2010-09-08 00:15:04 +0000813 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000814 LParenLoc,
815 Exprs, NumExprs,
816 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000817 }
818
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000819 bool ListInitialization = LParenLoc.isInvalid();
820 assert((!ListInitialization || (NumExprs == 1 && isa<InitListExpr>(Exprs[0])))
821 && "List initialization must have initializer list as expression.");
822 SourceRange FullRange = SourceRange(TyBeginLoc,
823 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
824
Douglas Gregor506ae412009-01-16 18:33:17 +0000825 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000826 // If the expression list is a single expression, the type conversion
827 // expression is equivalent (in definedness, and if defined in meaning) to the
828 // corresponding cast expression.
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000829 if (NumExprs == 1 && !ListInitialization) {
John McCallb45ae252011-10-05 07:41:44 +0000830 Expr *Arg = Exprs[0];
Anders Carlsson0aebc812009-09-09 21:33:21 +0000831 exprs.release();
John McCallb45ae252011-10-05 07:41:44 +0000832 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000833 }
834
Eli Friedmanc60ccf52012-02-29 00:00:28 +0000835 QualType ElemTy = Ty;
836 if (Ty->isArrayType()) {
837 if (!ListInitialization)
838 return ExprError(Diag(TyBeginLoc,
839 diag::err_value_init_for_array_type) << FullRange);
840 ElemTy = Context.getBaseElementType(Ty);
841 }
842
843 if (!Ty->isVoidType() &&
844 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregord10099e2012-05-04 16:32:21 +0000845 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedmanc60ccf52012-02-29 00:00:28 +0000846 return ExprError();
847
848 if (RequireNonAbstractType(TyBeginLoc, Ty,
849 diag::err_allocation_of_abstract_type))
850 return ExprError();
851
Douglas Gregor19311e72010-09-08 21:40:08 +0000852 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
853 InitializationKind Kind
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000854 = NumExprs ? ListInitialization
855 ? InitializationKind::CreateDirectList(TyBeginLoc)
856 : InitializationKind::CreateDirect(TyBeginLoc,
857 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000858 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000859 LParenLoc, RParenLoc);
860 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
861 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000862
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000863 if (!Result.isInvalid() && ListInitialization &&
864 isa<InitListExpr>(Result.get())) {
865 // If the list-initialization doesn't involve a constructor call, we'll get
866 // the initializer-list (with corrected type) back, but that's not what we
867 // want, since it will be treated as an initializer list in further
868 // processing. Explicitly insert a cast here.
869 InitListExpr *List = cast<InitListExpr>(Result.take());
870 Result = Owned(CXXFunctionalCastExpr::Create(Context, List->getType(),
871 Expr::getValueKindForType(TInfo->getType()),
872 TInfo, TyBeginLoc, CK_NoOp,
873 List, /*Path=*/0, RParenLoc));
874 }
875
Douglas Gregor19311e72010-09-08 21:40:08 +0000876 // FIXME: Improve AST representation?
877 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000878}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000879
John McCall6ec278d2011-01-27 09:37:56 +0000880/// doesUsualArrayDeleteWantSize - Answers whether the usual
881/// operator delete[] for the given type has a size_t parameter.
882static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
883 QualType allocType) {
884 const RecordType *record =
885 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
886 if (!record) return false;
887
888 // Try to find an operator delete[] in class scope.
889
890 DeclarationName deleteName =
891 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
892 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
893 S.LookupQualifiedName(ops, record->getDecl());
894
895 // We're just doing this for information.
896 ops.suppressDiagnostics();
897
898 // Very likely: there's no operator delete[].
899 if (ops.empty()) return false;
900
901 // If it's ambiguous, it should be illegal to call operator delete[]
902 // on this thing, so it doesn't matter if we allocate extra space or not.
903 if (ops.isAmbiguous()) return false;
904
905 LookupResult::Filter filter = ops.makeFilter();
906 while (filter.hasNext()) {
907 NamedDecl *del = filter.next()->getUnderlyingDecl();
908
909 // C++0x [basic.stc.dynamic.deallocation]p2:
910 // A template instance is never a usual deallocation function,
911 // regardless of its signature.
912 if (isa<FunctionTemplateDecl>(del)) {
913 filter.erase();
914 continue;
915 }
916
917 // C++0x [basic.stc.dynamic.deallocation]p2:
918 // If class T does not declare [an operator delete[] with one
919 // parameter] but does declare a member deallocation function
920 // named operator delete[] with exactly two parameters, the
921 // second of which has type std::size_t, then this function
922 // is a usual deallocation function.
923 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
924 filter.erase();
925 continue;
926 }
927 }
928 filter.done();
929
930 if (!ops.isSingleResult()) return false;
931
932 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
933 return (del->getNumParams() == 2);
934}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000935
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000936/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
937
938/// E.g.:
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000939/// @code new (memory) int[size][4] @endcode
940/// or
941/// @code ::new Foo(23, "hello") @endcode
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000942///
943/// \param StartLoc The first location of the expression.
944/// \param UseGlobal True if 'new' was prefixed with '::'.
945/// \param PlacementLParen Opening paren of the placement arguments.
946/// \param PlacementArgs Placement new arguments.
947/// \param PlacementRParen Closing paren of the placement arguments.
948/// \param TypeIdParens If the type is in parens, the source range.
949/// \param D The type to be allocated, as well as array dimensions.
950/// \param ConstructorLParen Opening paren of the constructor args, empty if
951/// initializer-list syntax is used.
952/// \param ConstructorArgs Constructor/initialization arguments.
953/// \param ConstructorRParen Closing paren of the constructor args.
John McCall60d7b3a2010-08-24 06:29:42 +0000954ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000955Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000956 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000957 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000958 Declarator &D, Expr *Initializer) {
Richard Smith34b41d92011-02-20 03:19:35 +0000959 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
960
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000961 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000962 // If the specified type is an array, unwrap it and save the expression.
963 if (D.getNumTypeObjects() > 0 &&
964 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
965 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000966 if (TypeContainsAuto)
967 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
968 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000969 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000970 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
971 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000972 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000973 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
974 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000975
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000976 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000977 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000978 }
979
Douglas Gregor043cad22009-09-11 00:18:58 +0000980 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000981 if (ArraySize) {
982 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000983 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
984 break;
985
986 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
987 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smith282e7e62012-02-04 09:53:13 +0000988 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Douglas Gregorab41fe92012-05-04 22:38:52 +0000989 Array.NumElts
990 = VerifyIntegerConstantExpression(NumElts, 0,
991 diag::err_new_array_nonconst)
992 .take();
Richard Smith282e7e62012-02-04 09:53:13 +0000993 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()) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00001157 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1158 Expr *ArraySize;
1159
1160 public:
1161 SizeConvertDiagnoser(Expr *ArraySize)
1162 : ICEConvertDiagnoser(false, false), ArraySize(ArraySize) { }
1163
1164 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1165 QualType T) {
1166 return S.Diag(Loc, diag::err_array_size_not_integral)
1167 << S.getLangOpts().CPlusPlus0x << T;
1168 }
1169
1170 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
1171 QualType T) {
1172 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1173 << T << ArraySize->getSourceRange();
1174 }
1175
1176 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
1177 SourceLocation Loc,
1178 QualType T,
1179 QualType ConvTy) {
1180 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1181 }
1182
1183 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
1184 CXXConversionDecl *Conv,
1185 QualType ConvTy) {
1186 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1187 << ConvTy->isEnumeralType() << ConvTy;
1188 }
1189
1190 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
1191 QualType T) {
1192 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1193 }
1194
1195 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
1196 QualType ConvTy) {
1197 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1198 << ConvTy->isEnumeralType() << ConvTy;
1199 }
1200
1201 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1202 QualType T,
1203 QualType ConvTy) {
1204 return S.Diag(Loc,
1205 S.getLangOpts().CPlusPlus0x
1206 ? diag::warn_cxx98_compat_array_size_conversion
1207 : diag::ext_array_size_conversion)
1208 << T << ConvTy->isEnumeralType() << ConvTy;
1209 }
1210 } SizeDiagnoser(ArraySize);
1211
1212 ExprResult ConvertedSize
1213 = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize, SizeDiagnoser,
1214 /*AllowScopedEnumerations*/ false);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001215 if (ConvertedSize.isInvalid())
1216 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001217
John McCall9ae2f072010-08-23 23:25:46 +00001218 ArraySize = ConvertedSize.take();
John McCall806054d2012-01-11 00:14:46 +00001219 QualType SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001220 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001221 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001222
Richard Smith0b458fd2012-02-04 05:35:53 +00001223 // C++98 [expr.new]p7:
1224 // The expression in a direct-new-declarator shall have integral type
1225 // with a non-negative value.
1226 //
1227 // Let's see if this is a constant < 0. If so, we reject it out of
1228 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1229 // array type.
1230 //
1231 // Note: such a construct has well-defined semantics in C++11: it throws
1232 // std::bad_array_new_length.
Sebastian Redl28507842009-02-26 14:39:58 +00001233 if (!ArraySize->isValueDependent()) {
1234 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +00001235 // We've already performed any required implicit conversion to integer or
1236 // unscoped enumeration type.
Richard Smith0b458fd2012-02-04 05:35:53 +00001237 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Sebastian Redl28507842009-02-26 14:39:58 +00001238 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001239 llvm::APInt::getNullValue(Value.getBitWidth()),
Richard Smith0b458fd2012-02-04 05:35:53 +00001240 Value.isUnsigned())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001241 if (getLangOpts().CPlusPlus0x)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001242 Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001243 diag::warn_typecheck_negative_array_new_size)
Douglas Gregor2767ce22010-08-18 00:39:00 +00001244 << ArraySize->getSourceRange();
Richard Smith0b458fd2012-02-04 05:35:53 +00001245 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00001246 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001247 diag::err_typecheck_negative_array_size)
1248 << ArraySize->getSourceRange());
1249 } else if (!AllocType->isDependentType()) {
1250 unsigned ActiveSizeBits =
1251 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1252 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001253 if (getLangOpts().CPlusPlus0x)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001254 Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001255 diag::warn_array_new_too_large)
1256 << Value.toString(10)
1257 << ArraySize->getSourceRange();
1258 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00001259 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001260 diag::err_array_too_large)
1261 << Value.toString(10)
1262 << ArraySize->getSourceRange());
Douglas Gregor2767ce22010-08-18 00:39:00 +00001263 }
1264 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001265 } else if (TypeIdParens.isValid()) {
1266 // Can't have dynamic array size when the type-id is in parentheses.
1267 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1268 << ArraySize->getSourceRange()
1269 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1270 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001271
Douglas Gregor4bd40312010-07-13 15:54:32 +00001272 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001273 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001274 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001275
John McCallf85e1932011-06-15 23:02:42 +00001276 // ARC: warn about ABI issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00001277 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001278 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1279 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1280 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1281 << 0 << BaseAllocType;
1282 }
1283
John McCall7d166272011-05-15 07:14:44 +00001284 // Note that we do *not* convert the argument in any way. It can
1285 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001286 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001287
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001288 FunctionDecl *OperatorNew = 0;
1289 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001290 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1291 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001292
Sebastian Redl28507842009-02-26 14:39:58 +00001293 if (!AllocType->isDependentType() &&
Ahmed Charles13a140c2012-02-25 11:00:22 +00001294 !Expr::hasAnyTypeDependentArguments(
1295 llvm::makeArrayRef(PlaceArgs, NumPlaceArgs)) &&
Sebastian Redl28507842009-02-26 14:39:58 +00001296 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001297 SourceRange(PlacementLParen, PlacementRParen),
1298 UseGlobal, AllocType, ArraySize, PlaceArgs,
1299 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001300 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001301
1302 // If this is an array allocation, compute whether the usual array
1303 // deallocation function for the type has a size_t parameter.
1304 bool UsualArrayDeleteWantsSize = false;
1305 if (ArraySize && !AllocType->isDependentType())
1306 UsualArrayDeleteWantsSize
1307 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1308
Chris Lattner5f9e2722011-07-23 10:55:15 +00001309 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001310 if (OperatorNew) {
1311 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001312 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001313 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001314 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001315 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001316
Anders Carlsson28e94832010-05-03 02:07:56 +00001317 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001318 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001319 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001320 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001321
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001322 NumPlaceArgs = AllPlaceArgs.size();
1323 if (NumPlaceArgs > 0)
1324 PlaceArgs = &AllPlaceArgs[0];
Eli Friedmane61eb042012-02-18 04:48:30 +00001325
1326 DiagnoseSentinelCalls(OperatorNew, PlacementLParen,
1327 PlaceArgs, NumPlaceArgs);
1328
1329 // FIXME: Missing call to CheckFunctionCall or equivalent
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001330 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001331
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001332 // Warn if the type is over-aligned and is being allocated by global operator
1333 // new.
Nick Lewycky507a8a32012-02-04 03:30:14 +00001334 if (NumPlaceArgs == 0 && OperatorNew &&
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001335 (OperatorNew->isImplicit() ||
1336 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1337 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1338 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1339 if (Align > SuitableAlign)
1340 Diag(StartLoc, diag::warn_overaligned_type)
1341 << AllocType
1342 << unsigned(Align / Context.getCharWidth())
1343 << unsigned(SuitableAlign / Context.getCharWidth());
1344 }
1345 }
1346
Sebastian Redlbd45d252012-02-16 12:59:47 +00001347 QualType InitType = AllocType;
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001348 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlbd45d252012-02-16 12:59:47 +00001349 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1350 // dialect distinction.
1351 if (ResultType->isArrayType() || ArraySize) {
1352 if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1353 SourceRange InitRange(Inits[0]->getLocStart(),
1354 Inits[NumInits - 1]->getLocEnd());
1355 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1356 return ExprError();
1357 }
1358 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1359 // We do the initialization typechecking against the array type
1360 // corresponding to the number of initializers + 1 (to also check
1361 // default-initialization).
1362 unsigned NumElements = ILE->getNumInits() + 1;
1363 InitType = Context.getConstantArrayType(AllocType,
1364 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1365 ArrayType::Normal, 0);
1366 }
Anders Carlsson48c95012010-05-03 15:45:23 +00001367 }
1368
Douglas Gregor99a2e602009-12-16 01:38:02 +00001369 if (!AllocType->isDependentType() &&
Ahmed Charles13a140c2012-02-25 11:00:22 +00001370 !Expr::hasAnyTypeDependentArguments(
1371 llvm::makeArrayRef(Inits, NumInits))) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001372 // C++11 [expr.new]p15:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001373 // A new-expression that creates an object of type T initializes that
1374 // object as follows:
1375 InitializationKind Kind
1376 // - If the new-initializer is omitted, the object is default-
1377 // initialized (8.5); if no initialization is performed,
1378 // the object has indeterminate value
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001379 = initStyle == CXXNewExpr::NoInit
1380 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001381 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001382 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001383 : initStyle == CXXNewExpr::ListInit
1384 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1385 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1386 DirectInitRange.getBegin(),
1387 DirectInitRange.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001388
Douglas Gregor99a2e602009-12-16 01:38:02 +00001389 InitializedEntity Entity
Sebastian Redlbd45d252012-02-16 12:59:47 +00001390 = InitializedEntity::InitializeNew(StartLoc, InitType);
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001391 InitializationSequence InitSeq(*this, Entity, Kind, Inits, NumInits);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001392 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001393 MultiExprArg(Inits, NumInits));
Douglas Gregor99a2e602009-12-16 01:38:02 +00001394 if (FullInit.isInvalid())
1395 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001396
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001397 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1398 // we don't want the initialized object to be destructed.
1399 if (CXXBindTemporaryExpr *Binder =
1400 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1401 FullInit = Owned(Binder->getSubExpr());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001402
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001403 Initializer = FullInit.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001404 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001405
Douglas Gregor6d908702010-02-26 05:06:18 +00001406 // Mark the new and delete operators as referenced.
1407 if (OperatorNew)
Eli Friedman5f2987c2012-02-02 03:46:19 +00001408 MarkFunctionReferenced(StartLoc, OperatorNew);
Douglas Gregor6d908702010-02-26 05:06:18 +00001409 if (OperatorDelete)
Eli Friedman5f2987c2012-02-02 03:46:19 +00001410 MarkFunctionReferenced(StartLoc, OperatorDelete);
Douglas Gregor6d908702010-02-26 05:06:18 +00001411
John McCall84ff0fc2011-07-13 20:12:57 +00001412 // C++0x [expr.new]p17:
1413 // If the new expression creates an array of objects of class type,
1414 // access and ambiguity control are done for the destructor.
David Blaikie426d6ca2012-03-10 23:40:02 +00001415 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1416 if (ArraySize && !BaseAllocType->isDependentType()) {
1417 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1418 if (CXXDestructorDecl *dtor = LookupDestructor(
1419 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1420 MarkFunctionReferenced(StartLoc, dtor);
1421 CheckDestructorAccess(StartLoc, dtor,
1422 PDiag(diag::err_access_dtor)
1423 << BaseAllocType);
1424 DiagnoseUseOfDecl(dtor, StartLoc);
1425 }
John McCall84ff0fc2011-07-13 20:12:57 +00001426 }
1427 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001428
Sebastian Redlf53597f2009-03-15 17:47:39 +00001429 PlacementArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001430
Ted Kremenekad7fe862010-02-11 22:51:03 +00001431 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001432 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001433 UsualArrayDeleteWantsSize,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001434 PlaceArgs, NumPlaceArgs, TypeIdParens,
1435 ArraySize, initStyle, Initializer,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001436 ResultType, AllocTypeInfo,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001437 StartLoc, DirectInitRange));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001438}
1439
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001440/// \brief Checks that a type is suitable as the allocated type
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001441/// in a new-expression.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001442bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001443 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001444 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1445 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001446 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001447 return Diag(Loc, diag::err_bad_new_type)
1448 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001449 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001450 return Diag(Loc, diag::err_bad_new_type)
1451 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001452 else if (!AllocType->isDependentType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001453 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001454 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001455 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001456 diag::err_allocation_of_abstract_type))
1457 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001458 else if (AllocType->isVariablyModifiedType())
1459 return Diag(Loc, diag::err_variably_modified_new_type)
1460 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001461 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1462 return Diag(Loc, diag::err_address_space_qualified_new)
1463 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikie4e4d0842012-03-11 07:00:24 +00001464 else if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001465 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1466 QualType BaseAllocType = Context.getBaseElementType(AT);
1467 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1468 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001469 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001470 << BaseAllocType;
1471 }
1472 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001473
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001474 return false;
1475}
1476
Douglas Gregor6d908702010-02-26 05:06:18 +00001477/// \brief Determine whether the given function is a non-placement
1478/// deallocation function.
1479static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1480 if (FD->isInvalidDecl())
1481 return false;
1482
1483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1484 return Method->isUsualDeallocationFunction();
1485
1486 return ((FD->getOverloadedOperator() == OO_Delete ||
1487 FD->getOverloadedOperator() == OO_Array_Delete) &&
1488 FD->getNumParams() == 1);
1489}
1490
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001491/// FindAllocationFunctions - Finds the overloads of operator new and delete
1492/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001493bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1494 bool UseGlobal, QualType AllocType,
1495 bool IsArray, Expr **PlaceArgs,
1496 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001497 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001498 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001499 // --- Choosing an allocation function ---
1500 // C++ 5.3.4p8 - 14 & 18
1501 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1502 // in the scope of the allocated class.
1503 // 2) If an array size is given, look for operator new[], else look for
1504 // operator new.
1505 // 3) The first argument is always size_t. Append the arguments from the
1506 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001507
Chris Lattner5f9e2722011-07-23 10:55:15 +00001508 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001509 // We don't care about the actual value of this argument.
1510 // FIXME: Should the Sema create the expression and embed it in the syntax
1511 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001512 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001513 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001514 Context.getSizeType(),
1515 SourceLocation());
1516 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001517 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1518
Douglas Gregor6d908702010-02-26 05:06:18 +00001519 // C++ [expr.new]p8:
1520 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001521 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001522 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001523 // type, the allocation function's name is operator new[] and the
1524 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001525 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1526 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001527 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1528 IsArray ? OO_Array_Delete : OO_Delete);
1529
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001530 QualType AllocElemType = Context.getBaseElementType(AllocType);
1531
1532 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001533 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001534 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001535 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001536 AllocArgs.size(), Record, /*AllowMissing=*/true,
1537 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001538 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001539 }
1540 if (!OperatorNew) {
1541 // Didn't find a member overload. Look for a global one.
1542 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001543 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001544 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001545 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1546 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001547 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001548 }
1549
John McCall9c82afc2010-04-20 02:18:25 +00001550 // We don't need an operator delete if we're running under
1551 // -fno-exceptions.
David Blaikie4e4d0842012-03-11 07:00:24 +00001552 if (!getLangOpts().Exceptions) {
John McCall9c82afc2010-04-20 02:18:25 +00001553 OperatorDelete = 0;
1554 return false;
1555 }
1556
Anders Carlssond9583892009-05-31 20:26:12 +00001557 // FindAllocationOverload can change the passed in arguments, so we need to
1558 // copy them back.
1559 if (NumPlaceArgs > 0)
1560 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Douglas Gregor6d908702010-02-26 05:06:18 +00001562 // C++ [expr.new]p19:
1563 //
1564 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001565 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001566 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001567 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001568 // the scope of T. If this lookup fails to find the name, or if
1569 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001570 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001571 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001572 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001573 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001574 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001575 LookupQualifiedName(FoundDelete, RD);
1576 }
John McCall90c8c572010-03-18 08:19:33 +00001577 if (FoundDelete.isAmbiguous())
1578 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001579
1580 if (FoundDelete.empty()) {
1581 DeclareGlobalNewDelete();
1582 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1583 }
1584
1585 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001586
Chris Lattner5f9e2722011-07-23 10:55:15 +00001587 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001588
John McCalledeb6c92010-09-14 21:34:24 +00001589 // Whether we're looking for a placement operator delete is dictated
1590 // by whether we selected a placement operator new, not by whether
1591 // we had explicit placement arguments. This matters for things like
1592 // struct A { void *operator new(size_t, int = 0); ... };
1593 // A *a = new A()
1594 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1595
1596 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001597 // C++ [expr.new]p20:
1598 // A declaration of a placement deallocation function matches the
1599 // declaration of a placement allocation function if it has the
1600 // same number of parameters and, after parameter transformations
1601 // (8.3.5), all parameter types except the first are
1602 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001603 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001604 // To perform this comparison, we compute the function type that
1605 // the deallocation function should have, and use that type both
1606 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001607 //
1608 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001609 QualType ExpectedFunctionType;
1610 {
1611 const FunctionProtoType *Proto
1612 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001613
Chris Lattner5f9e2722011-07-23 10:55:15 +00001614 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001615 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001616 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1617 ArgTypes.push_back(Proto->getArgType(I));
1618
John McCalle23cf432010-12-14 08:05:40 +00001619 FunctionProtoType::ExtProtoInfo EPI;
1620 EPI.Variadic = Proto->isVariadic();
1621
Douglas Gregor6d908702010-02-26 05:06:18 +00001622 ExpectedFunctionType
1623 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001624 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001625 }
1626
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001627 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001628 DEnd = FoundDelete.end();
1629 D != DEnd; ++D) {
1630 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001631 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001632 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1633 // Perform template argument deduction to try to match the
1634 // expected function type.
1635 TemplateDeductionInfo Info(Context, StartLoc);
1636 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1637 continue;
1638 } else
1639 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1640
1641 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001642 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001643 }
1644 } else {
1645 // C++ [expr.new]p20:
1646 // [...] Any non-placement deallocation function matches a
1647 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001648 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001649 DEnd = FoundDelete.end();
1650 D != DEnd; ++D) {
1651 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1652 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001653 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001654 }
1655 }
1656
1657 // C++ [expr.new]p20:
1658 // [...] If the lookup finds a single matching deallocation
1659 // function, that function will be called; otherwise, no
1660 // deallocation function will be called.
1661 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001662 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001663
1664 // C++0x [expr.new]p20:
1665 // If the lookup finds the two-parameter form of a usual
1666 // deallocation function (3.7.4.2) and that function, considered
1667 // as a placement deallocation function, would have been
1668 // selected as a match for the allocation function, the program
1669 // is ill-formed.
David Blaikie4e4d0842012-03-11 07:00:24 +00001670 if (NumPlaceArgs && getLangOpts().CPlusPlus0x &&
Douglas Gregor6d908702010-02-26 05:06:18 +00001671 isNonPlacementDeallocationFunction(OperatorDelete)) {
1672 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001673 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001674 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1675 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1676 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001677 } else {
1678 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001679 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001680 }
1681 }
1682
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001683 return false;
1684}
1685
Sebastian Redl7f662392008-12-04 22:20:51 +00001686/// FindAllocationOverload - Find an fitting overload for the allocation
1687/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001688bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1689 DeclarationName Name, Expr** Args,
1690 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001691 bool AllowMissing, FunctionDecl *&Operator,
1692 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001693 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1694 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001695 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001696 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001697 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001698 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001699 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001700 }
1701
John McCall90c8c572010-03-18 08:19:33 +00001702 if (R.isAmbiguous())
1703 return true;
1704
1705 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001706
John McCall5769d612010-02-08 23:07:23 +00001707 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001708 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001709 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001710 // Even member operator new/delete are implicitly treated as
1711 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001712 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001713
John McCall9aa472c2010-03-19 07:35:19 +00001714 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1715 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001716 /*ExplicitTemplateArgs=*/0,
1717 llvm::makeArrayRef(Args, NumArgs),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001718 Candidates,
1719 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001720 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001721 }
1722
John McCall9aa472c2010-03-19 07:35:19 +00001723 FunctionDecl *Fn = cast<FunctionDecl>(D);
Ahmed Charles13a140c2012-02-25 11:00:22 +00001724 AddOverloadCandidate(Fn, Alloc.getPair(),
1725 llvm::makeArrayRef(Args, NumArgs), Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001726 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001727 }
1728
1729 // Do the resolution.
1730 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001731 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001732 case OR_Success: {
1733 // Got one!
1734 FunctionDecl *FnDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00001735 MarkFunctionReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001736 // The first argument is size_t, and the first parameter must be size_t,
1737 // too. This is checked on declaration and can be assumed. (It can't be
1738 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001739 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001740 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1741 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001742 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1743 FnDecl->getParamDecl(i));
1744
1745 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1746 return true;
1747
John McCall60d7b3a2010-08-24 06:29:42 +00001748 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001749 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001750 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001751 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001752
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001753 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001754 }
Richard Smith9a561d52012-02-26 09:11:52 +00001755
Sebastian Redl7f662392008-12-04 22:20:51 +00001756 Operator = FnDecl;
Richard Smith9a561d52012-02-26 09:11:52 +00001757
1758 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1759 Best->FoundDecl, Diagnose) == AR_inaccessible)
1760 return true;
1761
Sebastian Redl7f662392008-12-04 22:20:51 +00001762 return false;
1763 }
1764
1765 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001766 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001767 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1768 << Name << Range;
Ahmed Charles13a140c2012-02-25 11:00:22 +00001769 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1770 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruth361d3802011-06-08 10:26:03 +00001771 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001772 return true;
1773
1774 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001775 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001776 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1777 << Name << Range;
Ahmed Charles13a140c2012-02-25 11:00:22 +00001778 Candidates.NoteCandidates(*this, OCD_ViableCandidates,
1779 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruth361d3802011-06-08 10:26:03 +00001780 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001781 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001782
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001783 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001784 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001785 Diag(StartLoc, diag::err_ovl_deleted_call)
1786 << Best->Function->isDeleted()
1787 << Name
1788 << getDeletedOrUnavailableSuffix(Best->Function)
1789 << Range;
Ahmed Charles13a140c2012-02-25 11:00:22 +00001790 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1791 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruth361d3802011-06-08 10:26:03 +00001792 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001793 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001794 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001795 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001796 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001797}
1798
1799
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001800/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1801/// delete. These are:
1802/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001803/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001804/// void* operator new(std::size_t) throw(std::bad_alloc);
1805/// void* operator new[](std::size_t) throw(std::bad_alloc);
1806/// void operator delete(void *) throw();
1807/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001808/// // C++0x:
1809/// void* operator new(std::size_t);
1810/// void* operator new[](std::size_t);
1811/// void operator delete(void *);
1812/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001813/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001814/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001815/// Note that the placement and nothrow forms of new are *not* implicitly
1816/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001817void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001818 if (GlobalNewDeleteDeclared)
1819 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001820
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001821 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001822 // [...] The following allocation and deallocation functions (18.4) are
1823 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001824 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001825 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001826 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001827 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001828 // void* operator new[](std::size_t) throw(std::bad_alloc);
1829 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001830 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001831 // C++0x:
1832 // void* operator new(std::size_t);
1833 // void* operator new[](std::size_t);
1834 // void operator delete(void*);
1835 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001836 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001837 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001838 // new, operator new[], operator delete, operator delete[].
1839 //
1840 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1841 // "std" or "bad_alloc" as necessary to form the exception specification.
1842 // However, we do not make these implicit declarations visible to name
1843 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001844 // Note that the C++0x versions of operator delete are deallocation functions,
1845 // and thus are implicitly noexcept.
David Blaikie4e4d0842012-03-11 07:00:24 +00001846 if (!StdBadAlloc && !getLangOpts().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001847 // The "std::bad_alloc" class has not yet been declared, so build it
1848 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001849 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1850 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001851 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001852 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001853 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001854 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001855 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001856
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001857 GlobalNewDeleteDeclared = true;
1858
1859 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1860 QualType SizeT = Context.getSizeType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001861 bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001862
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001863 DeclareGlobalAllocationFunction(
1864 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001865 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001866 DeclareGlobalAllocationFunction(
1867 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001868 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001869 DeclareGlobalAllocationFunction(
1870 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1871 Context.VoidTy, VoidPtr);
1872 DeclareGlobalAllocationFunction(
1873 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1874 Context.VoidTy, VoidPtr);
1875}
1876
1877/// DeclareGlobalAllocationFunction - Declares a single implicit global
1878/// allocation function if it doesn't already exist.
1879void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001880 QualType Return, QualType Argument,
1881 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001882 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1883
1884 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001885 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001886 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001887 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001888 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001889 // Only look at non-template functions, as it is the predefined,
1890 // non-templated allocation function we are trying to declare here.
1891 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1892 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001893 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001894 Func->getParamDecl(0)->getType().getUnqualifiedType());
1895 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001896 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1897 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001898 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001899 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001900 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001901 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001902 }
1903 }
1904
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001905 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001906 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001907 = (Name.getCXXOverloadedOperator() == OO_New ||
1908 Name.getCXXOverloadedOperator() == OO_Array_New);
David Blaikie4e4d0842012-03-11 07:00:24 +00001909 if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001910 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001911 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001912 }
John McCalle23cf432010-12-14 08:05:40 +00001913
1914 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001915 if (HasBadAllocExceptionSpec) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001916 if (!getLangOpts().CPlusPlus0x) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001917 EPI.ExceptionSpecType = EST_Dynamic;
1918 EPI.NumExceptions = 1;
1919 EPI.Exceptions = &BadAllocType;
1920 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001921 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00001922 EPI.ExceptionSpecType = getLangOpts().CPlusPlus0x ?
Sebastian Redl8999fe12011-03-14 18:08:30 +00001923 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001924 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001925
John McCalle23cf432010-12-14 08:05:40 +00001926 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001927 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001928 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1929 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001930 FnType, /*TInfo=*/0, SC_None,
1931 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001932 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001933
Nuno Lopesfc284482009-12-16 16:59:22 +00001934 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001935 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001936
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001937 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001938 SourceLocation(), 0,
1939 Argument, /*TInfo=*/0,
1940 SC_None, SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00001941 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001942
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001943 // FIXME: Also add this declaration to the IdentifierResolver, but
1944 // make sure it is at the end of the chain to coincide with the
1945 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001946 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001947}
1948
Anders Carlsson78f74552009-11-15 18:45:20 +00001949bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1950 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001951 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001952 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001953 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001954 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001955
John McCalla24dc2e2009-11-17 02:14:36 +00001956 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001957 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001958
Chandler Carruth23893242010-06-28 00:30:51 +00001959 Found.suppressDiagnostics();
1960
Chris Lattner5f9e2722011-07-23 10:55:15 +00001961 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001962 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1963 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001964 NamedDecl *ND = (*F)->getUnderlyingDecl();
1965
1966 // Ignore template operator delete members from the check for a usual
1967 // deallocation function.
1968 if (isa<FunctionTemplateDecl>(ND))
1969 continue;
1970
1971 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001972 Matches.push_back(F.getPair());
1973 }
1974
1975 // There's exactly one suitable operator; pick it.
1976 if (Matches.size() == 1) {
1977 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001978
1979 if (Operator->isDeleted()) {
1980 if (Diagnose) {
1981 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +00001982 NoteDeletedFunction(Operator);
Sean Hunt2be7e902011-05-12 22:46:29 +00001983 }
1984 return true;
1985 }
1986
Richard Smith9a561d52012-02-26 09:11:52 +00001987 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1988 Matches[0], Diagnose) == AR_inaccessible)
1989 return true;
1990
John McCall046a7462010-08-04 00:31:26 +00001991 return false;
1992
1993 // We found multiple suitable operators; complain about the ambiguity.
1994 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001995 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001996 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1997 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001998
Chris Lattner5f9e2722011-07-23 10:55:15 +00001999 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00002000 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
2001 Diag((*F)->getUnderlyingDecl()->getLocation(),
2002 diag::note_member_declared_here) << Name;
2003 }
John McCall046a7462010-08-04 00:31:26 +00002004 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00002005 }
2006
2007 // We did find operator delete/operator delete[] declarations, but
2008 // none of them were suitable.
2009 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00002010 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00002011 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2012 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002013
Sean Huntcb45a0f2011-05-12 22:46:25 +00002014 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2015 F != FEnd; ++F)
2016 Diag((*F)->getUnderlyingDecl()->getLocation(),
2017 diag::note_member_declared_here) << Name;
2018 }
Anders Carlsson78f74552009-11-15 18:45:20 +00002019 return true;
2020 }
2021
2022 // Look for a global declaration.
2023 DeclareGlobalNewDelete();
2024 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002025
Anders Carlsson78f74552009-11-15 18:45:20 +00002026 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
2027 Expr* DeallocArgs[1];
2028 DeallocArgs[0] = &Null;
2029 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00002030 DeallocArgs, 1, TUDecl, !Diagnose,
2031 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00002032 return true;
2033
2034 assert(Operator && "Did not find a deallocation function!");
2035 return false;
2036}
2037
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002038/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2039/// @code ::delete ptr; @endcode
2040/// or
2041/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00002042ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002043Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00002044 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002045 // C++ [expr.delete]p1:
2046 // The operand shall have a pointer type, or a class type having a single
2047 // conversion function to a pointer type. The result has type void.
2048 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002049 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2050
John Wiegley429bb272011-04-08 18:41:53 +00002051 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00002052 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002053 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00002054 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002055
John Wiegley429bb272011-04-08 18:41:53 +00002056 if (!Ex.get()->isTypeDependent()) {
John McCall5aba3eb2012-03-09 04:08:29 +00002057 // Perform lvalue-to-rvalue cast, if needed.
2058 Ex = DefaultLvalueConversion(Ex.take());
2059
John Wiegley429bb272011-04-08 18:41:53 +00002060 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002061
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002062 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002063 if (RequireCompleteType(StartLoc, Type,
Douglas Gregord10099e2012-05-04 16:32:21 +00002064 diag::err_delete_incomplete_class_type))
Douglas Gregor254a9422010-07-29 14:44:35 +00002065 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002066
Chris Lattner5f9e2722011-07-23 10:55:15 +00002067 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00002068
Fariborz Jahanian53462782009-09-11 21:44:33 +00002069 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002070 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002071 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002072 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00002073 NamedDecl *D = I.getDecl();
2074 if (isa<UsingShadowDecl>(D))
2075 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2076
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002077 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00002078 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002079 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002080
John McCall32daa422010-03-31 01:36:47 +00002081 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002082
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002083 QualType ConvType = Conv->getConversionType().getNonReferenceType();
2084 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00002085 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002086 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002087 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002088 if (ObjectPtrConversions.size() == 1) {
2089 // We have a single conversion to a pointer-to-object type. Perform
2090 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00002091 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00002092 ExprResult Res =
2093 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00002094 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00002095 AA_Converting);
2096 if (Res.isUsable()) {
2097 Ex = move(Res);
2098 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002099 }
2100 }
2101 else if (ObjectPtrConversions.size() > 1) {
2102 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002103 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00002104 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
2105 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002106 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002107 }
Sebastian Redl28507842009-02-26 14:39:58 +00002108 }
2109
Sebastian Redlf53597f2009-03-15 17:47:39 +00002110 if (!Type->isPointerType())
2111 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002112 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00002113
Ted Kremenek6217b802009-07-29 21:53:49 +00002114 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00002115 QualType PointeeElem = Context.getBaseElementType(Pointee);
2116
2117 if (unsigned AddressSpace = Pointee.getAddressSpace())
2118 return Diag(Ex.get()->getLocStart(),
2119 diag::err_address_space_qualified_delete)
2120 << Pointee.getUnqualifiedType() << AddressSpace;
2121
2122 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00002123 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002124 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00002125 // effectively bans deletion of "void*". However, most compilers support
2126 // this, so we treat it as a warning unless we're in a SFINAE context.
2127 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002128 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00002129 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00002130 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002131 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00002132 } else if (!Pointee->isDependentType()) {
2133 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregord10099e2012-05-04 16:32:21 +00002134 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmane52c9142011-07-26 22:25:31 +00002135 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2136 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2137 }
2138 }
2139
Douglas Gregor1070c9f2009-09-29 21:38:53 +00002140 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002141 // [Note: a pointer to a const type can be the operand of a
2142 // delete-expression; it is not necessary to cast away the constness
2143 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00002144 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00002145 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnara30bb4202011-11-16 15:42:13 +00002146 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
2147 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002148
2149 if (Pointee->isArrayType() && !ArrayForm) {
2150 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00002151 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002152 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2153 ArrayForm = true;
2154 }
2155
Anders Carlssond67c4c32009-08-16 20:29:29 +00002156 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2157 ArrayForm ? OO_Array_Delete : OO_Delete);
2158
Eli Friedmane52c9142011-07-26 22:25:31 +00002159 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002160 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00002161 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2162 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00002163 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002164
John McCall6ec278d2011-01-27 09:37:56 +00002165 // If we're allocating an array of records, check whether the
2166 // usual operator delete[] has a size_t parameter.
2167 if (ArrayForm) {
2168 // If the user specifically asked to use the global allocator,
2169 // we'll need to do the lookup into the class.
2170 if (UseGlobal)
2171 UsualArrayDeleteWantsSize =
2172 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2173
2174 // Otherwise, the usual operator delete[] should be the
2175 // function we just found.
2176 else if (isa<CXXMethodDecl>(OperatorDelete))
2177 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2178 }
2179
Richard Smith213d70b2012-02-18 04:13:32 +00002180 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmane52c9142011-07-26 22:25:31 +00002181 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002182 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002183 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00002184 DiagnoseUseOfDecl(Dtor, StartLoc);
2185 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00002186
2187 // C++ [expr.delete]p3:
2188 // In the first alternative (delete object), if the static type of the
2189 // object to be deleted is different from its dynamic type, the static
2190 // type shall be a base class of the dynamic type of the object to be
2191 // deleted and the static type shall have a virtual destructor or the
2192 // behavior is undefined.
2193 //
2194 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00002195 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00002196 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00002197 if (dtor && !dtor->isVirtual()) {
2198 if (PointeeRD->isAbstract()) {
2199 // If the class is abstract, we warn by default, because we're
2200 // sure the code has undefined behavior.
2201 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2202 << PointeeElem;
2203 } else if (!ArrayForm) {
2204 // Otherwise, if this is not an array delete, it's a bit suspect,
2205 // but not necessarily wrong.
2206 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2207 }
2208 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00002209 }
John McCallf85e1932011-06-15 23:02:42 +00002210
David Blaikie4e4d0842012-03-11 07:00:24 +00002211 } else if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002212 PointeeElem->isObjCLifetimeType() &&
2213 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
2214 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
2215 ArrayForm) {
2216 Diag(StartLoc, diag::warn_err_new_delete_object_array)
2217 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00002218 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002219
Anders Carlssond67c4c32009-08-16 20:29:29 +00002220 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00002221 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00002222 DeclareGlobalNewDelete();
2223 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00002224 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00002225 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00002226 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00002227 OperatorDelete))
2228 return ExprError();
2229 }
Mike Stump1eb44332009-09-09 15:08:12 +00002230
Eli Friedman5f2987c2012-02-02 03:46:19 +00002231 MarkFunctionReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00002232
Douglas Gregord880f522011-02-01 15:50:11 +00002233 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00002234 if (PointeeRD) {
2235 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00002236 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00002237 PDiag(diag::err_access_dtor) << PointeeElem);
2238 }
2239 }
2240
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002241 }
2242
Sebastian Redlf53597f2009-03-15 17:47:39 +00002243 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00002244 ArrayFormAsWritten,
2245 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00002246 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002247}
2248
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002249/// \brief Check the use of the given variable as a C++ condition in an if,
2250/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00002251ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00002252 SourceLocation StmtLoc,
2253 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002254 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002255
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002256 // C++ [stmt.select]p2:
2257 // The declarator shall not specify a function or an array.
2258 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002259 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002260 diag::err_invalid_use_of_function_type)
2261 << ConditionVar->getSourceRange());
2262 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002263 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002264 diag::err_invalid_use_of_array_type)
2265 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00002266
John Wiegley429bb272011-04-08 18:41:53 +00002267 ExprResult Condition =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002268 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2269 SourceLocation(),
2270 ConditionVar,
John McCallf4b88a42012-03-10 09:33:50 +00002271 /*enclosing*/ false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002272 ConditionVar->getLocation(),
2273 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00002274 VK_LValue));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002275
Eli Friedman5f2987c2012-02-02 03:46:19 +00002276 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002277
John Wiegley429bb272011-04-08 18:41:53 +00002278 if (ConvertToBoolean) {
2279 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2280 if (Condition.isInvalid())
2281 return ExprError();
2282 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002283
John Wiegley429bb272011-04-08 18:41:53 +00002284 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002285}
2286
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002287/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002288ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002289 // C++ 6.4p4:
2290 // The value of a condition that is an initialized declaration in a statement
2291 // other than a switch statement is the value of the declared variable
2292 // implicitly converted to type bool. If that conversion is ill-formed, the
2293 // program is ill-formed.
2294 // The value of a condition that is an expression is the value of the
2295 // expression, implicitly converted to bool.
2296 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002297 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002298}
Douglas Gregor77a52232008-09-12 00:47:35 +00002299
2300/// Helper function to determine whether this is the (deprecated) C++
2301/// conversion from a string literal to a pointer to non-const char or
2302/// non-const wchar_t (for narrow and wide string literals,
2303/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002304bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002305Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2306 // Look inside the implicit cast, if it exists.
2307 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2308 From = Cast->getSubExpr();
2309
2310 // A string literal (2.13.4) that is not a wide string literal can
2311 // be converted to an rvalue of type "pointer to char"; a wide
2312 // string literal can be converted to an rvalue of type "pointer
2313 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002314 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002315 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002316 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002317 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002318 // This conversion is considered only when there is an
2319 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002320 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2321 switch (StrLit->getKind()) {
2322 case StringLiteral::UTF8:
2323 case StringLiteral::UTF16:
2324 case StringLiteral::UTF32:
2325 // We don't allow UTF literals to be implicitly converted
2326 break;
2327 case StringLiteral::Ascii:
2328 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2329 ToPointeeType->getKind() == BuiltinType::Char_S);
2330 case StringLiteral::Wide:
2331 return ToPointeeType->isWideCharType();
2332 }
2333 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002334 }
2335
2336 return false;
2337}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002338
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002339static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002340 SourceLocation CastLoc,
2341 QualType Ty,
2342 CastKind Kind,
2343 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002344 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002345 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002346 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002347 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002348 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002349 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002350 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCallca0408f2010-08-23 06:44:23 +00002351 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002352
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002353 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00002354 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002355 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002356 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002357
John McCallb9abd8722012-04-07 03:04:20 +00002358 S.CheckConstructorAccess(CastLoc, Constructor,
2359 InitializedEntity::InitializeTemporary(Ty),
2360 Constructor->getAccess());
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002361
2362 ExprResult Result
2363 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2364 move_arg(ConstructorArgs),
2365 HadMultipleCandidates, /*ZeroInit*/ false,
2366 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002367 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002368 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002369
Douglas Gregorba70ab62010-04-16 22:17:36 +00002370 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2371 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002372
John McCall2de56d12010-08-25 11:45:40 +00002373 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002374 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002375
Douglas Gregorba70ab62010-04-16 22:17:36 +00002376 // Create an implicit call expr that calls it.
Eli Friedman3f01c8a2012-03-01 01:30:04 +00002377 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2378 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002379 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002380 if (Result.isInvalid())
2381 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00002382 // Record usage of conversion in an implicit cast.
2383 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2384 Result.get()->getType(),
2385 CK_UserDefinedConversion,
2386 Result.get(), 0,
2387 Result.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002388
John McCallca82a822011-09-21 08:36:56 +00002389 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2390
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002391 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002392 }
2393 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002394}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002395
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002396/// PerformImplicitConversion - Perform an implicit conversion of the
2397/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002398/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002399/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002400/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002401ExprResult
2402Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002403 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002404 AssignmentAction Action,
2405 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002406 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002407 case ImplicitConversionSequence::StandardConversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002408 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2409 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002410 if (Res.isInvalid())
2411 return ExprError();
2412 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002413 break;
John Wiegley429bb272011-04-08 18:41:53 +00002414 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002415
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002416 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002417
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002418 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002419 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002420 QualType BeforeToType;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002421 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002422 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002423 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002424
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002425 // If the user-defined conversion is specified by a conversion function,
2426 // the initial standard conversion sequence converts the source type to
2427 // the implicit object parameter of the conversion function.
2428 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002429 } else {
2430 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002431 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002432 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002433 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002434 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002435 // initial standard conversion sequence converts the source type to the
2436 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002437 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2438 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002439 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002440 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002441 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002442 ExprResult Res =
Richard Smithc8d7f582011-11-29 22:48:16 +00002443 PerformImplicitConversion(From, BeforeToType,
2444 ICS.UserDefined.Before, AA_Converting,
2445 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002446 if (Res.isInvalid())
2447 return ExprError();
2448 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002449 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002450
2451 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002452 = BuildCXXCastArgument(*this,
2453 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002454 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002455 CastKind, cast<CXXMethodDecl>(FD),
2456 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002457 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002458 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002459
2460 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002461 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002462
John Wiegley429bb272011-04-08 18:41:53 +00002463 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002464
Richard Smithc8d7f582011-11-29 22:48:16 +00002465 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2466 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002467 }
John McCall1d318332010-01-12 00:44:57 +00002468
2469 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002470 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002471 PDiag(diag::err_typecheck_ambiguous_condition)
2472 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002473 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002474
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002475 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002476 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002477
2478 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002479 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002480 }
2481
2482 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002483 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002484}
2485
Richard Smithc8d7f582011-11-29 22:48:16 +00002486/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002487/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002488/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002489/// expression. Flavor is the context in which we're performing this
2490/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002491ExprResult
Richard Smithc8d7f582011-11-29 22:48:16 +00002492Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002493 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002494 AssignmentAction Action,
2495 CheckedConversionKind CCK) {
2496 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2497
Mike Stump390b4cc2009-05-16 07:39:55 +00002498 // Overall FIXME: we are recomputing too many types here and doing far too
2499 // much extra work. What this means is that we need to keep track of more
2500 // information that is computed when we try the implicit conversion initially,
2501 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002502 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002503
Douglas Gregor225c41e2008-11-03 19:09:14 +00002504 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002505 // FIXME: When can ToType be a reference type?
2506 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002507 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002508 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002509 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002510 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002511 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002512 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002513 return ExprError();
2514 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2515 ToType, SCS.CopyConstructor,
2516 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002517 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002518 /*ZeroInit*/ false,
2519 CXXConstructExpr::CK_Complete,
2520 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002521 }
John Wiegley429bb272011-04-08 18:41:53 +00002522 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2523 ToType, SCS.CopyConstructor,
2524 MultiExprArg(*this, &From, 1),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002525 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002526 /*ZeroInit*/ false,
2527 CXXConstructExpr::CK_Complete,
2528 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002529 }
2530
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002531 // Resolve overloaded function references.
2532 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2533 DeclAccessPair Found;
2534 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2535 true, Found);
2536 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002537 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002538
Daniel Dunbar96a00142012-03-09 18:35:03 +00002539 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley429bb272011-04-08 18:41:53 +00002540 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002541
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002542 From = FixOverloadedFunctionReference(From, Found, Fn);
2543 FromType = From->getType();
2544 }
2545
Richard Smithc8d7f582011-11-29 22:48:16 +00002546 // Perform the first implicit conversion.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002547 switch (SCS.First) {
2548 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002549 // Nothing to do.
2550 break;
2551
Eli Friedmand814eaf2012-01-24 22:51:26 +00002552 case ICK_Lvalue_To_Rvalue: {
John McCall3c3b7f92011-10-25 17:37:35 +00002553 assert(From->getObjectKind() != OK_ObjCProperty);
John McCallf6a16482010-12-04 03:47:34 +00002554 FromType = FromType.getUnqualifiedType();
Eli Friedmand814eaf2012-01-24 22:51:26 +00002555 ExprResult FromRes = DefaultLvalueConversion(From);
2556 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2557 From = FromRes.take();
John McCallf6a16482010-12-04 03:47:34 +00002558 break;
Eli Friedmand814eaf2012-01-24 22:51:26 +00002559 }
John McCallf6a16482010-12-04 03:47:34 +00002560
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002561 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002562 FromType = Context.getArrayDecayedType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002563 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2564 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002565 break;
2566
2567 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002568 FromType = Context.getPointerType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002569 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2570 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002571 break;
2572
2573 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002574 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002575 }
2576
Richard Smithc8d7f582011-11-29 22:48:16 +00002577 // Perform the second implicit conversion
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002578 switch (SCS.Second) {
2579 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002580 // If both sides are functions (or pointers/references to them), there could
2581 // be incompatible exception declarations.
2582 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002583 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002584 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002585 break;
2586
Douglas Gregor43c79c22009-12-09 00:47:37 +00002587 case ICK_NoReturn_Adjustment:
2588 // If both sides are functions (or pointers/references to them), there could
2589 // be incompatible exception declarations.
2590 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002591 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002592
Richard Smithc8d7f582011-11-29 22:48:16 +00002593 From = ImpCastExprToType(From, ToType, CK_NoOp,
2594 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002595 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002596
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002597 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002598 case ICK_Integral_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002599 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2600 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002601 break;
2602
2603 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002604 case ICK_Floating_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002605 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2606 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002607 break;
2608
2609 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002610 case ICK_Complex_Conversion: {
2611 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2612 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2613 CastKind CK;
2614 if (FromEl->isRealFloatingType()) {
2615 if (ToEl->isRealFloatingType())
2616 CK = CK_FloatingComplexCast;
2617 else
2618 CK = CK_FloatingComplexToIntegralComplex;
2619 } else if (ToEl->isRealFloatingType()) {
2620 CK = CK_IntegralComplexToFloatingComplex;
2621 } else {
2622 CK = CK_IntegralComplexCast;
2623 }
Richard Smithc8d7f582011-11-29 22:48:16 +00002624 From = ImpCastExprToType(From, ToType, CK,
2625 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002626 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002627 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002628
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002629 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002630 if (ToType->isRealFloatingType())
Richard Smithc8d7f582011-11-29 22:48:16 +00002631 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2632 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002633 else
Richard Smithc8d7f582011-11-29 22:48:16 +00002634 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2635 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002636 break;
2637
Douglas Gregorf9201e02009-02-11 23:02:49 +00002638 case ICK_Compatible_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002639 From = ImpCastExprToType(From, ToType, CK_NoOp,
2640 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002641 break;
2642
John McCallf85e1932011-06-15 23:02:42 +00002643 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002644 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002645 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002646 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002647 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002648 Diag(From->getLocStart(),
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002649 diag::ext_typecheck_convert_incompatible_pointer)
2650 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002651 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002652 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00002653 Diag(From->getLocStart(),
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002654 diag::ext_typecheck_convert_incompatible_pointer)
2655 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002656 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002657
Douglas Gregor926df6c2011-06-11 01:09:30 +00002658 if (From->getType()->isObjCObjectPointerType() &&
2659 ToType->isObjCObjectPointerType())
2660 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002661 }
David Blaikie4e4d0842012-03-11 07:00:24 +00002662 else if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002663 !CheckObjCARCUnavailableWeakConversion(ToType,
2664 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002665 if (Action == AA_Initializing)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002666 Diag(From->getLocStart(),
John McCall7f3a6d32011-09-09 06:12:06 +00002667 diag::err_arc_weak_unavailable_assign);
2668 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00002669 Diag(From->getLocStart(),
John McCall7f3a6d32011-09-09 06:12:06 +00002670 diag::err_arc_convesion_of_weak_unavailable)
2671 << (Action == AA_Casting) << From->getType() << ToType
2672 << From->getSourceRange();
2673 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002674
John McCalldaa8e4e2010-11-15 09:13:47 +00002675 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002676 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002677 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002678 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002679
2680 // Make sure we extend blocks if necessary.
2681 // FIXME: doing this here is really ugly.
2682 if (Kind == CK_BlockPointerToObjCPointerCast) {
2683 ExprResult E = From;
2684 (void) PrepareCastToObjCObjectPointer(E);
2685 From = E.take();
2686 }
2687
Richard Smithc8d7f582011-11-29 22:48:16 +00002688 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2689 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002690 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002691 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002692
Anders Carlsson61faec12009-09-12 04:46:44 +00002693 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002694 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002695 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002696 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002697 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002698 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002699 return ExprError();
Richard Smithc8d7f582011-11-29 22:48:16 +00002700 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2701 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002702 break;
2703 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002704
Abramo Bagnara737d5442011-04-07 09:26:19 +00002705 case ICK_Boolean_Conversion:
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002706 // Perform half-to-boolean conversion via float.
2707 if (From->getType()->isHalfType()) {
2708 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2709 FromType = Context.FloatTy;
2710 }
2711
Richard Smithc8d7f582011-11-29 22:48:16 +00002712 From = ImpCastExprToType(From, Context.BoolTy,
2713 ScalarTypeToBooleanCastKind(FromType),
2714 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002715 break;
2716
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002717 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002718 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002719 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002720 ToType.getNonReferenceType(),
2721 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002722 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002723 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002724 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002725 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002726
Richard Smithc8d7f582011-11-29 22:48:16 +00002727 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2728 CK_DerivedToBase, From->getValueKind(),
2729 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002730 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002731 }
2732
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002733 case ICK_Vector_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002734 From = ImpCastExprToType(From, ToType, CK_BitCast,
2735 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002736 break;
2737
2738 case ICK_Vector_Splat:
Richard Smithc8d7f582011-11-29 22:48:16 +00002739 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2740 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002741 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002742
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002743 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002744 // Case 1. x -> _Complex y
2745 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2746 QualType ElType = ToComplex->getElementType();
2747 bool isFloatingComplex = ElType->isRealFloatingType();
2748
2749 // x -> y
2750 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2751 // do nothing
2752 } else if (From->getType()->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002753 From = ImpCastExprToType(From, ElType,
2754 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002755 } else {
2756 assert(From->getType()->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002757 From = ImpCastExprToType(From, ElType,
2758 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002759 }
2760 // y -> _Complex y
Richard Smithc8d7f582011-11-29 22:48:16 +00002761 From = ImpCastExprToType(From, ToType,
2762 isFloatingComplex ? CK_FloatingRealToComplex
2763 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002764
2765 // Case 2. _Complex x -> y
2766 } else {
2767 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2768 assert(FromComplex);
2769
2770 QualType ElType = FromComplex->getElementType();
2771 bool isFloatingComplex = ElType->isRealFloatingType();
2772
2773 // _Complex x -> x
Richard Smithc8d7f582011-11-29 22:48:16 +00002774 From = ImpCastExprToType(From, ElType,
2775 isFloatingComplex ? CK_FloatingComplexToReal
2776 : CK_IntegralComplexToReal,
2777 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002778
2779 // x -> y
2780 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2781 // do nothing
2782 } else if (ToType->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002783 From = ImpCastExprToType(From, ToType,
2784 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2785 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002786 } else {
2787 assert(ToType->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002788 From = ImpCastExprToType(From, ToType,
2789 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2790 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002791 }
2792 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002793 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002794
2795 case ICK_Block_Pointer_Conversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002796 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2797 VK_RValue, /*BasePath=*/0, CCK).take();
John McCallf85e1932011-06-15 23:02:42 +00002798 break;
2799 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002800
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002801 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002802 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002803 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002804 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2805 if (FromRes.isInvalid())
2806 return ExprError();
2807 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002808 assert ((ConvTy == Sema::Compatible) &&
2809 "Improper transparent union conversion");
2810 (void)ConvTy;
2811 break;
2812 }
2813
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002814 case ICK_Lvalue_To_Rvalue:
2815 case ICK_Array_To_Pointer:
2816 case ICK_Function_To_Pointer:
2817 case ICK_Qualification:
2818 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002819 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002820 }
2821
2822 switch (SCS.Third) {
2823 case ICK_Identity:
2824 // Nothing to do.
2825 break;
2826
Sebastian Redl906082e2010-07-20 04:20:21 +00002827 case ICK_Qualification: {
2828 // The qualification keeps the category of the inner expression, unless the
2829 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002830 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002831 From->getValueKind() : VK_RValue;
Richard Smithc8d7f582011-11-29 22:48:16 +00002832 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2833 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002834
Douglas Gregor069a6da2011-03-14 16:13:32 +00002835 if (SCS.DeprecatedStringLiteralToCharPtr &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002836 !getLangOpts().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002837 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2838 << ToType.getNonReferenceType();
2839
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002840 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002841 }
2842
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002843 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002844 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002845 }
2846
Douglas Gregor47bfcca2012-04-12 20:42:30 +00002847 // If this conversion sequence involved a scalar -> atomic conversion, perform
2848 // that conversion now.
2849 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>())
2850 if (Context.hasSameType(ToAtomic->getValueType(), From->getType()))
2851 From = ImpCastExprToType(From, ToType, CK_NonAtomicToAtomic, VK_RValue, 0,
2852 CCK).take();
2853
John Wiegley429bb272011-04-08 18:41:53 +00002854 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002855}
2856
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002857ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002858 SourceLocation KWLoc,
2859 ParsedType Ty,
2860 SourceLocation RParen) {
2861 TypeSourceInfo *TSInfo;
2862 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002863
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002864 if (!TSInfo)
2865 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002866 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002867}
2868
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002869/// \brief Check the completeness of a type in a unary type trait.
2870///
2871/// If the particular type trait requires a complete type, tries to complete
2872/// it. If completing the type fails, a diagnostic is emitted and false
2873/// returned. If completing the type succeeds or no completion was required,
2874/// returns true.
2875static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2876 UnaryTypeTrait UTT,
2877 SourceLocation Loc,
2878 QualType ArgTy) {
2879 // C++0x [meta.unary.prop]p3:
2880 // For all of the class templates X declared in this Clause, instantiating
2881 // that template with a template argument that is a class template
2882 // specialization may result in the implicit instantiation of the template
2883 // argument if and only if the semantics of X require that the argument
2884 // must be a complete type.
2885 // We apply this rule to all the type trait expressions used to implement
2886 // these class templates. We also try to follow any GCC documented behavior
2887 // in these expressions to ensure portability of standard libraries.
2888 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002889 // is_complete_type somewhat obviously cannot require a complete type.
2890 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002891 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002892
2893 // These traits are modeled on the type predicates in C++0x
2894 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2895 // requiring a complete type, as whether or not they return true cannot be
2896 // impacted by the completeness of the type.
2897 case UTT_IsVoid:
2898 case UTT_IsIntegral:
2899 case UTT_IsFloatingPoint:
2900 case UTT_IsArray:
2901 case UTT_IsPointer:
2902 case UTT_IsLvalueReference:
2903 case UTT_IsRvalueReference:
2904 case UTT_IsMemberFunctionPointer:
2905 case UTT_IsMemberObjectPointer:
2906 case UTT_IsEnum:
2907 case UTT_IsUnion:
2908 case UTT_IsClass:
2909 case UTT_IsFunction:
2910 case UTT_IsReference:
2911 case UTT_IsArithmetic:
2912 case UTT_IsFundamental:
2913 case UTT_IsObject:
2914 case UTT_IsScalar:
2915 case UTT_IsCompound:
2916 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002917 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002918
2919 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2920 // which requires some of its traits to have the complete type. However,
2921 // the completeness of the type cannot impact these traits' semantics, and
2922 // so they don't require it. This matches the comments on these traits in
2923 // Table 49.
2924 case UTT_IsConst:
2925 case UTT_IsVolatile:
2926 case UTT_IsSigned:
2927 case UTT_IsUnsigned:
2928 return true;
2929
2930 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002931 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002932 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002933 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002934 case UTT_IsStandardLayout:
2935 case UTT_IsPOD:
2936 case UTT_IsLiteral:
2937 case UTT_IsEmpty:
2938 case UTT_IsPolymorphic:
2939 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002940 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002941
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002942 // These traits require a complete type.
2943 case UTT_IsFinal:
2944
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002945 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002946 // [meta.unary.prop] despite not being named the same. They are specified
2947 // by both GCC and the Embarcadero C++ compiler, and require the complete
2948 // type due to the overarching C++0x type predicates being implemented
2949 // requiring the complete type.
2950 case UTT_HasNothrowAssign:
2951 case UTT_HasNothrowConstructor:
2952 case UTT_HasNothrowCopy:
2953 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002954 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002955 case UTT_HasTrivialCopy:
2956 case UTT_HasTrivialDestructor:
2957 case UTT_HasVirtualDestructor:
2958 // Arrays of unknown bound are expressly allowed.
2959 QualType ElTy = ArgTy;
2960 if (ArgTy->isIncompleteArrayType())
2961 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2962
2963 // The void type is expressly allowed.
2964 if (ElTy->isVoidType())
2965 return true;
2966
2967 return !S.RequireCompleteType(
2968 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002969 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002970 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002971}
2972
2973static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2974 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002975 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002976
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002977 ASTContext &C = Self.Context;
2978 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002979 // Type trait expressions corresponding to the primary type category
2980 // predicates in C++0x [meta.unary.cat].
2981 case UTT_IsVoid:
2982 return T->isVoidType();
2983 case UTT_IsIntegral:
2984 return T->isIntegralType(C);
2985 case UTT_IsFloatingPoint:
2986 return T->isFloatingType();
2987 case UTT_IsArray:
2988 return T->isArrayType();
2989 case UTT_IsPointer:
2990 return T->isPointerType();
2991 case UTT_IsLvalueReference:
2992 return T->isLValueReferenceType();
2993 case UTT_IsRvalueReference:
2994 return T->isRValueReferenceType();
2995 case UTT_IsMemberFunctionPointer:
2996 return T->isMemberFunctionPointerType();
2997 case UTT_IsMemberObjectPointer:
2998 return T->isMemberDataPointerType();
2999 case UTT_IsEnum:
3000 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00003001 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003002 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003003 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003004 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003005 case UTT_IsFunction:
3006 return T->isFunctionType();
3007
3008 // Type trait expressions which correspond to the convenient composition
3009 // predicates in C++0x [meta.unary.comp].
3010 case UTT_IsReference:
3011 return T->isReferenceType();
3012 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003013 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003014 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003015 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003016 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003017 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003018 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00003019 // Note: semantic analysis depends on Objective-C lifetime types to be
3020 // considered scalar types. However, such types do not actually behave
3021 // like scalar types at run time (since they may require retain/release
3022 // operations), so we report them as non-scalar.
3023 if (T->isObjCLifetimeType()) {
3024 switch (T.getObjCLifetime()) {
3025 case Qualifiers::OCL_None:
3026 case Qualifiers::OCL_ExplicitNone:
3027 return true;
3028
3029 case Qualifiers::OCL_Strong:
3030 case Qualifiers::OCL_Weak:
3031 case Qualifiers::OCL_Autoreleasing:
3032 return false;
3033 }
3034 }
3035
Chandler Carruthcec0ced2011-05-01 09:29:55 +00003036 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003037 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003038 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003039 case UTT_IsMemberPointer:
3040 return T->isMemberPointerType();
3041
3042 // Type trait expressions which correspond to the type property predicates
3043 // in C++0x [meta.unary.prop].
3044 case UTT_IsConst:
3045 return T.isConstQualified();
3046 case UTT_IsVolatile:
3047 return T.isVolatileQualified();
3048 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00003049 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00003050 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00003051 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003052 case UTT_IsStandardLayout:
3053 return T->isStandardLayoutType();
3054 case UTT_IsPOD:
Benjamin Kramer470360d2012-04-28 10:00:33 +00003055 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003056 case UTT_IsLiteral:
3057 return T->isLiteralType();
3058 case UTT_IsEmpty:
3059 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3060 return !RD->isUnion() && RD->isEmpty();
3061 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003062 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00003063 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3064 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003065 return false;
3066 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00003067 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3068 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003069 return false;
Douglas Gregor5e9392b2011-12-03 18:14:24 +00003070 case UTT_IsFinal:
3071 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3072 return RD->hasAttr<FinalAttr>();
3073 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00003074 case UTT_IsSigned:
3075 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00003076 case UTT_IsUnsigned:
3077 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003078
3079 // Type trait expressions which query classes regarding their construction,
3080 // destruction, and copying. Rather than being based directly on the
3081 // related type predicates in the standard, they are specified by both
3082 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3083 // specifications.
3084 //
3085 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3086 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00003087 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003088 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3089 // If __is_pod (type) is true then the trait is true, else if type is
3090 // a cv class or union type (or array thereof) with a trivial default
3091 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003092 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003093 return true;
3094 if (const RecordType *RT =
3095 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00003096 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003097 return false;
3098 case UTT_HasTrivialCopy:
3099 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3100 // If __is_pod (type) is true or type is a reference type then
3101 // the trait is true, else if type is a cv class or union type
3102 // with a trivial copy constructor ([class.copy]) then the trait
3103 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003104 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003105 return true;
3106 if (const RecordType *RT = T->getAs<RecordType>())
3107 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
3108 return false;
3109 case UTT_HasTrivialAssign:
3110 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3111 // If type is const qualified or is a reference type then the
3112 // trait is false. Otherwise if __is_pod (type) is true then the
3113 // trait is true, else if type is a cv class or union type with
3114 // a trivial copy assignment ([class.copy]) then the trait is
3115 // true, else it is false.
3116 // Note: the const and reference restrictions are interesting,
3117 // given that const and reference members don't prevent a class
3118 // from having a trivial copy assignment operator (but do cause
3119 // errors if the copy assignment operator is actually used, q.v.
3120 // [class.copy]p12).
3121
3122 if (C.getBaseElementType(T).isConstQualified())
3123 return false;
John McCallf85e1932011-06-15 23:02:42 +00003124 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003125 return true;
3126 if (const RecordType *RT = T->getAs<RecordType>())
3127 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
3128 return false;
3129 case UTT_HasTrivialDestructor:
3130 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3131 // If __is_pod (type) is true or type is a reference type
3132 // then the trait is true, else if type is a cv class or union
3133 // type (or array thereof) with a trivial destructor
3134 // ([class.dtor]) then the trait is true, else it is
3135 // false.
John McCallf85e1932011-06-15 23:02:42 +00003136 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003137 return true;
John McCallf85e1932011-06-15 23:02:42 +00003138
3139 // Objective-C++ ARC: autorelease types don't require destruction.
3140 if (T->isObjCLifetimeType() &&
3141 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3142 return true;
3143
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003144 if (const RecordType *RT =
3145 C.getBaseElementType(T)->getAs<RecordType>())
3146 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
3147 return false;
3148 // TODO: Propagate nothrowness for implicitly declared special members.
3149 case UTT_HasNothrowAssign:
3150 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3151 // If type is const qualified or is a reference type then the
3152 // trait is false. Otherwise if __has_trivial_assign (type)
3153 // is true then the trait is true, else if type is a cv class
3154 // or union type with copy assignment operators that are known
3155 // not to throw an exception then the trait is true, else it is
3156 // false.
3157 if (C.getBaseElementType(T).isConstQualified())
3158 return false;
3159 if (T->isReferenceType())
3160 return false;
John McCallf85e1932011-06-15 23:02:42 +00003161 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
3162 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003163 if (const RecordType *RT = T->getAs<RecordType>()) {
3164 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
3165 if (RD->hasTrivialCopyAssignment())
3166 return true;
3167
3168 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003169 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00003170 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
3171 Sema::LookupOrdinaryName);
3172 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregord41679d2011-10-12 15:40:49 +00003173 Res.suppressDiagnostics();
Sebastian Redlf8aca862010-09-14 23:40:14 +00003174 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3175 Op != OpEnd; ++Op) {
Douglas Gregord41679d2011-10-12 15:40:49 +00003176 if (isa<FunctionTemplateDecl>(*Op))
3177 continue;
3178
Sebastian Redlf8aca862010-09-14 23:40:14 +00003179 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3180 if (Operator->isCopyAssignmentOperator()) {
3181 FoundAssign = true;
3182 const FunctionProtoType *CPT
3183 = Operator->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;
3189 if (!CPT->isNothrow(Self.Context))
3190 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003191 }
3192 }
3193 }
Douglas Gregord41679d2011-10-12 15:40:49 +00003194
Richard Smith7a614d82011-06-11 17:19:42 +00003195 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003196 }
3197 return false;
3198 case UTT_HasNothrowCopy:
3199 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3200 // If __has_trivial_copy (type) is true then the trait is true, else
3201 // if type is a cv class or union type with copy constructors that are
3202 // known not to throw an exception then the trait is true, else it is
3203 // false.
John McCallf85e1932011-06-15 23:02:42 +00003204 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003205 return true;
3206 if (const RecordType *RT = T->getAs<RecordType>()) {
3207 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3208 if (RD->hasTrivialCopyConstructor())
3209 return true;
3210
3211 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003212 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003213 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00003214 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003215 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003216 // A template constructor is never a copy constructor.
3217 // FIXME: However, it may actually be selected at the actual overload
3218 // resolution point.
3219 if (isa<FunctionTemplateDecl>(*Con))
3220 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003221 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3222 if (Constructor->isCopyConstructor(FoundTQs)) {
3223 FoundConstructor = true;
3224 const FunctionProtoType *CPT
3225 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +00003226 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3227 if (!CPT)
3228 return false;
Richard Smith7a614d82011-06-11 17:19:42 +00003229 if (CPT->getExceptionSpecType() == EST_Delayed)
3230 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003231 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00003232 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00003233 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3234 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003235 }
3236 }
3237
Richard Smith7a614d82011-06-11 17:19:42 +00003238 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003239 }
3240 return false;
3241 case UTT_HasNothrowConstructor:
3242 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3243 // If __has_trivial_constructor (type) is true then the trait is
3244 // true, else if type is a cv class or union type (or array
3245 // thereof) with a default constructor that is known not to
3246 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003247 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003248 return true;
3249 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3250 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00003251 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003252 return true;
3253
Sebastian Redl751025d2010-09-13 22:02:47 +00003254 DeclContext::lookup_const_iterator Con, ConEnd;
3255 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3256 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003257 // FIXME: In C++0x, a constructor template can be a default constructor.
3258 if (isa<FunctionTemplateDecl>(*Con))
3259 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00003260 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3261 if (Constructor->isDefaultConstructor()) {
3262 const FunctionProtoType *CPT
3263 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +00003264 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3265 if (!CPT)
3266 return false;
Richard Smith7a614d82011-06-11 17:19:42 +00003267 if (CPT->getExceptionSpecType() == EST_Delayed)
3268 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00003269 // TODO: check whether evaluating default arguments can throw.
3270 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003271 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00003272 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003273 }
3274 }
3275 return false;
3276 case UTT_HasVirtualDestructor:
3277 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3278 // If type is a class type with a virtual destructor ([class.dtor])
3279 // then the trait is true, else it is false.
3280 if (const RecordType *Record = T->getAs<RecordType>()) {
3281 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00003282 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003283 return Destructor->isVirtual();
3284 }
3285 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003286
3287 // These type trait expressions are modeled on the specifications for the
3288 // Embarcadero C++0x type trait functions:
3289 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3290 case UTT_IsCompleteType:
3291 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3292 // Returns True if and only if T is a complete type at the point of the
3293 // function call.
3294 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003295 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00003296 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003297}
3298
3299ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00003300 SourceLocation KWLoc,
3301 TypeSourceInfo *TSInfo,
3302 SourceLocation RParen) {
3303 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00003304 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3305 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00003306
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003307 bool Value = false;
3308 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003309 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003310
3311 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00003312 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00003313}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003314
Francois Pichet6ad6f282010-12-07 00:08:36 +00003315ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3316 SourceLocation KWLoc,
3317 ParsedType LhsTy,
3318 ParsedType RhsTy,
3319 SourceLocation RParen) {
3320 TypeSourceInfo *LhsTSInfo;
3321 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3322 if (!LhsTSInfo)
3323 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3324
3325 TypeSourceInfo *RhsTSInfo;
3326 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3327 if (!RhsTSInfo)
3328 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3329
3330 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3331}
3332
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003333static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3334 ArrayRef<TypeSourceInfo *> Args,
3335 SourceLocation RParenLoc) {
3336 switch (Kind) {
3337 case clang::TT_IsTriviallyConstructible: {
3338 // C++11 [meta.unary.prop]:
Dmitri Gribenko62348f02012-02-24 20:03:35 +00003339 // is_trivially_constructible is defined as:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003340 //
Dmitri Gribenko62348f02012-02-24 20:03:35 +00003341 // is_constructible<T, Args...>::value is true and the variable
3342 // definition for is_constructible, as defined below, is known to call no
3343 // operation that is not trivial.
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003344 //
3345 // The predicate condition for a template specialization
3346 // is_constructible<T, Args...> shall be satisfied if and only if the
3347 // following variable definition would be well-formed for some invented
3348 // variable t:
3349 //
3350 // T t(create<Args>()...);
3351 if (Args.empty()) {
3352 S.Diag(KWLoc, diag::err_type_trait_arity)
3353 << 1 << 1 << 1 << (int)Args.size();
3354 return false;
3355 }
3356
3357 bool SawVoid = false;
3358 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3359 if (Args[I]->getType()->isVoidType()) {
3360 SawVoid = true;
3361 continue;
3362 }
3363
3364 if (!Args[I]->getType()->isIncompleteType() &&
3365 S.RequireCompleteType(KWLoc, Args[I]->getType(),
3366 diag::err_incomplete_type_used_in_type_trait_expr))
3367 return false;
3368 }
3369
3370 // If any argument was 'void', of course it won't type-check.
3371 if (SawVoid)
3372 return false;
3373
3374 llvm::SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3375 llvm::SmallVector<Expr *, 2> ArgExprs;
3376 ArgExprs.reserve(Args.size() - 1);
3377 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3378 QualType T = Args[I]->getType();
3379 if (T->isObjectType() || T->isFunctionType())
3380 T = S.Context.getRValueReferenceType(T);
3381 OpaqueArgExprs.push_back(
Daniel Dunbar96a00142012-03-09 18:35:03 +00003382 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003383 T.getNonLValueExprType(S.Context),
3384 Expr::getValueKindForType(T)));
3385 ArgExprs.push_back(&OpaqueArgExprs.back());
3386 }
3387
3388 // Perform the initialization in an unevaluated context within a SFINAE
3389 // trap at translation unit scope.
3390 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3391 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3392 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3393 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3394 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3395 RParenLoc));
3396 InitializationSequence Init(S, To, InitKind,
3397 ArgExprs.begin(), ArgExprs.size());
3398 if (Init.Failed())
3399 return false;
3400
3401 ExprResult Result = Init.Perform(S, To, InitKind,
3402 MultiExprArg(ArgExprs.data(),
3403 ArgExprs.size()));
3404 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3405 return false;
3406
3407 // The initialization succeeded; not make sure there are no non-trivial
3408 // calls.
3409 return !Result.get()->hasNonTrivialCall(S.Context);
3410 }
3411 }
3412
3413 return false;
3414}
3415
3416ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3417 ArrayRef<TypeSourceInfo *> Args,
3418 SourceLocation RParenLoc) {
3419 bool Dependent = false;
3420 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3421 if (Args[I]->getType()->isDependentType()) {
3422 Dependent = true;
3423 break;
3424 }
3425 }
3426
3427 bool Value = false;
3428 if (!Dependent)
3429 Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3430
3431 return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind,
3432 Args, RParenLoc, Value);
3433}
3434
3435ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3436 ArrayRef<ParsedType> Args,
3437 SourceLocation RParenLoc) {
3438 llvm::SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
3439 ConvertedArgs.reserve(Args.size());
3440
3441 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3442 TypeSourceInfo *TInfo;
3443 QualType T = GetTypeFromParser(Args[I], &TInfo);
3444 if (!TInfo)
3445 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3446
3447 ConvertedArgs.push_back(TInfo);
3448 }
3449
3450 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3451}
3452
Francois Pichet6ad6f282010-12-07 00:08:36 +00003453static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3454 QualType LhsT, QualType RhsT,
3455 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003456 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3457 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003458
3459 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003460 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003461 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003462 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003463 // Base and Derived are not unions and name the same class type without
3464 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003465
John McCalld89d30f2011-01-28 22:02:36 +00003466 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3467 if (!lhsRecord) return false;
3468
3469 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3470 if (!rhsRecord) return false;
3471
3472 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3473 == (lhsRecord == rhsRecord));
3474
3475 if (lhsRecord == rhsRecord)
3476 return !lhsRecord->getDecl()->isUnion();
3477
3478 // C++0x [meta.rel]p2:
3479 // If Base and Derived are class types and are different types
3480 // (ignoring possible cv-qualifiers) then Derived shall be a
3481 // complete type.
3482 if (Self.RequireCompleteType(KeyLoc, RhsT,
3483 diag::err_incomplete_type_used_in_type_trait_expr))
3484 return false;
3485
3486 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3487 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3488 }
John Wiegley20c0da72011-04-27 23:09:49 +00003489 case BTT_IsSame:
3490 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003491 case BTT_TypeCompatible:
3492 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3493 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003494 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003495 case BTT_IsConvertibleTo: {
3496 // C++0x [meta.rel]p4:
3497 // Given the following function prototype:
3498 //
3499 // template <class T>
3500 // typename add_rvalue_reference<T>::type create();
3501 //
3502 // the predicate condition for a template specialization
3503 // is_convertible<From, To> shall be satisfied if and only if
3504 // the return expression in the following code would be
3505 // well-formed, including any implicit conversions to the return
3506 // type of the function:
3507 //
3508 // To test() {
3509 // return create<From>();
3510 // }
3511 //
3512 // Access checking is performed as if in a context unrelated to To and
3513 // From. Only the validity of the immediate context of the expression
3514 // of the return-statement (including conversions to the return type)
3515 // is considered.
3516 //
3517 // We model the initialization as a copy-initialization of a temporary
3518 // of the appropriate type, which for this expression is identical to the
3519 // return statement (since NRVO doesn't apply).
3520 if (LhsT->isObjectType() || LhsT->isFunctionType())
3521 LhsT = Self.Context.getRValueReferenceType(LhsT);
3522
3523 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003524 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003525 Expr::getValueKindForType(LhsT));
3526 Expr *FromPtr = &From;
3527 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3528 SourceLocation()));
3529
Eli Friedman3add9f02012-01-25 01:05:57 +00003530 // Perform the initialization in an unevaluated context within a SFINAE
3531 // trap at translation unit scope.
3532 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003533 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3534 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003535 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003536 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003537 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003538
Douglas Gregor9f361132011-01-27 20:28:01 +00003539 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3540 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3541 }
Douglas Gregor25d0a0f2012-02-23 07:33:15 +00003542
3543 case BTT_IsTriviallyAssignable: {
3544 // C++11 [meta.unary.prop]p3:
3545 // is_trivially_assignable is defined as:
3546 // is_assignable<T, U>::value is true and the assignment, as defined by
3547 // is_assignable, is known to call no operation that is not trivial
3548 //
3549 // is_assignable is defined as:
3550 // The expression declval<T>() = declval<U>() is well-formed when
3551 // treated as an unevaluated operand (Clause 5).
3552 //
3553 // For both, T and U shall be complete types, (possibly cv-qualified)
3554 // void, or arrays of unknown bound.
3555 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3556 Self.RequireCompleteType(KeyLoc, LhsT,
3557 diag::err_incomplete_type_used_in_type_trait_expr))
3558 return false;
3559 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3560 Self.RequireCompleteType(KeyLoc, RhsT,
3561 diag::err_incomplete_type_used_in_type_trait_expr))
3562 return false;
3563
3564 // cv void is never assignable.
3565 if (LhsT->isVoidType() || RhsT->isVoidType())
3566 return false;
3567
3568 // Build expressions that emulate the effect of declval<T>() and
3569 // declval<U>().
3570 if (LhsT->isObjectType() || LhsT->isFunctionType())
3571 LhsT = Self.Context.getRValueReferenceType(LhsT);
3572 if (RhsT->isObjectType() || RhsT->isFunctionType())
3573 RhsT = Self.Context.getRValueReferenceType(RhsT);
3574 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3575 Expr::getValueKindForType(LhsT));
3576 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3577 Expr::getValueKindForType(RhsT));
3578
3579 // Attempt the assignment in an unevaluated context within a SFINAE
3580 // trap at translation unit scope.
3581 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3582 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3583 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3584 ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs);
3585 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3586 return false;
3587
3588 return !Result.get()->hasNonTrivialCall(Self.Context);
3589 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003590 }
3591 llvm_unreachable("Unknown type trait or not implemented");
3592}
3593
3594ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3595 SourceLocation KWLoc,
3596 TypeSourceInfo *LhsTSInfo,
3597 TypeSourceInfo *RhsTSInfo,
3598 SourceLocation RParen) {
3599 QualType LhsT = LhsTSInfo->getType();
3600 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003601
John McCalld89d30f2011-01-28 22:02:36 +00003602 if (BTT == BTT_TypeCompatible) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003603 if (getLangOpts().CPlusPlus) {
Francois Pichetf1872372010-12-08 22:35:30 +00003604 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3605 << SourceRange(KWLoc, RParen);
3606 return ExprError();
3607 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003608 }
3609
3610 bool Value = false;
3611 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3612 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3613
Francois Pichetf1872372010-12-08 22:35:30 +00003614 // Select trait result type.
3615 QualType ResultType;
3616 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003617 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003618 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3619 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003620 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003621 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Douglas Gregor25d0a0f2012-02-23 07:33:15 +00003622 case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy;
Francois Pichetf1872372010-12-08 22:35:30 +00003623 }
3624
Francois Pichet6ad6f282010-12-07 00:08:36 +00003625 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3626 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003627 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003628}
3629
John Wiegley21ff2e52011-04-28 00:16:57 +00003630ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3631 SourceLocation KWLoc,
3632 ParsedType Ty,
3633 Expr* DimExpr,
3634 SourceLocation RParen) {
3635 TypeSourceInfo *TSInfo;
3636 QualType T = GetTypeFromParser(Ty, &TSInfo);
3637 if (!TSInfo)
3638 TSInfo = Context.getTrivialTypeSourceInfo(T);
3639
3640 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3641}
3642
3643static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3644 QualType T, Expr *DimExpr,
3645 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003646 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003647
3648 switch(ATT) {
3649 case ATT_ArrayRank:
3650 if (T->isArrayType()) {
3651 unsigned Dim = 0;
3652 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3653 ++Dim;
3654 T = AT->getElementType();
3655 }
3656 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003657 }
John Wiegleycf566412011-04-28 02:06:46 +00003658 return 0;
3659
John Wiegley21ff2e52011-04-28 00:16:57 +00003660 case ATT_ArrayExtent: {
3661 llvm::APSInt Value;
3662 uint64_t Dim;
Richard Smith282e7e62012-02-04 09:53:13 +00003663 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregorab41fe92012-05-04 22:38:52 +00003664 diag::err_dimension_expr_not_constant_integer,
Richard Smith282e7e62012-02-04 09:53:13 +00003665 false).isInvalid())
3666 return 0;
3667 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbare7d6ca02012-03-09 21:38:22 +00003668 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3669 << DimExpr->getSourceRange();
Richard Smith282e7e62012-02-04 09:53:13 +00003670 return 0;
John Wiegleycf566412011-04-28 02:06:46 +00003671 }
Richard Smith282e7e62012-02-04 09:53:13 +00003672 Dim = Value.getLimitedValue();
John Wiegley21ff2e52011-04-28 00:16:57 +00003673
3674 if (T->isArrayType()) {
3675 unsigned D = 0;
3676 bool Matched = false;
3677 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3678 if (Dim == D) {
3679 Matched = true;
3680 break;
3681 }
3682 ++D;
3683 T = AT->getElementType();
3684 }
3685
John Wiegleycf566412011-04-28 02:06:46 +00003686 if (Matched && T->isArrayType()) {
3687 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3688 return CAT->getSize().getLimitedValue();
3689 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003690 }
John Wiegleycf566412011-04-28 02:06:46 +00003691 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003692 }
3693 }
3694 llvm_unreachable("Unknown type trait or not implemented");
3695}
3696
3697ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3698 SourceLocation KWLoc,
3699 TypeSourceInfo *TSInfo,
3700 Expr* DimExpr,
3701 SourceLocation RParen) {
3702 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003703
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003704 // FIXME: This should likely be tracked as an APInt to remove any host
3705 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003706 uint64_t Value = 0;
3707 if (!T->isDependentType())
3708 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3709
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003710 // While the specification for these traits from the Embarcadero C++
3711 // compiler's documentation says the return type is 'unsigned int', Clang
3712 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3713 // compiler, there is no difference. On several other platforms this is an
3714 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003715 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003716 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003717 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003718}
3719
John Wiegley55262202011-04-25 06:54:41 +00003720ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003721 SourceLocation KWLoc,
3722 Expr *Queried,
3723 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003724 // If error parsing the expression, ignore.
3725 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003726 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003727
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003728 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003729
3730 return move(Result);
3731}
3732
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003733static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3734 switch (ET) {
3735 case ET_IsLValueExpr: return E->isLValue();
3736 case ET_IsRValueExpr: return E->isRValue();
3737 }
3738 llvm_unreachable("Expression trait not covered by switch");
3739}
3740
John Wiegley55262202011-04-25 06:54:41 +00003741ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003742 SourceLocation KWLoc,
3743 Expr *Queried,
3744 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003745 if (Queried->isTypeDependent()) {
3746 // Delay type-checking for type-dependent expressions.
3747 } else if (Queried->getType()->isPlaceholderType()) {
3748 ExprResult PE = CheckPlaceholderExpr(Queried);
3749 if (PE.isInvalid()) return ExprError();
3750 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3751 }
3752
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003753 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003754
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003755 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3756 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003757}
3758
Richard Trieudd225092011-09-15 21:56:47 +00003759QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003760 ExprValueKind &VK,
3761 SourceLocation Loc,
3762 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003763 assert(!LHS.get()->getType()->isPlaceholderType() &&
3764 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003765 "placeholders should have been weeded out by now");
3766
3767 // The LHS undergoes lvalue conversions if this is ->*.
3768 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003769 LHS = DefaultLvalueConversion(LHS.take());
3770 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003771 }
3772
3773 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003774 RHS = DefaultLvalueConversion(RHS.take());
3775 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003776
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003777 const char *OpSpelling = isIndirect ? "->*" : ".*";
3778 // C++ 5.5p2
3779 // The binary operator .* [p3: ->*] binds its second operand, which shall
3780 // be of type "pointer to member of T" (where T is a completely-defined
3781 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003782 QualType RHSType = RHS.get()->getType();
3783 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003784 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003785 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003786 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003787 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003788 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003789
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003790 QualType Class(MemPtr->getClass(), 0);
3791
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003792 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3793 // member pointer points must be completely-defined. However, there is no
3794 // reason for this semantic distinction, and the rule is not enforced by
3795 // other compilers. Therefore, we do not check this property, as it is
3796 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003797
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003798 // C++ 5.5p2
3799 // [...] to its first operand, which shall be of class T or of a class of
3800 // which T is an unambiguous and accessible base class. [p3: a pointer to
3801 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003802 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003803 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003804 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3805 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003806 else {
3807 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003808 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003809 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003810 return QualType();
3811 }
3812 }
3813
Richard Trieudd225092011-09-15 21:56:47 +00003814 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003815 // If we want to check the hierarchy, we need a complete type.
Douglas Gregord10099e2012-05-04 16:32:21 +00003816 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
3817 OpSpelling, (int)isIndirect)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003818 return QualType();
3819 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003820 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003821 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003822 // FIXME: Would it be useful to print full ambiguity paths, or is that
3823 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003824 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003825 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3826 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003827 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003828 return QualType();
3829 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003830 // Cast LHS to type of use.
3831 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003832 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00003833
John McCallf871d0c2010-08-07 06:22:56 +00003834 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003835 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003836 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3837 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003838 }
3839
Richard Trieudd225092011-09-15 21:56:47 +00003840 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003841 // Diagnose use of pointer-to-member type which when used as
3842 // the functional cast in a pointer-to-member expression.
3843 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3844 return QualType();
3845 }
John McCallf89e55a2010-11-18 06:31:45 +00003846
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003847 // C++ 5.5p2
3848 // The result is an object or a function of the type specified by the
3849 // second operand.
3850 // The cv qualifiers are the union of those in the pointer and the left side,
3851 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003852 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003853 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003854
Douglas Gregor6b4df912011-01-26 16:40:18 +00003855 // C++0x [expr.mptr.oper]p6:
3856 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003857 // ill-formed if the second operand is a pointer to member function with
3858 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3859 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003860 // is a pointer to member function with ref-qualifier &&.
3861 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3862 switch (Proto->getRefQualifier()) {
3863 case RQ_None:
3864 // Do nothing
3865 break;
3866
3867 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003868 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003869 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003870 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003871 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003872
Douglas Gregor6b4df912011-01-26 16:40:18 +00003873 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003874 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003875 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003876 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003877 break;
3878 }
3879 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003880
John McCallf89e55a2010-11-18 06:31:45 +00003881 // C++ [expr.mptr.oper]p6:
3882 // The result of a .* expression whose second operand is a pointer
3883 // to a data member is of the same value category as its
3884 // first operand. The result of a .* expression whose second
3885 // operand is a pointer to a member function is a prvalue. The
3886 // result of an ->* expression is an lvalue if its second operand
3887 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003888 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003889 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003890 return Context.BoundMemberTy;
3891 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003892 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003893 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003894 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003895 }
John McCallf89e55a2010-11-18 06:31:45 +00003896
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003897 return Result;
3898}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003899
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003900/// \brief Try to convert a type to another according to C++0x 5.16p3.
3901///
3902/// This is part of the parameter validation for the ? operator. If either
3903/// value operand is a class type, the two operands are attempted to be
3904/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003905/// It returns true if the program is ill-formed and has already been diagnosed
3906/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003907static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3908 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003909 bool &HaveConversion,
3910 QualType &ToType) {
3911 HaveConversion = false;
3912 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003913
3914 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003915 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003916 // C++0x 5.16p3
3917 // The process for determining whether an operand expression E1 of type T1
3918 // can be converted to match an operand expression E2 of type T2 is defined
3919 // as follows:
3920 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003921 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003922 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003923 // E1 can be converted to match E2 if E1 can be implicitly converted to
3924 // type "lvalue reference to T2", subject to the constraint that in the
3925 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003926 QualType T = Self.Context.getLValueReferenceType(ToType);
3927 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003928
Douglas Gregorb70cf442010-03-26 20:14:36 +00003929 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3930 if (InitSeq.isDirectReferenceBinding()) {
3931 ToType = T;
3932 HaveConversion = true;
3933 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003934 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003935
Douglas Gregorb70cf442010-03-26 20:14:36 +00003936 if (InitSeq.isAmbiguous())
3937 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003938 }
John McCallb1bdc622010-02-25 01:37:24 +00003939
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003940 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3941 // -- if E1 and E2 have class type, and the underlying class types are
3942 // the same or one is a base class of the other:
3943 QualType FTy = From->getType();
3944 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003945 const RecordType *FRec = FTy->getAs<RecordType>();
3946 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003947 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003948 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003949 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003950 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003951 // E1 can be converted to match E2 if the class of T2 is the
3952 // same type as, or a base class of, the class of T1, and
3953 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003954 if (FRec == TRec || FDerivedFromT) {
3955 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003956 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3957 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003958 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003959 HaveConversion = true;
3960 return false;
3961 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003962
Douglas Gregorb70cf442010-03-26 20:14:36 +00003963 if (InitSeq.isAmbiguous())
3964 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003965 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003966 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003967
Douglas Gregorb70cf442010-03-26 20:14:36 +00003968 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003969 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003970
Douglas Gregorb70cf442010-03-26 20:14:36 +00003971 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3972 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003973 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003974 // an rvalue).
3975 //
3976 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3977 // to the array-to-pointer or function-to-pointer conversions.
3978 if (!TTy->getAs<TagType>())
3979 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003980
Douglas Gregorb70cf442010-03-26 20:14:36 +00003981 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3982 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003983 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003984 ToType = TTy;
3985 if (InitSeq.isAmbiguous())
3986 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3987
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003988 return false;
3989}
3990
3991/// \brief Try to find a common type for two according to C++0x 5.16p5.
3992///
3993/// This is part of the parameter validation for the ? operator. If either
3994/// value operand is a class type, overload resolution is used to find a
3995/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003996static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003997 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003998 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003999 OverloadCandidateSet CandidateSet(QuestionLoc);
4000 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
4001 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004002
4003 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00004004 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00004005 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004006 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00004007 ExprResult LHSRes =
4008 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
4009 Best->Conversions[0], Sema::AA_Converting);
4010 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004011 break;
John Wiegley429bb272011-04-08 18:41:53 +00004012 LHS = move(LHSRes);
4013
4014 ExprResult RHSRes =
4015 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
4016 Best->Conversions[1], Sema::AA_Converting);
4017 if (RHSRes.isInvalid())
4018 break;
4019 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00004020 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00004021 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004022 return false;
John Wiegley429bb272011-04-08 18:41:53 +00004023 }
4024
Douglas Gregor20093b42009-12-09 23:02:17 +00004025 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00004026
4027 // Emit a better diagnostic if one of the expressions is a null pointer
4028 // constant and the other is a pointer type. In this case, the user most
4029 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004030 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004031 return true;
4032
4033 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00004034 << LHS.get()->getType() << RHS.get()->getType()
4035 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004036 return true;
4037
Douglas Gregor20093b42009-12-09 23:02:17 +00004038 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00004039 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00004040 << LHS.get()->getType() << RHS.get()->getType()
4041 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00004042 // FIXME: Print the possible common types by printing the return types of
4043 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004044 break;
4045
Douglas Gregor20093b42009-12-09 23:02:17 +00004046 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00004047 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004048 }
4049 return true;
4050}
4051
Sebastian Redl76458502009-04-17 16:30:52 +00004052/// \brief Perform an "extended" implicit conversion as returned by
4053/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00004054static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00004055 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00004056 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00004057 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00004058 Expr *Arg = E.take();
4059 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
4060 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00004061 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00004062 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004063
John Wiegley429bb272011-04-08 18:41:53 +00004064 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00004065 return false;
4066}
4067
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004068/// \brief Check the operands of ?: under C++ semantics.
4069///
4070/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4071/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00004072QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00004073 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004074 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00004075 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4076 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004077
4078 // C++0x 5.16p1
4079 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00004080 if (!Cond.get()->isTypeDependent()) {
4081 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
4082 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004083 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004084 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004085 }
4086
John McCallf89e55a2010-11-18 06:31:45 +00004087 // Assume r-value.
4088 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004089 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00004090
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004091 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00004092 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004093 return Context.DependentTy;
4094
4095 // C++0x 5.16p2
4096 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00004097 QualType LTy = LHS.get()->getType();
4098 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004099 bool LVoid = LTy->isVoidType();
4100 bool RVoid = RTy->isVoidType();
4101 if (LVoid || RVoid) {
4102 // ... then the [l2r] conversions are performed on the second and third
4103 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00004104 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4105 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4106 if (LHS.isInvalid() || RHS.isInvalid())
4107 return QualType();
4108 LTy = LHS.get()->getType();
4109 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004110
4111 // ... and one of the following shall hold:
4112 // -- The second or the third operand (but not both) is a throw-
4113 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00004114 bool LThrow = isa<CXXThrowExpr>(LHS.get());
4115 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004116 if (LThrow && !RThrow)
4117 return RTy;
4118 if (RThrow && !LThrow)
4119 return LTy;
4120
4121 // -- Both the second and third operands have type void; the result is of
4122 // type void and is an rvalue.
4123 if (LVoid && RVoid)
4124 return Context.VoidTy;
4125
4126 // Neither holds, error.
4127 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4128 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00004129 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004130 return QualType();
4131 }
4132
4133 // Neither is void.
4134
4135 // C++0x 5.16p3
4136 // Otherwise, if the second and third operand have different types, and
4137 // either has (cv) class type, and attempt is made to convert each of those
4138 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004139 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004140 (LTy->isRecordType() || RTy->isRecordType())) {
4141 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
4142 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00004143 QualType L2RType, R2LType;
4144 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00004145 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004146 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004147 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004148 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004149
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004150 // If both can be converted, [...] the program is ill-formed.
4151 if (HaveL2R && HaveR2L) {
4152 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00004153 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004154 return QualType();
4155 }
4156
4157 // If exactly one conversion is possible, that conversion is applied to
4158 // the chosen operand and the converted operands are used in place of the
4159 // original operands for the remainder of this section.
4160 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00004161 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004162 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004163 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004164 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00004165 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004166 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004167 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004168 }
4169 }
4170
4171 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00004172 // If the second and third operands are glvalues of the same value
4173 // category and have the same type, the result is of that type and
4174 // value category and it is a bit-field if the second or the third
4175 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00004176 // We only extend this to bitfields, not to the crazy other kinds of
4177 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00004178 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00004179 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00004180 LHS.get()->isGLValue() &&
4181 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
4182 LHS.get()->isOrdinaryOrBitFieldObject() &&
4183 RHS.get()->isOrdinaryOrBitFieldObject()) {
4184 VK = LHS.get()->getValueKind();
4185 if (LHS.get()->getObjectKind() == OK_BitField ||
4186 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00004187 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00004188 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00004189 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004190
4191 // C++0x 5.16p5
4192 // Otherwise, the result is an rvalue. If the second and third operands
4193 // do not have the same type, and either has (cv) class type, ...
4194 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4195 // ... overload resolution is used to determine the conversions (if any)
4196 // to be applied to the operands. If the overload resolution fails, the
4197 // program is ill-formed.
4198 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4199 return QualType();
4200 }
4201
4202 // C++0x 5.16p6
4203 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
4204 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00004205 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4206 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4207 if (LHS.isInvalid() || RHS.isInvalid())
4208 return QualType();
4209 LTy = LHS.get()->getType();
4210 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004211
4212 // After those conversions, one of the following shall hold:
4213 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00004214 // is of that type. If the operands have class type, the result
4215 // is a prvalue temporary of the result type, which is
4216 // copy-initialized from either the second operand or the third
4217 // operand depending on the value of the first operand.
4218 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4219 if (LTy->isRecordType()) {
4220 // The operands have class type. Make a temporary copy.
4221 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004222 ExprResult LHSCopy = PerformCopyInitialization(Entity,
4223 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00004224 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00004225 if (LHSCopy.isInvalid())
4226 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004227
4228 ExprResult RHSCopy = PerformCopyInitialization(Entity,
4229 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00004230 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00004231 if (RHSCopy.isInvalid())
4232 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004233
John Wiegley429bb272011-04-08 18:41:53 +00004234 LHS = LHSCopy;
4235 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00004236 }
4237
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004238 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00004239 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004240
Douglas Gregorfb4a5432010-05-18 22:42:18 +00004241 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004242 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004243 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00004244
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004245 // -- The second and third operands have arithmetic or enumeration type;
4246 // the usual arithmetic conversions are performed to bring them to a
4247 // common type, and the result is of that type.
4248 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4249 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004250 if (LHS.isInvalid() || RHS.isInvalid())
4251 return QualType();
4252 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004253 }
4254
4255 // -- The second and third operands have pointer type, or one has pointer
4256 // type and the other is a null pointer constant; pointer conversions
4257 // and qualification conversions are performed to bring them to their
4258 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00004259 // -- The second and third operands have pointer to member type, or one has
4260 // pointer to member type and the other is a null pointer constant;
4261 // pointer to member conversions and qualification conversions are
4262 // performed to bring them to a common type, whose cv-qualification
4263 // shall match the cv-qualification of either the second or the third
4264 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004265 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004266 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004267 isSFINAEContext()? 0 : &NonStandardCompositeType);
4268 if (!Composite.isNull()) {
4269 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004270 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004271 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4272 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00004273 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004274
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004275 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004276 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004277
Douglas Gregor1927b1f2010-04-01 22:47:07 +00004278 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00004279 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4280 if (!Composite.isNull())
4281 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004282
Chandler Carruth7ef93242011-02-19 00:13:59 +00004283 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00004284 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00004285 return QualType();
4286
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004287 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00004288 << LHS.get()->getType() << RHS.get()->getType()
4289 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004290 return QualType();
4291}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004292
4293/// \brief Find a merged pointer type and convert the two expressions to it.
4294///
Douglas Gregor20b3e992009-08-24 17:42:35 +00004295/// This finds the composite pointer type (or member pointer type) for @p E1
4296/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
4297/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004298/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004299///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004300/// \param Loc The location of the operator requiring these two expressions to
4301/// be converted to the composite pointer type.
4302///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004303/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4304/// a non-standard (but still sane) composite type to which both expressions
4305/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4306/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004307QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004308 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004309 bool *NonStandardCompositeType) {
4310 if (NonStandardCompositeType)
4311 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004312
David Blaikie4e4d0842012-03-11 07:00:24 +00004313 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004314 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004315
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00004316 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4317 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00004318 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004319
4320 // C++0x 5.9p2
4321 // Pointer conversions and qualification conversions are performed on
4322 // pointer operands to bring them to their composite pointer type. If
4323 // one operand is a null pointer constant, the composite pointer type is
4324 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00004325 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004326 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00004327 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004328 else
John Wiegley429bb272011-04-08 18:41:53 +00004329 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004330 return T2;
4331 }
Douglas Gregorce940492009-09-25 04:25:58 +00004332 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004333 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00004334 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004335 else
John Wiegley429bb272011-04-08 18:41:53 +00004336 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004337 return T1;
4338 }
Mike Stump1eb44332009-09-09 15:08:12 +00004339
Douglas Gregor20b3e992009-08-24 17:42:35 +00004340 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004341 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4342 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004343 return QualType();
4344
4345 // Otherwise, of one of the operands has type "pointer to cv1 void," then
4346 // the other has type "pointer to cv2 T" and the composite pointer type is
4347 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4348 // Otherwise, the composite pointer type is a pointer type similar to the
4349 // type of one of the operands, with a cv-qualification signature that is
4350 // the union of the cv-qualification signatures of the operand types.
4351 // In practice, the first part here is redundant; it's subsumed by the second.
4352 // What we do here is, we build the two possible composite types, and try the
4353 // conversions in both directions. If only one works, or if the two composite
4354 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00004355 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00004356 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00004357 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004358 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00004359 ContainingClassVector;
4360 ContainingClassVector MemberOfClass;
4361 QualType Composite1 = Context.getCanonicalType(T1),
4362 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004363 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00004364 do {
4365 const PointerType *Ptr1, *Ptr2;
4366 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4367 (Ptr2 = Composite2->getAs<PointerType>())) {
4368 Composite1 = Ptr1->getPointeeType();
4369 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004370
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004371 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004372 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004373 if (NonStandardCompositeType &&
4374 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4375 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004376
Douglas Gregor20b3e992009-08-24 17:42:35 +00004377 QualifierUnion.push_back(
4378 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4379 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
4380 continue;
4381 }
Mike Stump1eb44332009-09-09 15:08:12 +00004382
Douglas Gregor20b3e992009-08-24 17:42:35 +00004383 const MemberPointerType *MemPtr1, *MemPtr2;
4384 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4385 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4386 Composite1 = MemPtr1->getPointeeType();
4387 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004388
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004389 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004390 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004391 if (NonStandardCompositeType &&
4392 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4393 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004394
Douglas Gregor20b3e992009-08-24 17:42:35 +00004395 QualifierUnion.push_back(
4396 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4397 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4398 MemPtr2->getClass()));
4399 continue;
4400 }
Mike Stump1eb44332009-09-09 15:08:12 +00004401
Douglas Gregor20b3e992009-08-24 17:42:35 +00004402 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00004403
Douglas Gregor20b3e992009-08-24 17:42:35 +00004404 // Cannot unwrap any more types.
4405 break;
4406 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00004407
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004408 if (NeedConstBefore && NonStandardCompositeType) {
4409 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004410 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004411 // requirements of C++ [conv.qual]p4 bullet 3.
4412 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4413 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4414 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4415 *NonStandardCompositeType = true;
4416 }
4417 }
4418 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004419
Douglas Gregor20b3e992009-08-24 17:42:35 +00004420 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004421 ContainingClassVector::reverse_iterator MOC
4422 = MemberOfClass.rbegin();
4423 for (QualifierVector::reverse_iterator
4424 I = QualifierUnion.rbegin(),
4425 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00004426 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00004427 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004428 if (MOC->first && MOC->second) {
4429 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00004430 Composite1 = Context.getMemberPointerType(
4431 Context.getQualifiedType(Composite1, Quals),
4432 MOC->first);
4433 Composite2 = Context.getMemberPointerType(
4434 Context.getQualifiedType(Composite2, Quals),
4435 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004436 } else {
4437 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00004438 Composite1
4439 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4440 Composite2
4441 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00004442 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004443 }
4444
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004445 // Try to convert to the first composite pointer type.
4446 InitializedEntity Entity1
4447 = InitializedEntity::InitializeTemporary(Composite1);
4448 InitializationKind Kind
4449 = InitializationKind::CreateCopy(Loc, SourceLocation());
4450 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4451 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00004452
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004453 if (E1ToC1 && E2ToC1) {
4454 // Conversion to Composite1 is viable.
4455 if (!Context.hasSameType(Composite1, Composite2)) {
4456 // Composite2 is a different type from Composite1. Check whether
4457 // Composite2 is also viable.
4458 InitializedEntity Entity2
4459 = InitializedEntity::InitializeTemporary(Composite2);
4460 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4461 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4462 if (E1ToC2 && E2ToC2) {
4463 // Both Composite1 and Composite2 are viable and are different;
4464 // this is an ambiguity.
4465 return QualType();
4466 }
4467 }
4468
4469 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004470 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004471 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004472 if (E1Result.isInvalid())
4473 return QualType();
4474 E1 = E1Result.takeAs<Expr>();
4475
4476 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004477 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004478 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004479 if (E2Result.isInvalid())
4480 return QualType();
4481 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004482
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004483 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004484 }
4485
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004486 // Check whether Composite2 is viable.
4487 InitializedEntity Entity2
4488 = InitializedEntity::InitializeTemporary(Composite2);
4489 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4490 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4491 if (!E1ToC2 || !E2ToC2)
4492 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004493
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004494 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004495 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004496 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004497 if (E1Result.isInvalid())
4498 return QualType();
4499 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004500
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004501 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004502 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004503 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004504 if (E2Result.isInvalid())
4505 return QualType();
4506 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004507
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004508 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004509}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004510
John McCall60d7b3a2010-08-24 06:29:42 +00004511ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004512 if (!E)
4513 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004514
John McCallf85e1932011-06-15 23:02:42 +00004515 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4516
4517 // If the result is a glvalue, we shouldn't bind it.
4518 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004519 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004520
John McCallf85e1932011-06-15 23:02:42 +00004521 // In ARC, calls that return a retainable type can return retained,
4522 // in which case we have to insert a consuming cast.
David Blaikie4e4d0842012-03-11 07:00:24 +00004523 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004524 E->getType()->isObjCRetainableType()) {
4525
4526 bool ReturnsRetained;
4527
4528 // For actual calls, we compute this by examining the type of the
4529 // called value.
4530 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4531 Expr *Callee = Call->getCallee()->IgnoreParens();
4532 QualType T = Callee->getType();
4533
4534 if (T == Context.BoundMemberTy) {
4535 // Handle pointer-to-members.
4536 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4537 T = BinOp->getRHS()->getType();
4538 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4539 T = Mem->getMemberDecl()->getType();
4540 }
4541
4542 if (const PointerType *Ptr = T->getAs<PointerType>())
4543 T = Ptr->getPointeeType();
4544 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4545 T = Ptr->getPointeeType();
4546 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4547 T = MemPtr->getPointeeType();
4548
4549 const FunctionType *FTy = T->getAs<FunctionType>();
4550 assert(FTy && "call to value not of function type?");
4551 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4552
4553 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4554 // type always produce a +1 object.
4555 } else if (isa<StmtExpr>(E)) {
4556 ReturnsRetained = true;
4557
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004558 // We hit this case with the lambda conversion-to-block optimization;
4559 // we don't want any extra casts here.
4560 } else if (isa<CastExpr>(E) &&
4561 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
4562 return Owned(E);
4563
John McCallf85e1932011-06-15 23:02:42 +00004564 // For message sends and property references, we try to find an
4565 // actual method. FIXME: we should infer retention by selector in
4566 // cases where we don't have an actual method.
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004567 } else {
4568 ObjCMethodDecl *D = 0;
4569 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4570 D = Send->getMethodDecl();
Patrick Beardeb382ec2012-04-19 00:25:12 +00004571 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4572 D = BoxedExpr->getBoxingMethod();
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004573 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4574 D = ArrayLit->getArrayWithObjectsMethod();
4575 } else if (ObjCDictionaryLiteral *DictLit
4576 = dyn_cast<ObjCDictionaryLiteral>(E)) {
4577 D = DictLit->getDictWithObjectsMethod();
4578 }
John McCallf85e1932011-06-15 23:02:42 +00004579
4580 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004581
4582 // Don't do reclaims on performSelector calls; despite their
4583 // return type, the invoked method doesn't necessarily actually
4584 // return an object.
4585 if (!ReturnsRetained &&
4586 D && D->getMethodFamily() == OMF_performSelector)
4587 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004588 }
4589
John McCall567c5862011-11-14 19:53:16 +00004590 // Don't reclaim an object of Class type.
4591 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4592 return Owned(E);
4593
John McCall7e5e5f42011-07-07 06:58:02 +00004594 ExprNeedsCleanups = true;
4595
John McCall33e56f32011-09-10 06:18:15 +00004596 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4597 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004598 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4599 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004600 }
4601
David Blaikie4e4d0842012-03-11 07:00:24 +00004602 if (!getLangOpts().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00004603 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004604
Peter Collingbourneb4ab8432012-01-26 03:33:51 +00004605 // Search for the base element type (cf. ASTContext::getBaseElementType) with
4606 // a fast path for the common case that the type is directly a RecordType.
4607 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4608 const RecordType *RT = 0;
4609 while (!RT) {
4610 switch (T->getTypeClass()) {
4611 case Type::Record:
4612 RT = cast<RecordType>(T);
4613 break;
4614 case Type::ConstantArray:
4615 case Type::IncompleteArray:
4616 case Type::VariableArray:
4617 case Type::DependentSizedArray:
4618 T = cast<ArrayType>(T)->getElementType().getTypePtr();
4619 break;
4620 default:
4621 return Owned(E);
4622 }
4623 }
Mike Stump1eb44332009-09-09 15:08:12 +00004624
Richard Smith76f3f692012-02-22 02:04:18 +00004625 // That should be enough to guarantee that this type is complete, if we're
4626 // not processing a decltype expression.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004627 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith213d70b2012-02-18 04:13:32 +00004628 if (RD->isInvalidDecl() || RD->isDependentContext())
John McCall86ff3082010-02-04 22:26:26 +00004629 return Owned(E);
Richard Smith76f3f692012-02-22 02:04:18 +00004630
4631 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
4632 CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD);
John McCallf85e1932011-06-15 23:02:42 +00004633
John McCallf85e1932011-06-15 23:02:42 +00004634 if (Destructor) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00004635 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004636 CheckDestructorAccess(E->getExprLoc(), Destructor,
4637 PDiag(diag::err_access_dtor_temp)
4638 << E->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00004639 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00004640
Richard Smith76f3f692012-02-22 02:04:18 +00004641 // If destructor is trivial, we can avoid the extra copy.
4642 if (Destructor->isTrivial())
4643 return Owned(E);
Richard Smith213d70b2012-02-18 04:13:32 +00004644
John McCall80ee6e82011-11-10 05:35:25 +00004645 // We need a cleanup, but we don't need to remember the temporary.
John McCallf85e1932011-06-15 23:02:42 +00004646 ExprNeedsCleanups = true;
Richard Smith76f3f692012-02-22 02:04:18 +00004647 }
Richard Smith213d70b2012-02-18 04:13:32 +00004648
4649 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smith76f3f692012-02-22 02:04:18 +00004650 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
4651
4652 if (IsDecltype)
4653 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
4654
4655 return Owned(Bind);
Anders Carlssondef11992009-05-30 20:36:53 +00004656}
4657
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004658ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004659Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004660 if (SubExpr.isInvalid())
4661 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004662
John McCall4765fa02010-12-06 08:20:24 +00004663 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004664}
4665
John McCall80ee6e82011-11-10 05:35:25 +00004666Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4667 assert(SubExpr && "sub expression can't be null!");
4668
Eli Friedmand2cce132012-02-02 23:15:15 +00004669 CleanupVarDeclMarking();
4670
John McCall80ee6e82011-11-10 05:35:25 +00004671 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4672 assert(ExprCleanupObjects.size() >= FirstCleanup);
4673 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4674 if (!ExprNeedsCleanups)
4675 return SubExpr;
4676
4677 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4678 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4679 ExprCleanupObjects.size() - FirstCleanup);
4680
4681 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4682 DiscardCleanupsInEvaluationContext();
4683
4684 return E;
4685}
4686
John McCall4765fa02010-12-06 08:20:24 +00004687Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004688 assert(SubStmt && "sub statement can't be null!");
4689
Eli Friedmand2cce132012-02-02 23:15:15 +00004690 CleanupVarDeclMarking();
4691
John McCallf85e1932011-06-15 23:02:42 +00004692 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004693 return SubStmt;
4694
4695 // FIXME: In order to attach the temporaries, wrap the statement into
4696 // a StmtExpr; currently this is only used for asm statements.
4697 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4698 // a new AsmStmtWithTemporaries.
4699 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4700 SourceLocation(),
4701 SourceLocation());
4702 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4703 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004704 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004705}
4706
Richard Smith76f3f692012-02-22 02:04:18 +00004707/// Process the expression contained within a decltype. For such expressions,
4708/// certain semantic checks on temporaries are delayed until this point, and
4709/// are omitted for the 'topmost' call in the decltype expression. If the
4710/// topmost call bound a temporary, strip that temporary off the expression.
4711ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
4712 ExpressionEvaluationContextRecord &Rec = ExprEvalContexts.back();
4713 assert(Rec.IsDecltype && "not in a decltype expression");
4714
4715 // C++11 [expr.call]p11:
4716 // If a function call is a prvalue of object type,
4717 // -- if the function call is either
4718 // -- the operand of a decltype-specifier, or
4719 // -- the right operand of a comma operator that is the operand of a
4720 // decltype-specifier,
4721 // a temporary object is not introduced for the prvalue.
4722
4723 // Recursively rebuild ParenExprs and comma expressions to strip out the
4724 // outermost CXXBindTemporaryExpr, if any.
4725 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4726 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
4727 if (SubExpr.isInvalid())
4728 return ExprError();
4729 if (SubExpr.get() == PE->getSubExpr())
4730 return Owned(E);
4731 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take());
4732 }
4733 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4734 if (BO->getOpcode() == BO_Comma) {
4735 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
4736 if (RHS.isInvalid())
4737 return ExprError();
4738 if (RHS.get() == BO->getRHS())
4739 return Owned(E);
4740 return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(),
4741 BO_Comma, BO->getType(),
4742 BO->getValueKind(),
4743 BO->getObjectKind(),
4744 BO->getOperatorLoc()));
4745 }
4746 }
4747
4748 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
4749 if (TopBind)
4750 E = TopBind->getSubExpr();
4751
4752 // Disable the special decltype handling now.
4753 Rec.IsDecltype = false;
4754
4755 // Perform the semantic checks we delayed until this point.
4756 CallExpr *TopCall = dyn_cast<CallExpr>(E);
4757 for (unsigned I = 0, N = Rec.DelayedDecltypeCalls.size(); I != N; ++I) {
4758 CallExpr *Call = Rec.DelayedDecltypeCalls[I];
4759 if (Call == TopCall)
4760 continue;
4761
4762 if (CheckCallReturnType(Call->getCallReturnType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004763 Call->getLocStart(),
Richard Smith76f3f692012-02-22 02:04:18 +00004764 Call, Call->getDirectCallee()))
4765 return ExprError();
4766 }
4767
4768 // Now all relevant types are complete, check the destructors are accessible
4769 // and non-deleted, and annotate them on the temporaries.
4770 for (unsigned I = 0, N = Rec.DelayedDecltypeBinds.size(); I != N; ++I) {
4771 CXXBindTemporaryExpr *Bind = Rec.DelayedDecltypeBinds[I];
4772 if (Bind == TopBind)
4773 continue;
4774
4775 CXXTemporary *Temp = Bind->getTemporary();
4776
4777 CXXRecordDecl *RD =
4778 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
4779 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4780 Temp->setDestructor(Destructor);
4781
Richard Smith2f68ca02012-05-11 22:20:10 +00004782 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
4783 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smith76f3f692012-02-22 02:04:18 +00004784 PDiag(diag::err_access_dtor_temp)
Richard Smith2f68ca02012-05-11 22:20:10 +00004785 << Bind->getType());
4786 DiagnoseUseOfDecl(Destructor, Bind->getExprLoc());
Richard Smith76f3f692012-02-22 02:04:18 +00004787
4788 // We need a cleanup, but we don't need to remember the temporary.
4789 ExprNeedsCleanups = true;
4790 }
4791
4792 // Possibly strip off the top CXXBindTemporaryExpr.
4793 return Owned(E);
4794}
4795
John McCall60d7b3a2010-08-24 06:29:42 +00004796ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004797Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004798 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004799 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004800 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004801 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004802 if (Result.isInvalid()) return ExprError();
4803 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004804
John McCall3c3b7f92011-10-25 17:37:35 +00004805 Result = CheckPlaceholderExpr(Base);
4806 if (Result.isInvalid()) return ExprError();
4807 Base = Result.take();
4808
John McCall9ae2f072010-08-23 23:25:46 +00004809 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004810 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004811 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004812 // If we have a pointer to a dependent type and are using the -> operator,
4813 // the object type is the type that the pointer points to. We might still
4814 // have enough information about that type to do something useful.
4815 if (OpKind == tok::arrow)
4816 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4817 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004818
John McCallb3d87482010-08-24 05:47:05 +00004819 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004820 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004821 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004822 }
Mike Stump1eb44332009-09-09 15:08:12 +00004823
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004824 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004825 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004826 // returned, with the original second operand.
4827 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004828 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004829 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004830 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004831 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004832
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004833 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004834 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4835 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004836 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004837 Base = Result.get();
4838 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004839 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004840 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004841 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004842 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004843 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004844 for (unsigned i = 0; i < Locations.size(); i++)
4845 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004846 return ExprError();
4847 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004848 }
Mike Stump1eb44332009-09-09 15:08:12 +00004849
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004850 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
Douglas Gregor31658df2009-11-20 19:58:21 +00004851 BaseType = BaseType->getPointeeType();
4852 }
Mike Stump1eb44332009-09-09 15:08:12 +00004853
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004854 // Objective-C properties allow "." access on Objective-C pointer types,
4855 // so adjust the base type to the object type itself.
4856 if (BaseType->isObjCObjectPointerType())
4857 BaseType = BaseType->getPointeeType();
4858
4859 // C++ [basic.lookup.classref]p2:
4860 // [...] If the type of the object expression is of pointer to scalar
4861 // type, the unqualified-id is looked up in the context of the complete
4862 // postfix-expression.
4863 //
4864 // This also indicates that we could be parsing a pseudo-destructor-name.
4865 // Note that Objective-C class and object types can be pseudo-destructor
4866 // expressions or normal member (ivar or property) access expressions.
4867 if (BaseType->isObjCObjectOrInterfaceType()) {
4868 MayBePseudoDestructor = true;
4869 } else if (!BaseType->isRecordType()) {
John McCallb3d87482010-08-24 05:47:05 +00004870 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004871 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004872 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004873 }
Mike Stump1eb44332009-09-09 15:08:12 +00004874
Douglas Gregorcefc3af2012-04-16 07:05:22 +00004875 // The object type must be complete (or dependent), or
4876 // C++11 [expr.prim.general]p3:
4877 // Unlike the object expression in other contexts, *this is not required to
4878 // be of complete type for purposes of class member access (5.2.5) outside
4879 // the member function body.
Douglas Gregor03c57052009-11-17 05:17:33 +00004880 if (!BaseType->isDependentType() &&
Douglas Gregorcefc3af2012-04-16 07:05:22 +00004881 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00004882 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor03c57052009-11-17 05:17:33 +00004883 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004884
Douglas Gregorc68afe22009-09-03 21:38:09 +00004885 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004886 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004887 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004888 // type C (or of pointer to a class type C), the unqualified-id is looked
4889 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004890 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004891 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004892}
4893
John McCall60d7b3a2010-08-24 06:29:42 +00004894ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004895 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004896 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004897 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4898 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004899 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004900
Douglas Gregor77549082010-02-24 21:29:12 +00004901 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004902 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004903 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004904 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004905 /*RPLoc*/ ExpectedLParenLoc);
4906}
Douglas Gregord4dca082010-02-24 18:44:31 +00004907
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004908static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie91ec7892011-12-16 16:03:09 +00004909 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004910 if (Base->hasPlaceholderType()) {
4911 ExprResult result = S.CheckPlaceholderExpr(Base);
4912 if (result.isInvalid()) return true;
4913 Base = result.take();
4914 }
4915 ObjectType = Base->getType();
4916
David Blaikie91ec7892011-12-16 16:03:09 +00004917 // C++ [expr.pseudo]p2:
4918 // The left-hand side of the dot operator shall be of scalar type. The
4919 // left-hand side of the arrow operator shall be of pointer to scalar type.
4920 // This scalar type is the object type.
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004921 // Note that this is rather different from the normal handling for the
4922 // arrow operator.
David Blaikie91ec7892011-12-16 16:03:09 +00004923 if (OpKind == tok::arrow) {
4924 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4925 ObjectType = Ptr->getPointeeType();
4926 } else if (!Base->isTypeDependent()) {
4927 // The user wrote "p->" when she probably meant "p."; fix it.
4928 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4929 << ObjectType << true
4930 << FixItHint::CreateReplacement(OpLoc, ".");
4931 if (S.isSFINAEContext())
4932 return true;
4933
4934 OpKind = tok::period;
4935 }
4936 }
4937
4938 return false;
4939}
4940
John McCall60d7b3a2010-08-24 06:29:42 +00004941ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004942 SourceLocation OpLoc,
4943 tok::TokenKind OpKind,
4944 const CXXScopeSpec &SS,
4945 TypeSourceInfo *ScopeTypeInfo,
4946 SourceLocation CCLoc,
4947 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004948 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004949 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004950 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004951
Eli Friedman8c9fe202012-01-25 04:35:06 +00004952 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004953 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4954 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004955
Douglas Gregorb57fb492010-02-24 22:38:50 +00004956 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004957 if (getLangOpts().MicrosoftMode && ObjectType->isVoidType())
Nico Weber2d757ec2012-01-23 06:08:16 +00004958 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Nico Weberdf1be862012-01-23 05:50:57 +00004959 else
4960 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4961 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004962 return ExprError();
4963 }
4964
4965 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004966 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004967 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004968 if (DestructedTypeInfo) {
4969 QualType DestructedType = DestructedTypeInfo->getType();
4970 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004971 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004972 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4973 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4974 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4975 << ObjectType << DestructedType << Base->getSourceRange()
4976 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004977
John McCallf85e1932011-06-15 23:02:42 +00004978 // Recover by setting the destructed type to the object type.
4979 DestructedType = ObjectType;
4980 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004981 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004982 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4983 } else if (DestructedType.getObjCLifetime() !=
4984 ObjectType.getObjCLifetime()) {
4985
4986 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4987 // Okay: just pretend that the user provided the correctly-qualified
4988 // type.
4989 } else {
4990 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4991 << ObjectType << DestructedType << Base->getSourceRange()
4992 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4993 }
4994
4995 // Recover by setting the destructed type to the object type.
4996 DestructedType = ObjectType;
4997 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4998 DestructedTypeStart);
4999 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5000 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005001 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00005002 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005003
Douglas Gregorb57fb492010-02-24 22:38:50 +00005004 // C++ [expr.pseudo]p2:
5005 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
5006 // form
5007 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005008 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00005009 //
5010 // shall designate the same scalar type.
5011 if (ScopeTypeInfo) {
5012 QualType ScopeType = ScopeTypeInfo->getType();
5013 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00005014 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005015
Abramo Bagnarabd054db2010-05-20 10:00:11 +00005016 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00005017 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00005018 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00005019 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005020
Douglas Gregorb57fb492010-02-24 22:38:50 +00005021 ScopeType = QualType();
5022 ScopeTypeInfo = 0;
5023 }
5024 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005025
John McCall9ae2f072010-08-23 23:25:46 +00005026 Expr *Result
5027 = new (Context) CXXPseudoDestructorExpr(Context, Base,
5028 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00005029 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00005030 ScopeTypeInfo,
5031 CCLoc,
5032 TildeLoc,
5033 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005034
Douglas Gregorb57fb492010-02-24 22:38:50 +00005035 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00005036 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005037
John McCall9ae2f072010-08-23 23:25:46 +00005038 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00005039}
5040
John McCall60d7b3a2010-08-24 06:29:42 +00005041ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00005042 SourceLocation OpLoc,
5043 tok::TokenKind OpKind,
5044 CXXScopeSpec &SS,
5045 UnqualifiedId &FirstTypeName,
5046 SourceLocation CCLoc,
5047 SourceLocation TildeLoc,
5048 UnqualifiedId &SecondTypeName,
5049 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00005050 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5051 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5052 "Invalid first type name in pseudo-destructor");
5053 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5054 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5055 "Invalid second type name in pseudo-destructor");
5056
Eli Friedman8c9fe202012-01-25 04:35:06 +00005057 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00005058 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5059 return ExprError();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005060
5061 // Compute the object type that we should use for name lookup purposes. Only
5062 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00005063 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005064 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00005065 if (ObjectType->isRecordType())
5066 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00005067 else if (ObjectType->isDependentType())
5068 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005069 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005070
5071 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00005072 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00005073 QualType DestructedType;
5074 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005075 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00005076 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005077 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00005078 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00005079 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005080 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005081 ((SS.isSet() && !computeDeclContext(SS, false)) ||
5082 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005083 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005084 // couldn't find anything useful in scope. Just store the identifier and
5085 // it's location, and we'll perform (qualified) name lookup again at
5086 // template instantiation time.
5087 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5088 SecondTypeName.StartLocation);
5089 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005090 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00005091 diag::err_pseudo_dtor_destructor_non_type)
5092 << SecondTypeName.Identifier << ObjectType;
5093 if (isSFINAEContext())
5094 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005095
Douglas Gregor77549082010-02-24 21:29:12 +00005096 // Recover by assuming we had the right type all along.
5097 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00005098 } else
Douglas Gregor77549082010-02-24 21:29:12 +00005099 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005100 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00005101 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00005102 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00005103 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5104 TemplateId->getTemplateArgs(),
5105 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00005106 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005107 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00005108 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00005109 TemplateId->TemplateNameLoc,
5110 TemplateId->LAngleLoc,
5111 TemplateArgsPtr,
5112 TemplateId->RAngleLoc);
5113 if (T.isInvalid() || !T.get()) {
5114 // Recover by assuming we had the right type all along.
5115 DestructedType = ObjectType;
5116 } else
5117 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005118 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005119
5120 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00005121 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005122 if (!DestructedType.isNull()) {
5123 if (!DestructedTypeInfo)
5124 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00005125 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005126 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5127 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005128
Douglas Gregorb57fb492010-02-24 22:38:50 +00005129 // Convert the name of the scope type (the type prior to '::') into a type.
5130 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00005131 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005132 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00005133 FirstTypeName.Identifier) {
5134 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005135 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00005136 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00005137 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00005138 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005139 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00005140 diag::err_pseudo_dtor_destructor_non_type)
5141 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005142
Douglas Gregorb57fb492010-02-24 22:38:50 +00005143 if (isSFINAEContext())
5144 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005145
Douglas Gregorb57fb492010-02-24 22:38:50 +00005146 // Just drop this type. It's unnecessary anyway.
5147 ScopeType = QualType();
5148 } else
5149 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005150 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00005151 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00005152 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00005153 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5154 TemplateId->getTemplateArgs(),
5155 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00005156 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005157 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00005158 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00005159 TemplateId->TemplateNameLoc,
5160 TemplateId->LAngleLoc,
5161 TemplateArgsPtr,
5162 TemplateId->RAngleLoc);
5163 if (T.isInvalid() || !T.get()) {
5164 // Recover by dropping this type.
5165 ScopeType = QualType();
5166 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005167 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005168 }
5169 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005170
Douglas Gregorb4a418f2010-02-24 23:02:30 +00005171 if (!ScopeType.isNull() && !ScopeTypeInfo)
5172 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5173 FirstTypeName.StartLocation);
5174
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005175
John McCall9ae2f072010-08-23 23:25:46 +00005176 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00005177 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005178 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00005179}
5180
David Blaikie91ec7892011-12-16 16:03:09 +00005181ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5182 SourceLocation OpLoc,
5183 tok::TokenKind OpKind,
5184 SourceLocation TildeLoc,
5185 const DeclSpec& DS,
5186 bool HasTrailingLParen) {
Eli Friedman8c9fe202012-01-25 04:35:06 +00005187 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00005188 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5189 return ExprError();
5190
5191 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5192
5193 TypeLocBuilder TLB;
5194 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5195 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5196 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5197 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5198
5199 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5200 0, SourceLocation(), TildeLoc,
5201 Destructed, HasTrailingLParen);
5202}
5203
John Wiegley429bb272011-04-08 18:41:53 +00005204ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman3f01c8a2012-03-01 01:30:04 +00005205 CXXConversionDecl *Method,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005206 bool HadMultipleCandidates) {
Eli Friedman23f02672012-03-01 04:01:32 +00005207 if (Method->getParent()->isLambda() &&
5208 Method->getConversionType()->isBlockPointerType()) {
5209 // This is a lambda coversion to block pointer; check if the argument
5210 // is a LambdaExpr.
5211 Expr *SubE = E;
5212 CastExpr *CE = dyn_cast<CastExpr>(SubE);
5213 if (CE && CE->getCastKind() == CK_NoOp)
5214 SubE = CE->getSubExpr();
5215 SubE = SubE->IgnoreParens();
5216 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5217 SubE = BE->getSubExpr();
5218 if (isa<LambdaExpr>(SubE)) {
5219 // For the conversion to block pointer on a lambda expression, we
5220 // construct a special BlockLiteral instead; this doesn't really make
5221 // a difference in ARC, but outside of ARC the resulting block literal
5222 // follows the normal lifetime rules for block literals instead of being
5223 // autoreleased.
5224 DiagnosticErrorTrap Trap(Diags);
5225 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5226 E->getExprLoc(),
5227 Method, E);
5228 if (Exp.isInvalid())
5229 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5230 return Exp;
5231 }
5232 }
5233
5234
John Wiegley429bb272011-04-08 18:41:53 +00005235 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
5236 FoundDecl, Method);
5237 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005238 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00005239
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005240 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00005241 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnara960809e2011-11-16 22:46:05 +00005242 SourceLocation(), Context.BoundMemberTy,
John McCallf89e55a2010-11-18 06:31:45 +00005243 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005244 if (HadMultipleCandidates)
5245 ME->setHadMultipleCandidates(true);
5246
John McCallf89e55a2010-11-18 06:31:45 +00005247 QualType ResultType = Method->getResultType();
5248 ExprValueKind VK = Expr::getValueKindForType(ResultType);
5249 ResultType = ResultType.getNonLValueExprType(Context);
5250
Eli Friedman5f2987c2012-02-02 03:46:19 +00005251 MarkFunctionReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005252 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00005253 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00005254 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005255 return CE;
5256}
5257
Sebastian Redl2e156222010-09-10 20:55:43 +00005258ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5259 SourceLocation RParen) {
Richard Smithe6975e92012-04-17 00:58:00 +00005260 CanThrowResult CanThrow = canThrow(Operand);
Sebastian Redl2e156222010-09-10 20:55:43 +00005261 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
Richard Smithe6975e92012-04-17 00:58:00 +00005262 CanThrow, KeyLoc, RParen));
Sebastian Redl2e156222010-09-10 20:55:43 +00005263}
5264
5265ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5266 Expr *Operand, SourceLocation RParen) {
5267 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00005268}
5269
Eli Friedmane26073c2012-05-24 22:04:19 +00005270static bool IsSpecialDiscardedValue(Expr *E) {
5271 // In C++11, discarded-value expressions of a certain form are special,
5272 // according to [expr]p10:
5273 // The lvalue-to-rvalue conversion (4.1) is applied only if the
5274 // expression is an lvalue of volatile-qualified type and it has
5275 // one of the following forms:
5276 E = E->IgnoreParens();
5277
Eli Friedman02180682012-05-24 22:36:31 +00005278 // - id-expression (5.1.1),
Eli Friedmane26073c2012-05-24 22:04:19 +00005279 if (isa<DeclRefExpr>(E))
5280 return true;
5281
Eli Friedman02180682012-05-24 22:36:31 +00005282 // - subscripting (5.2.1),
Eli Friedmane26073c2012-05-24 22:04:19 +00005283 if (isa<ArraySubscriptExpr>(E))
5284 return true;
5285
Eli Friedman02180682012-05-24 22:36:31 +00005286 // - class member access (5.2.5),
Eli Friedmane26073c2012-05-24 22:04:19 +00005287 if (isa<MemberExpr>(E))
5288 return true;
5289
Eli Friedman02180682012-05-24 22:36:31 +00005290 // - indirection (5.3.1),
Eli Friedmane26073c2012-05-24 22:04:19 +00005291 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
5292 if (UO->getOpcode() == UO_Deref)
5293 return true;
5294
5295 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedman02180682012-05-24 22:36:31 +00005296 // - pointer-to-member operation (5.5),
Eli Friedmane26073c2012-05-24 22:04:19 +00005297 if (BO->isPtrMemOp())
5298 return true;
5299
Eli Friedman02180682012-05-24 22:36:31 +00005300 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmane26073c2012-05-24 22:04:19 +00005301 if (BO->getOpcode() == BO_Comma)
5302 return IsSpecialDiscardedValue(BO->getRHS());
5303 }
5304
Eli Friedman02180682012-05-24 22:36:31 +00005305 // - conditional expression (5.16) where both the second and the third
Eli Friedmane26073c2012-05-24 22:04:19 +00005306 // operands are one of the above, or
5307 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
5308 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
5309 IsSpecialDiscardedValue(CO->getFalseExpr());
5310 // The related edge case of "*x ?: *x".
5311 if (BinaryConditionalOperator *BCO =
5312 dyn_cast<BinaryConditionalOperator>(E)) {
5313 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
5314 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
5315 IsSpecialDiscardedValue(BCO->getFalseExpr());
5316 }
5317
5318 // Objective-C++ extensions to the rule.
5319 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
5320 return true;
5321
5322 return false;
5323}
5324
John McCallf6a16482010-12-04 03:47:34 +00005325/// Perform the conversions required for an expression used in a
5326/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00005327ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall3c3b7f92011-10-25 17:37:35 +00005328 if (E->hasPlaceholderType()) {
5329 ExprResult result = CheckPlaceholderExpr(E);
5330 if (result.isInvalid()) return Owned(E);
5331 E = result.take();
5332 }
5333
John McCalla878cda2010-12-02 02:07:15 +00005334 // C99 6.3.2.1:
5335 // [Except in specific positions,] an lvalue that does not have
5336 // array type is converted to the value stored in the
5337 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00005338 if (E->isRValue()) {
5339 // In C, function designators (i.e. expressions of function type)
5340 // are r-values, but we still want to do function-to-pointer decay
5341 // on them. This is both technically correct and convenient for
5342 // some clients.
David Blaikie4e4d0842012-03-11 07:00:24 +00005343 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalle6d134b2011-06-27 21:24:11 +00005344 return DefaultFunctionArrayConversion(E);
5345
5346 return Owned(E);
5347 }
John McCalla878cda2010-12-02 02:07:15 +00005348
Eli Friedmane26073c2012-05-24 22:04:19 +00005349 if (getLangOpts().CPlusPlus) {
5350 // The C++11 standard defines the notion of a discarded-value expression;
5351 // normally, we don't need to do anything to handle it, but if it is a
5352 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
5353 // conversion.
5354 if (getLangOpts().CPlusPlus0x && E->isGLValue() &&
5355 E->getType().isVolatileQualified() &&
5356 IsSpecialDiscardedValue(E)) {
5357 ExprResult Res = DefaultLvalueConversion(E);
5358 if (Res.isInvalid())
5359 return Owned(E);
5360 E = Res.take();
5361 }
5362 return Owned(E);
5363 }
John McCallf6a16482010-12-04 03:47:34 +00005364
5365 // GCC seems to also exclude expressions of incomplete enum type.
5366 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5367 if (!T->getDecl()->isComplete()) {
5368 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00005369 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
5370 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00005371 }
5372 }
5373
John Wiegley429bb272011-04-08 18:41:53 +00005374 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5375 if (Res.isInvalid())
5376 return Owned(E);
5377 E = Res.take();
5378
John McCall85515d62010-12-04 12:29:11 +00005379 if (!E->getType()->isVoidType())
5380 RequireCompleteType(E->getExprLoc(), E->getType(),
5381 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00005382 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00005383}
5384
David Blaikiedef07622012-05-16 04:20:04 +00005385ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC) {
John Wiegley429bb272011-04-08 18:41:53 +00005386 ExprResult FullExpr = Owned(FE);
5387
5388 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00005389 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00005390
John Wiegley429bb272011-04-08 18:41:53 +00005391 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00005392 return ExprError();
5393
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00005394 // Top-level message sends default to 'id' when we're in a debugger.
David Blaikie4e4d0842012-03-11 07:00:24 +00005395 if (getLangOpts().DebuggerCastResultToId &&
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00005396 FullExpr.get()->getType() == Context.UnknownAnyTy &&
5397 isa<ObjCMessageExpr>(FullExpr.get())) {
5398 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
5399 if (FullExpr.isInvalid())
5400 return ExprError();
5401 }
5402
John McCallfb8721c2011-04-10 19:13:55 +00005403 FullExpr = CheckPlaceholderExpr(FullExpr.take());
5404 if (FullExpr.isInvalid())
5405 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00005406
John Wiegley429bb272011-04-08 18:41:53 +00005407 FullExpr = IgnoredValueConversions(FullExpr.take());
5408 if (FullExpr.isInvalid())
5409 return ExprError();
5410
David Blaikiedef07622012-05-16 04:20:04 +00005411 CheckImplicitConversions(FullExpr.get(), CC);
John McCall4765fa02010-12-06 08:20:24 +00005412 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00005413}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00005414
5415StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
5416 if (!FullStmt) return StmtError();
5417
John McCall4765fa02010-12-06 08:20:24 +00005418 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00005419}
Francois Pichet1e862692011-05-06 20:48:22 +00005420
Douglas Gregorba0513d2011-10-25 01:33:02 +00005421Sema::IfExistsResult
5422Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
5423 CXXScopeSpec &SS,
5424 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet1e862692011-05-06 20:48:22 +00005425 DeclarationName TargetName = TargetNameInfo.getName();
5426 if (!TargetName)
Douglas Gregor3896fc52011-10-24 22:31:10 +00005427 return IER_DoesNotExist;
Douglas Gregorba0513d2011-10-25 01:33:02 +00005428
Douglas Gregor3896fc52011-10-24 22:31:10 +00005429 // If the name itself is dependent, then the result is dependent.
5430 if (TargetName.isDependentName())
5431 return IER_Dependent;
Douglas Gregorba0513d2011-10-25 01:33:02 +00005432
Francois Pichet1e862692011-05-06 20:48:22 +00005433 // Do the redeclaration lookup in the current scope.
5434 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
5435 Sema::NotForRedeclaration);
Douglas Gregor3896fc52011-10-24 22:31:10 +00005436 LookupParsedName(R, S, &SS);
Francois Pichet1e862692011-05-06 20:48:22 +00005437 R.suppressDiagnostics();
Douglas Gregor3896fc52011-10-24 22:31:10 +00005438
5439 switch (R.getResultKind()) {
5440 case LookupResult::Found:
5441 case LookupResult::FoundOverloaded:
5442 case LookupResult::FoundUnresolvedValue:
5443 case LookupResult::Ambiguous:
5444 return IER_Exists;
5445
5446 case LookupResult::NotFound:
5447 return IER_DoesNotExist;
5448
5449 case LookupResult::NotFoundInCurrentInstantiation:
5450 return IER_Dependent;
5451 }
David Blaikie7530c032012-01-17 06:56:22 +00005452
5453 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet1e862692011-05-06 20:48:22 +00005454}
Douglas Gregorba0513d2011-10-25 01:33:02 +00005455
Douglas Gregor65019ac2011-10-25 03:44:56 +00005456Sema::IfExistsResult
5457Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5458 bool IsIfExists, CXXScopeSpec &SS,
5459 UnqualifiedId &Name) {
Douglas Gregorba0513d2011-10-25 01:33:02 +00005460 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor65019ac2011-10-25 03:44:56 +00005461
5462 // Check for unexpanded parameter packs.
5463 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5464 collectUnexpandedParameterPacks(SS, Unexpanded);
5465 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
5466 if (!Unexpanded.empty()) {
5467 DiagnoseUnexpandedParameterPacks(KeywordLoc,
5468 IsIfExists? UPPC_IfExists
5469 : UPPC_IfNotExists,
5470 Unexpanded);
5471 return IER_Error;
5472 }
5473
Douglas Gregorba0513d2011-10-25 01:33:02 +00005474 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
5475}