blob: 0e5d630e4af8b87c082f666880aaf16a798f604b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall2a7fb272010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
John McCall469a1eb2011-02-02 13:00:07 +000019#include "clang/Sema/ScopeInfo.h"
Richard Smith7a614d82011-06-11 17:19:42 +000020#include "clang/Sema/Scope.h"
John McCall2a7fb272010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Steve Naroff210679c2007-08-25 14:02:58 +000022#include "clang/AST/ASTContext.h"
Nick Lewyckyfca84b22012-01-24 21:15:41 +000023#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000025#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000026#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000027#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000028#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000031#include "clang/Lex/Preprocessor.h"
David Blaikie91ec7892011-12-16 16:03:09 +000032#include "TypeLocBuilder.h"
Sebastian Redlbd45d252012-02-16 12:59:47 +000033#include "llvm/ADT/APInt.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000034#include "llvm/ADT/STLExtras.h"
Chandler Carruth73e0a912011-05-01 07:23:17 +000035#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000037using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000038
John McCallb3d87482010-08-24 05:47:05 +000039ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000040 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000041 SourceLocation NameLoc,
42 Scope *S, CXXScopeSpec &SS,
43 ParsedType ObjectTypePtr,
44 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000045 // Determine where to perform name lookup.
46
47 // FIXME: This area of the standard is very messy, and the current
48 // wording is rather unclear about which scopes we search for the
49 // destructor name; see core issues 399 and 555. Issue 399 in
50 // particular shows where the current description of destructor name
51 // lookup is completely out of line with existing practice, e.g.,
52 // this appears to be ill-formed:
53 //
54 // namespace N {
55 // template <typename T> struct S {
56 // ~S();
57 // };
58 // }
59 //
60 // void f(N::S<int>* s) {
61 // s->N::S<int>::~S();
62 // }
63 //
Douglas Gregor93649fd2010-02-23 00:15:22 +000064 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +000065 // For this reason, we're currently only doing the C++03 version of this
66 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +000067 QualType SearchType;
68 DeclContext *LookupCtx = 0;
69 bool isDependent = false;
70 bool LookInScope = false;
71
72 // If we have an object type, it's because we are in a
73 // pseudo-destructor-expression or a member access expression, and
74 // we know what type we're looking for.
75 if (ObjectTypePtr)
76 SearchType = GetTypeFromParser(ObjectTypePtr);
77
78 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +000079 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000080
Douglas Gregor93649fd2010-02-23 00:15:22 +000081 bool AlreadySearched = false;
82 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +000083 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000084 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +000085 // the type-names are looked up as types in the scope designated by the
86 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +000087 //
88 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +000089 //
90 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +000091 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +000092 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +000093 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +000094 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000095 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +000096 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +000097 //
Sebastian Redlc0fee502010-07-07 23:17:38 +000098 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000099 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +0000100 // nested-name-specifier.
101 DeclContext *DC = computeDeclContext(SS, EnteringContext);
102 if (DC && DC->isFileContext()) {
103 AlreadySearched = true;
104 LookupCtx = DC;
105 isDependent = false;
106 } else if (DC && isa<CXXRecordDecl>(DC))
107 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000108
Sebastian Redlc0fee502010-07-07 23:17:38 +0000109 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000110 NestedNameSpecifier *Prefix = 0;
111 if (AlreadySearched) {
112 // Nothing left to do.
113 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
114 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000115 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000116 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
117 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000118 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000119 LookupCtx = computeDeclContext(SearchType);
120 isDependent = SearchType->isDependentType();
121 } else {
122 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000123 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000124 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000125
Douglas Gregoredc90502010-02-25 04:46:04 +0000126 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000127 } else if (ObjectTypePtr) {
128 // C++ [basic.lookup.classref]p3:
129 // If the unqualified-id is ~type-name, the type-name is looked up
130 // in the context of the entire postfix-expression. If the type T
131 // of the object expression is of a class type C, the type-name is
132 // also looked up in the scope of class C. At least one of the
133 // lookups shall find a name that refers to (possibly
134 // cv-qualified) T.
135 LookupCtx = computeDeclContext(SearchType);
136 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000137 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000138 "Caller should have completed object type");
139
140 LookInScope = true;
141 } else {
142 // Perform lookup into the current scope (only).
143 LookInScope = true;
144 }
145
Douglas Gregor7ec18732011-03-04 22:32:08 +0000146 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregor124b8782010-02-16 19:09:40 +0000147 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
148 for (unsigned Step = 0; Step != 2; ++Step) {
149 // Look for the name first in the computed lookup context (if we
Douglas Gregor7ec18732011-03-04 22:32:08 +0000150 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregor124b8782010-02-16 19:09:40 +0000151 // we're allowed to look there).
152 Found.clear();
153 if (Step == 0 && LookupCtx)
154 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000155 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000156 LookupName(Found, S);
157 else
158 continue;
159
160 // FIXME: Should we be suppressing ambiguities here?
161 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000162 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000163
164 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
165 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000166
167 if (SearchType.isNull() || SearchType->isDependentType() ||
168 Context.hasSameUnqualifiedType(T, SearchType)) {
169 // We found our type!
170
John McCallb3d87482010-08-24 05:47:05 +0000171 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000172 }
John Wiegley36784e72011-03-08 08:13:22 +0000173
Douglas Gregor7ec18732011-03-04 22:32:08 +0000174 if (!SearchType.isNull())
175 NonMatchingTypeDecl = Type;
Douglas Gregor124b8782010-02-16 19:09:40 +0000176 }
177
178 // If the name that we found is a class template name, and it is
179 // the same name as the template name in the last part of the
180 // nested-name-specifier (if present) or the object type, then
181 // this is the destructor for that class.
182 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000183 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000184 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
185 QualType MemberOfType;
186 if (SS.isSet()) {
187 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
188 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000189 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
190 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000191 }
192 }
193 if (MemberOfType.isNull())
194 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000195
Douglas Gregor124b8782010-02-16 19:09:40 +0000196 if (MemberOfType.isNull())
197 continue;
198
199 // We're referring into a class template specialization. If the
200 // class template we found is the same as the template being
201 // specialized, we found what we are looking for.
202 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
203 if (ClassTemplateSpecializationDecl *Spec
204 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
205 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
206 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000207 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000208 }
209
210 continue;
211 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000212
Douglas Gregor124b8782010-02-16 19:09:40 +0000213 // We're referring to an unresolved class template
214 // specialization. Determine whether we class template we found
215 // is the same as the template being specialized or, if we don't
216 // know which template is being specialized, that it at least
217 // has the same name.
218 if (const TemplateSpecializationType *SpecType
219 = MemberOfType->getAs<TemplateSpecializationType>()) {
220 TemplateName SpecName = SpecType->getTemplateName();
221
222 // The class template we found is the same template being
223 // specialized.
224 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
225 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000226 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000227
228 continue;
229 }
230
231 // The class template we found has the same name as the
232 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000233 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000234 = SpecName.getAsDependentTemplateName()) {
235 if (DepTemplate->isIdentifier() &&
236 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000237 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000238
239 continue;
240 }
241 }
242 }
243 }
244
245 if (isDependent) {
246 // We didn't find our type, but that's okay: it's dependent
247 // anyway.
Douglas Gregore29425b2011-02-28 22:42:13 +0000248
249 // FIXME: What if we have no nested-name-specifier?
250 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
251 SS.getWithLocInContext(Context),
252 II, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000253 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000254 }
255
Douglas Gregor7ec18732011-03-04 22:32:08 +0000256 if (NonMatchingTypeDecl) {
257 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
258 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
259 << T << SearchType;
260 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
261 << T;
262 } else if (ObjectTypePtr)
263 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000264 << &II;
Douglas Gregor124b8782010-02-16 19:09:40 +0000265 else
266 Diag(NameLoc, diag::err_destructor_class_name);
267
John McCallb3d87482010-08-24 05:47:05 +0000268 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000269}
270
David Blaikie53a75c02011-12-08 16:13:53 +0000271ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie4db8c442011-12-12 04:13:55 +0000272 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikie53a75c02011-12-08 16:13:53 +0000273 return ParsedType();
274 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
275 && "only get destructor types from declspecs");
276 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
277 QualType SearchType = GetTypeFromParser(ObjectType);
278 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
279 return ParsedType::make(T);
280 }
281
282 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
283 << T << SearchType;
284 return ParsedType();
285}
286
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000287/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000288ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000289 SourceLocation TypeidLoc,
290 TypeSourceInfo *Operand,
291 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000292 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000293 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000294 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000295 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000296 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000297 Qualifiers Quals;
298 QualType T
299 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
300 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000301 if (T->getAs<RecordType>() &&
302 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
303 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000304
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000305 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
306 Operand,
307 SourceRange(TypeidLoc, RParenLoc)));
308}
309
310/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000311ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000312 SourceLocation TypeidLoc,
313 Expr *E,
314 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000315 if (E && !E->isTypeDependent()) {
John McCall6dbba4f2011-10-11 23:14:30 +0000316 if (E->getType()->isPlaceholderType()) {
317 ExprResult result = CheckPlaceholderExpr(E);
318 if (result.isInvalid()) return ExprError();
319 E = result.take();
320 }
321
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000322 QualType T = E->getType();
323 if (const RecordType *RecordT = T->getAs<RecordType>()) {
324 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
325 // C++ [expr.typeid]p3:
326 // [...] If the type of the expression is a class type, the class
327 // shall be completely-defined.
328 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
329 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000330
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000331 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000332 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000333 // polymorphic class type [...] [the] expression is an unevaluated
334 // operand. [...]
Sebastian Redl906082e2010-07-20 04:20:21 +0000335 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Eli Friedmanef331b72012-01-20 01:26:23 +0000336 // The subexpression is potentially evaluated; switch the context
337 // and recheck the subexpression.
338 ExprResult Result = TranformToPotentiallyEvaluated(E);
339 if (Result.isInvalid()) return ExprError();
340 E = Result.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000341
342 // We require a vtable to query the type at run time.
343 MarkVTableUsed(TypeidLoc, RecordD);
344 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000345 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000346
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000347 // C++ [expr.typeid]p4:
348 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000349 // cv-qualified type, the result of the typeid expression refers to a
350 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000351 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000352 Qualifiers Quals;
353 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
354 if (!Context.hasSameType(T, UnqualT)) {
355 T = UnqualT;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000356 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000357 }
358 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000359
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000360 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000361 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000362 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000363}
364
365/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000366ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000367Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
368 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000369 // Find the std::type_info type.
Sebastian Redlce0682f2011-03-31 19:29:24 +0000370 if (!getStdNamespace())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000371 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000372
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000373 if (!CXXTypeInfoDecl) {
374 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
375 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
376 LookupQualifiedName(R, getStdNamespace());
377 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
378 if (!CXXTypeInfoDecl)
379 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
380 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000381
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000382 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000383
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000384 if (isType) {
385 // The operand is a type; handle it as such.
386 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000387 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
388 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000389 if (T.isNull())
390 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000391
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000392 if (!TInfo)
393 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000394
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000395 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000396 }
Mike Stump1eb44332009-09-09 15:08:12 +0000397
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000398 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000399 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000400}
401
Francois Pichet6915c522010-12-27 01:32:00 +0000402/// Retrieve the UuidAttr associated with QT.
403static UuidAttr *GetUuidAttrOfType(QualType QT) {
404 // Optionally remove one level of pointer, reference or array indirection.
John McCallf4c73712011-01-19 06:33:43 +0000405 const Type *Ty = QT.getTypePtr();;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000406 if (QT->isPointerType() || QT->isReferenceType())
407 Ty = QT->getPointeeType().getTypePtr();
408 else if (QT->isArrayType())
409 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
410
Francois Pichet8db75a22011-05-08 10:02:20 +0000411 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichet6915c522010-12-27 01:32:00 +0000412 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet8db75a22011-05-08 10:02:20 +0000413 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
414 E = RD->redecls_end(); I != E; ++I) {
415 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichet6915c522010-12-27 01:32:00 +0000416 return Uuid;
Francois Pichet6915c522010-12-27 01:32:00 +0000417 }
Francois Pichet8db75a22011-05-08 10:02:20 +0000418
Francois Pichet6915c522010-12-27 01:32:00 +0000419 return 0;
Francois Pichet913b7bf2010-12-20 03:51:03 +0000420}
421
Francois Pichet01b7c302010-09-08 12:20:18 +0000422/// \brief Build a Microsoft __uuidof expression with a type operand.
423ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
424 SourceLocation TypeidLoc,
425 TypeSourceInfo *Operand,
426 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000427 if (!Operand->getType()->isDependentType()) {
428 if (!GetUuidAttrOfType(Operand->getType()))
429 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
430 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000431
Francois Pichet01b7c302010-09-08 12:20:18 +0000432 // FIXME: add __uuidof semantic analysis for type operand.
433 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
434 Operand,
435 SourceRange(TypeidLoc, RParenLoc)));
436}
437
438/// \brief Build a Microsoft __uuidof expression with an expression operand.
439ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
440 SourceLocation TypeidLoc,
441 Expr *E,
442 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000443 if (!E->getType()->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000444 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichet6915c522010-12-27 01:32:00 +0000445 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
446 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
447 }
448 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet01b7c302010-09-08 12:20:18 +0000449 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
450 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000451 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000452}
453
454/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
455ExprResult
456Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
457 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000458 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000459 if (!MSVCGuidDecl) {
460 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
461 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
462 LookupQualifiedName(R, Context.getTranslationUnitDecl());
463 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
464 if (!MSVCGuidDecl)
465 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000466 }
467
Francois Pichet01b7c302010-09-08 12:20:18 +0000468 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000469
Francois Pichet01b7c302010-09-08 12:20:18 +0000470 if (isType) {
471 // The operand is a type; handle it as such.
472 TypeSourceInfo *TInfo = 0;
473 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
474 &TInfo);
475 if (T.isNull())
476 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000477
Francois Pichet01b7c302010-09-08 12:20:18 +0000478 if (!TInfo)
479 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
480
481 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
482 }
483
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000484 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000485 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
486}
487
Steve Naroff1b273c42007-09-16 14:56:35 +0000488/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000489ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000490Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000491 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000493 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
494 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000495}
Chris Lattner50dd2892008-02-26 00:51:44 +0000496
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000497/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000498ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000499Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
500 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
501}
502
Chris Lattner50dd2892008-02-26 00:51:44 +0000503/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000504ExprResult
Douglas Gregorbca01b42011-07-06 22:04:06 +0000505Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
506 bool IsThrownVarInScope = false;
507 if (Ex) {
508 // C++0x [class.copymove]p31:
509 // When certain criteria are met, an implementation is allowed to omit the
510 // copy/move construction of a class object [...]
511 //
512 // - in a throw-expression, when the operand is the name of a
513 // non-volatile automatic object (other than a function or catch-
514 // clause parameter) whose scope does not extend beyond the end of the
515 // innermost enclosing try-block (if there is one), the copy/move
516 // operation from the operand to the exception object (15.1) can be
517 // omitted by constructing the automatic object directly into the
518 // exception object
519 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
520 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
521 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
522 for( ; S; S = S->getParent()) {
523 if (S->isDeclScope(Var)) {
524 IsThrownVarInScope = true;
525 break;
526 }
527
528 if (S->getFlags() &
529 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
530 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
531 Scope::TryScope))
532 break;
533 }
534 }
535 }
536 }
537
538 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
539}
540
541ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
542 bool IsThrownVarInScope) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000543 // Don't report an error if 'throw' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +0000544 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000545 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000546 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregorbca01b42011-07-06 22:04:06 +0000547
John Wiegley429bb272011-04-08 18:41:53 +0000548 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregorbca01b42011-07-06 22:04:06 +0000549 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley429bb272011-04-08 18:41:53 +0000550 if (ExRes.isInvalid())
551 return ExprError();
552 Ex = ExRes.take();
553 }
Douglas Gregorbca01b42011-07-06 22:04:06 +0000554
555 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
556 IsThrownVarInScope));
Sebastian Redl972041f2009-04-27 20:27:31 +0000557}
558
559/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000560ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
561 bool IsThrownVarInScope) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000562 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000563 // A throw-expression initializes a temporary object, called the exception
564 // object, the type of which is determined by removing any top-level
565 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000566 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000567 // or "pointer to function returning T", [...]
568 if (E->getType().hasQualifiers())
John Wiegley429bb272011-04-08 18:41:53 +0000569 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000570 E->getValueKind()).take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000571
John Wiegley429bb272011-04-08 18:41:53 +0000572 ExprResult Res = DefaultFunctionArrayConversion(E);
573 if (Res.isInvalid())
574 return ExprError();
575 E = Res.take();
Sebastian Redl972041f2009-04-27 20:27:31 +0000576
577 // If the type of the exception would be an incomplete type or a pointer
578 // to an incomplete type other than (cv) void the program is ill-formed.
579 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000580 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000581 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000582 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000583 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000584 }
585 if (!isPointer || !Ty->isVoidType()) {
586 if (RequireCompleteType(ThrowLoc, Ty,
Douglas Gregord10099e2012-05-04 16:32:21 +0000587 isPointer? diag::err_throw_incomplete_ptr
588 : diag::err_throw_incomplete,
589 E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000590 return ExprError();
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000591
Douglas Gregorbf422f92010-04-15 18:05:39 +0000592 if (RequireNonAbstractType(ThrowLoc, E->getType(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +0000593 diag::err_throw_abstract_type, E))
John Wiegley429bb272011-04-08 18:41:53 +0000594 return ExprError();
Sebastian Redl972041f2009-04-27 20:27:31 +0000595 }
596
John McCallac418162010-04-22 01:10:34 +0000597 // Initialize the exception result. This implicitly weeds out
598 // abstract types or types with inaccessible copy constructors.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000599
600 // C++0x [class.copymove]p31:
601 // When certain criteria are met, an implementation is allowed to omit the
602 // copy/move construction of a class object [...]
603 //
604 // - in a throw-expression, when the operand is the name of a
605 // non-volatile automatic object (other than a function or catch-clause
606 // parameter) whose scope does not extend beyond the end of the
607 // innermost enclosing try-block (if there is one), the copy/move
608 // operation from the operand to the exception object (15.1) can be
609 // omitted by constructing the automatic object directly into the
610 // exception object
611 const VarDecl *NRVOVariable = 0;
612 if (IsThrownVarInScope)
613 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
614
John McCallac418162010-04-22 01:10:34 +0000615 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000616 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregorbca01b42011-07-06 22:04:06 +0000617 /*NRVO=*/NRVOVariable != 0);
John Wiegley429bb272011-04-08 18:41:53 +0000618 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000619 QualType(), E,
620 IsThrownVarInScope);
John McCallac418162010-04-22 01:10:34 +0000621 if (Res.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000622 return ExprError();
623 E = Res.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000624
Eli Friedman5ed9b932010-06-03 20:39:03 +0000625 // If the exception has class type, we need additional handling.
626 const RecordType *RecordTy = Ty->getAs<RecordType>();
627 if (!RecordTy)
John Wiegley429bb272011-04-08 18:41:53 +0000628 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000629 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
630
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000631 // If we are throwing a polymorphic class type or pointer thereof,
632 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000633 MarkVTableUsed(ThrowLoc, RD);
634
Eli Friedman98efb9f2010-10-12 20:32:36 +0000635 // If a pointer is thrown, the referenced object will not be destroyed.
636 if (isPointer)
John Wiegley429bb272011-04-08 18:41:53 +0000637 return Owned(E);
Eli Friedman98efb9f2010-10-12 20:32:36 +0000638
Richard Smith213d70b2012-02-18 04:13:32 +0000639 // If the class has a destructor, we must be able to call it.
640 if (RD->hasIrrelevantDestructor())
John Wiegley429bb272011-04-08 18:41:53 +0000641 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000642
Sebastian Redl28357452012-03-05 19:35:43 +0000643 CXXDestructorDecl *Destructor = LookupDestructor(RD);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000644 if (!Destructor)
John Wiegley429bb272011-04-08 18:41:53 +0000645 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000646
Eli Friedman5f2987c2012-02-02 03:46:19 +0000647 MarkFunctionReferenced(E->getExprLoc(), Destructor);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000648 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000649 PDiag(diag::err_access_dtor_exception) << Ty);
Richard Smith213d70b2012-02-18 04:13:32 +0000650 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
John Wiegley429bb272011-04-08 18:41:53 +0000651 return Owned(E);
Chris Lattner50dd2892008-02-26 00:51:44 +0000652}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000653
Eli Friedman72899c32012-01-07 04:59:52 +0000654QualType Sema::getCurrentThisType() {
655 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000656 QualType ThisTy = CXXThisTypeOverride;
Richard Smith7a614d82011-06-11 17:19:42 +0000657 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
658 if (method && method->isInstance())
659 ThisTy = method->getThisType(Context);
Richard Smith7a614d82011-06-11 17:19:42 +0000660 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000661
Richard Smith7a614d82011-06-11 17:19:42 +0000662 return ThisTy;
John McCall5808ce42011-02-03 08:15:49 +0000663}
664
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000665Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
666 Decl *ContextDecl,
667 unsigned CXXThisTypeQuals,
668 bool Enabled)
669 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
670{
671 if (!Enabled || !ContextDecl)
672 return;
673
674 CXXRecordDecl *Record = 0;
675 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
676 Record = Template->getTemplatedDecl();
677 else
678 Record = cast<CXXRecordDecl>(ContextDecl);
679
680 S.CXXThisTypeOverride
681 = S.Context.getPointerType(
682 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
683
684 this->Enabled = true;
685}
686
687
688Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
689 if (Enabled) {
690 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
691 }
692}
693
Douglas Gregora1f21142012-02-01 17:04:21 +0000694void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) {
Eli Friedman72899c32012-01-07 04:59:52 +0000695 // We don't need to capture this in an unevaluated context.
Douglas Gregora1f21142012-02-01 17:04:21 +0000696 if (ExprEvalContexts.back().Context == Unevaluated && !Explicit)
Eli Friedman72899c32012-01-07 04:59:52 +0000697 return;
698
699 // Otherwise, check that we can capture 'this'.
700 unsigned NumClosures = 0;
701 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000702 if (CapturingScopeInfo *CSI =
703 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
704 if (CSI->CXXThisCaptureIndex != 0) {
705 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman72899c32012-01-07 04:59:52 +0000706 break;
707 }
Douglas Gregora1f21142012-02-01 17:04:21 +0000708
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000709 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000710 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregora1f21142012-02-01 17:04:21 +0000711 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
712 Explicit) {
713 // This closure can capture 'this'; continue looking upwards.
Eli Friedman72899c32012-01-07 04:59:52 +0000714 NumClosures++;
Douglas Gregora1f21142012-02-01 17:04:21 +0000715 Explicit = false;
Eli Friedman72899c32012-01-07 04:59:52 +0000716 continue;
717 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000718 // This context can't implicitly capture 'this'; fail out.
Douglas Gregora1f21142012-02-01 17:04:21 +0000719 Diag(Loc, diag::err_this_capture) << Explicit;
Eli Friedman72899c32012-01-07 04:59:52 +0000720 return;
721 }
Eli Friedman72899c32012-01-07 04:59:52 +0000722 break;
723 }
724
725 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
726 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
727 // contexts.
728 for (unsigned idx = FunctionScopes.size() - 1;
729 NumClosures; --idx, --NumClosures) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000730 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Eli Friedman668165a2012-02-11 02:51:16 +0000731 Expr *ThisExpr = 0;
Douglas Gregor999713e2012-02-18 09:37:24 +0000732 QualType ThisTy = getCurrentThisType();
Eli Friedman668165a2012-02-11 02:51:16 +0000733 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
734 // For lambda expressions, build a field and an initializing expression.
Eli Friedman668165a2012-02-11 02:51:16 +0000735 CXXRecordDecl *Lambda = LSI->Lambda;
736 FieldDecl *Field
737 = FieldDecl::Create(Context, Lambda, Loc, Loc, 0, ThisTy,
738 Context.getTrivialTypeSourceInfo(ThisTy, Loc),
739 0, false, false);
740 Field->setImplicit(true);
741 Field->setAccess(AS_private);
742 Lambda->addDecl(Field);
743 ThisExpr = new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/true);
744 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000745 bool isNested = NumClosures > 1;
Douglas Gregor999713e2012-02-18 09:37:24 +0000746 CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
Eli Friedman72899c32012-01-07 04:59:52 +0000747 }
748}
749
Richard Smith7a614d82011-06-11 17:19:42 +0000750ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000751 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
752 /// is a non-lvalue expression whose value is the address of the object for
753 /// which the function is called.
754
Douglas Gregor341350e2011-10-18 16:47:30 +0000755 QualType ThisTy = getCurrentThisType();
Richard Smith7a614d82011-06-11 17:19:42 +0000756 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000757
Eli Friedman72899c32012-01-07 04:59:52 +0000758 CheckCXXThisCapture(Loc);
Richard Smith7a614d82011-06-11 17:19:42 +0000759 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000760}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000761
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000762bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
763 // If we're outside the body of a member function, then we'll have a specified
764 // type for 'this'.
765 if (CXXThisTypeOverride.isNull())
766 return false;
767
768 // Determine whether we're looking into a class that's currently being
769 // defined.
770 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
771 return Class && Class->isBeingDefined();
772}
773
John McCall60d7b3a2010-08-24 06:29:42 +0000774ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000775Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000776 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000777 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000778 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000779 if (!TypeRep)
780 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000781
John McCall9d125032010-01-15 18:39:57 +0000782 TypeSourceInfo *TInfo;
783 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
784 if (!TInfo)
785 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000786
787 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
788}
789
790/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
791/// Can be interpreted either as function-style casting ("int(x)")
792/// or class type construction ("ClassType(x,y,z)")
793/// or creation of a value-initialized type ("int()").
794ExprResult
795Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
796 SourceLocation LParenLoc,
797 MultiExprArg exprs,
798 SourceLocation RParenLoc) {
799 QualType Ty = TInfo->getType();
Sebastian Redlf53597f2009-03-15 17:47:39 +0000800 unsigned NumExprs = exprs.size();
801 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000802 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000803
Sebastian Redlf53597f2009-03-15 17:47:39 +0000804 if (Ty->isDependentType() ||
Ahmed Charles13a140c2012-02-25 11:00:22 +0000805 CallExpr::hasAnyTypeDependentArguments(
806 llvm::makeArrayRef(Exprs, NumExprs))) {
Sebastian Redlf53597f2009-03-15 17:47:39 +0000807 exprs.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Douglas Gregorab6677e2010-09-08 00:15:04 +0000809 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000810 LParenLoc,
811 Exprs, NumExprs,
812 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000813 }
814
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000815 bool ListInitialization = LParenLoc.isInvalid();
816 assert((!ListInitialization || (NumExprs == 1 && isa<InitListExpr>(Exprs[0])))
817 && "List initialization must have initializer list as expression.");
818 SourceRange FullRange = SourceRange(TyBeginLoc,
819 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
820
Douglas Gregor506ae412009-01-16 18:33:17 +0000821 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000822 // If the expression list is a single expression, the type conversion
823 // expression is equivalent (in definedness, and if defined in meaning) to the
824 // corresponding cast expression.
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000825 if (NumExprs == 1 && !ListInitialization) {
John McCallb45ae252011-10-05 07:41:44 +0000826 Expr *Arg = Exprs[0];
Anders Carlsson0aebc812009-09-09 21:33:21 +0000827 exprs.release();
John McCallb45ae252011-10-05 07:41:44 +0000828 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000829 }
830
Eli Friedmanc60ccf52012-02-29 00:00:28 +0000831 QualType ElemTy = Ty;
832 if (Ty->isArrayType()) {
833 if (!ListInitialization)
834 return ExprError(Diag(TyBeginLoc,
835 diag::err_value_init_for_array_type) << FullRange);
836 ElemTy = Context.getBaseElementType(Ty);
837 }
838
839 if (!Ty->isVoidType() &&
840 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregord10099e2012-05-04 16:32:21 +0000841 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedmanc60ccf52012-02-29 00:00:28 +0000842 return ExprError();
843
844 if (RequireNonAbstractType(TyBeginLoc, Ty,
845 diag::err_allocation_of_abstract_type))
846 return ExprError();
847
Douglas Gregor19311e72010-09-08 21:40:08 +0000848 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
849 InitializationKind Kind
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000850 = NumExprs ? ListInitialization
851 ? InitializationKind::CreateDirectList(TyBeginLoc)
852 : InitializationKind::CreateDirect(TyBeginLoc,
853 LParenLoc, RParenLoc)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000854 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor19311e72010-09-08 21:40:08 +0000855 LParenLoc, RParenLoc);
856 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
857 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redlf53597f2009-03-15 17:47:39 +0000858
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000859 if (!Result.isInvalid() && ListInitialization &&
860 isa<InitListExpr>(Result.get())) {
861 // If the list-initialization doesn't involve a constructor call, we'll get
862 // the initializer-list (with corrected type) back, but that's not what we
863 // want, since it will be treated as an initializer list in further
864 // processing. Explicitly insert a cast here.
865 InitListExpr *List = cast<InitListExpr>(Result.take());
866 Result = Owned(CXXFunctionalCastExpr::Create(Context, List->getType(),
867 Expr::getValueKindForType(TInfo->getType()),
868 TInfo, TyBeginLoc, CK_NoOp,
869 List, /*Path=*/0, RParenLoc));
870 }
871
Douglas Gregor19311e72010-09-08 21:40:08 +0000872 // FIXME: Improve AST representation?
873 return move(Result);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000874}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000875
John McCall6ec278d2011-01-27 09:37:56 +0000876/// doesUsualArrayDeleteWantSize - Answers whether the usual
877/// operator delete[] for the given type has a size_t parameter.
878static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
879 QualType allocType) {
880 const RecordType *record =
881 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
882 if (!record) return false;
883
884 // Try to find an operator delete[] in class scope.
885
886 DeclarationName deleteName =
887 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
888 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
889 S.LookupQualifiedName(ops, record->getDecl());
890
891 // We're just doing this for information.
892 ops.suppressDiagnostics();
893
894 // Very likely: there's no operator delete[].
895 if (ops.empty()) return false;
896
897 // If it's ambiguous, it should be illegal to call operator delete[]
898 // on this thing, so it doesn't matter if we allocate extra space or not.
899 if (ops.isAmbiguous()) return false;
900
901 LookupResult::Filter filter = ops.makeFilter();
902 while (filter.hasNext()) {
903 NamedDecl *del = filter.next()->getUnderlyingDecl();
904
905 // C++0x [basic.stc.dynamic.deallocation]p2:
906 // A template instance is never a usual deallocation function,
907 // regardless of its signature.
908 if (isa<FunctionTemplateDecl>(del)) {
909 filter.erase();
910 continue;
911 }
912
913 // C++0x [basic.stc.dynamic.deallocation]p2:
914 // If class T does not declare [an operator delete[] with one
915 // parameter] but does declare a member deallocation function
916 // named operator delete[] with exactly two parameters, the
917 // second of which has type std::size_t, then this function
918 // is a usual deallocation function.
919 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
920 filter.erase();
921 continue;
922 }
923 }
924 filter.done();
925
926 if (!ops.isSingleResult()) return false;
927
928 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
929 return (del->getNumParams() == 2);
930}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000931
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000932/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
933
934/// E.g.:
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000935/// @code new (memory) int[size][4] @endcode
936/// or
937/// @code ::new Foo(23, "hello") @endcode
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000938///
939/// \param StartLoc The first location of the expression.
940/// \param UseGlobal True if 'new' was prefixed with '::'.
941/// \param PlacementLParen Opening paren of the placement arguments.
942/// \param PlacementArgs Placement new arguments.
943/// \param PlacementRParen Closing paren of the placement arguments.
944/// \param TypeIdParens If the type is in parens, the source range.
945/// \param D The type to be allocated, as well as array dimensions.
946/// \param ConstructorLParen Opening paren of the constructor args, empty if
947/// initializer-list syntax is used.
948/// \param ConstructorArgs Constructor/initialization arguments.
949/// \param ConstructorRParen Closing paren of the constructor args.
John McCall60d7b3a2010-08-24 06:29:42 +0000950ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000951Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000952 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000953 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000954 Declarator &D, Expr *Initializer) {
Richard Smith34b41d92011-02-20 03:19:35 +0000955 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
956
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000957 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000958 // If the specified type is an array, unwrap it and save the expression.
959 if (D.getNumTypeObjects() > 0 &&
960 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
961 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +0000962 if (TypeContainsAuto)
963 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
964 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000965 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000966 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
967 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000968 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +0000969 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
970 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000971
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000972 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000973 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +0000974 }
975
Douglas Gregor043cad22009-09-11 00:18:58 +0000976 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000977 if (ArraySize) {
978 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +0000979 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
980 break;
981
982 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
983 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smith282e7e62012-02-04 09:53:13 +0000984 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
985 Array.NumElts = VerifyIntegerConstantExpression(NumElts, 0,
986 PDiag(diag::err_new_array_nonconst)).take();
987 if (!Array.NumElts)
988 return ExprError();
Douglas Gregor043cad22009-09-11 00:18:58 +0000989 }
990 }
991 }
992 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +0000993
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +0000994 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCallbf1a0282010-06-04 23:28:52 +0000995 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +0000996 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000997 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000998
Sebastian Redl2aed8b82012-02-16 12:22:20 +0000999 SourceRange DirectInitRange;
1000 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1001 DirectInitRange = List->getSourceRange();
1002
Mike Stump1eb44332009-09-09 15:08:12 +00001003 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +00001004 PlacementLParen,
Mike Stump1eb44332009-09-09 15:08:12 +00001005 move(PlacementArgs),
Douglas Gregor3433cf72009-05-21 00:00:09 +00001006 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001007 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +00001008 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001009 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00001010 ArraySize,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001011 DirectInitRange,
1012 Initializer,
Richard Smith34b41d92011-02-20 03:19:35 +00001013 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +00001014}
1015
Sebastian Redlbd45d252012-02-16 12:59:47 +00001016static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1017 Expr *Init) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001018 if (!Init)
1019 return true;
Sebastian Redl1f278052012-02-17 08:42:32 +00001020 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1021 return PLE->getNumExprs() == 0;
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001022 if (isa<ImplicitValueInitExpr>(Init))
1023 return true;
1024 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1025 return !CCE->isListInitialization() &&
1026 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlbd45d252012-02-16 12:59:47 +00001027 else if (Style == CXXNewExpr::ListInit) {
1028 assert(isa<InitListExpr>(Init) &&
1029 "Shouldn't create list CXXConstructExprs for arrays.");
1030 return true;
1031 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001032 return false;
1033}
1034
John McCall60d7b3a2010-08-24 06:29:42 +00001035ExprResult
Douglas Gregor3433cf72009-05-21 00:00:09 +00001036Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
1037 SourceLocation PlacementLParen,
1038 MultiExprArg PlacementArgs,
1039 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001040 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +00001041 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001042 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +00001043 Expr *ArraySize,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001044 SourceRange DirectInitRange,
1045 Expr *Initializer,
Richard Smith34b41d92011-02-20 03:19:35 +00001046 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001047 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001048
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001049 CXXNewExpr::InitializationStyle initStyle;
1050 if (DirectInitRange.isValid()) {
1051 assert(Initializer && "Have parens but no initializer.");
1052 initStyle = CXXNewExpr::CallInit;
1053 } else if (Initializer && isa<InitListExpr>(Initializer))
1054 initStyle = CXXNewExpr::ListInit;
1055 else {
Sebastian Redl428c6202012-02-22 09:07:21 +00001056 // In template instantiation, the initializer could be a CXXDefaultArgExpr
1057 // unwrapped from a CXXConstructExpr that was implicitly built. There is no
1058 // particularly sane way we can handle this (especially since it can even
1059 // occur for array new), so we throw the initializer away and have it be
1060 // rebuilt.
1061 if (Initializer && isa<CXXDefaultArgExpr>(Initializer))
1062 Initializer = 0;
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001063 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1064 isa<CXXConstructExpr>(Initializer)) &&
1065 "Initializer expression that cannot have been implicitly created.");
1066 initStyle = CXXNewExpr::NoInit;
1067 }
1068
1069 Expr **Inits = &Initializer;
1070 unsigned NumInits = Initializer ? 1 : 0;
1071 if (initStyle == CXXNewExpr::CallInit) {
1072 if (ParenListExpr *List = dyn_cast<ParenListExpr>(Initializer)) {
1073 Inits = List->getExprs();
1074 NumInits = List->getNumExprs();
1075 } else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Initializer)){
1076 if (!isa<CXXTemporaryObjectExpr>(CCE)) {
1077 // Can happen in template instantiation. Since this is just an implicit
1078 // construction, we just take it apart and rebuild it.
1079 Inits = CCE->getArgs();
1080 NumInits = CCE->getNumArgs();
1081 }
1082 }
1083 }
1084
Richard Smith34b41d92011-02-20 03:19:35 +00001085 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1086 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001087 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith34b41d92011-02-20 03:19:35 +00001088 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1089 << AllocType << TypeRange);
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001090 if (initStyle == CXXNewExpr::ListInit)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001091 return ExprError(Diag(Inits[0]->getLocStart(),
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001092 diag::err_auto_new_requires_parens)
1093 << AllocType << TypeRange);
1094 if (NumInits > 1) {
1095 Expr *FirstBad = Inits[1];
Daniel Dunbar96a00142012-03-09 18:35:03 +00001096 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith34b41d92011-02-20 03:19:35 +00001097 diag::err_auto_new_ctor_multiple_expressions)
1098 << AllocType << TypeRange);
1099 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001100 Expr *Deduce = Inits[0];
Richard Smitha085da82011-03-17 16:11:59 +00001101 TypeSourceInfo *DeducedType = 0;
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001102 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) ==
Sebastian Redlb832f6d2012-01-23 22:09:39 +00001103 DAR_Failed)
Richard Smith34b41d92011-02-20 03:19:35 +00001104 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001105 << AllocType << Deduce->getType()
1106 << TypeRange << Deduce->getSourceRange());
Richard Smitha085da82011-03-17 16:11:59 +00001107 if (!DeducedType)
1108 return ExprError();
Richard Smith34b41d92011-02-20 03:19:35 +00001109
Richard Smitha085da82011-03-17 16:11:59 +00001110 AllocTypeInfo = DeducedType;
1111 AllocType = AllocTypeInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +00001112 }
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001113
Douglas Gregor3caf04e2010-05-16 16:01:03 +00001114 // Per C++0x [expr.new]p5, the type being constructed may be a
1115 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +00001116 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +00001117 if (const ConstantArrayType *Array
1118 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001119 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1120 Context.getSizeType(),
1121 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +00001122 AllocType = Array->getElementType();
1123 }
1124 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001125
Douglas Gregora0750762010-10-06 16:00:31 +00001126 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1127 return ExprError();
1128
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001129 if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001130 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1131 diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001132 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001133 }
1134
John McCallf85e1932011-06-15 23:02:42 +00001135 // In ARC, infer 'retaining' for the allocated
David Blaikie4e4d0842012-03-11 07:00:24 +00001136 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001137 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1138 AllocType->isObjCLifetimeType()) {
1139 AllocType = Context.getLifetimeQualifiedType(AllocType,
1140 AllocType->getObjCARCImplicitLifetime());
1141 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001142
John McCallf85e1932011-06-15 23:02:42 +00001143 QualType ResultType = Context.getPointerType(AllocType);
1144
Richard Smithf39aec12012-02-04 07:07:42 +00001145 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1146 // integral or enumeration type with a non-negative value."
1147 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1148 // enumeration type, or a class type for which a single non-explicit
1149 // conversion function to integral or unscoped enumeration type exists.
Sebastian Redl28507842009-02-26 14:39:58 +00001150 if (ArraySize && !ArraySize->isTypeDependent()) {
Eli Friedmanceccab92012-01-26 00:26:18 +00001151 ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(
Richard Smithebaf0e62011-10-18 20:49:44 +00001152 StartLoc, ArraySize,
David Blaikie4e4d0842012-03-11 07:00:24 +00001153 PDiag(diag::err_array_size_not_integral) << getLangOpts().CPlusPlus0x,
Richard Smithebaf0e62011-10-18 20:49:44 +00001154 PDiag(diag::err_array_size_incomplete_type)
1155 << ArraySize->getSourceRange(),
1156 PDiag(diag::err_array_size_explicit_conversion),
1157 PDiag(diag::note_array_size_conversion),
1158 PDiag(diag::err_array_size_ambiguous_conversion),
1159 PDiag(diag::note_array_size_conversion),
David Blaikie4e4d0842012-03-11 07:00:24 +00001160 PDiag(getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00001161 diag::warn_cxx98_compat_array_size_conversion :
Richard Smithf39aec12012-02-04 07:07:42 +00001162 diag::ext_array_size_conversion),
1163 /*AllowScopedEnumerations*/ false);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001164 if (ConvertedSize.isInvalid())
1165 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001166
John McCall9ae2f072010-08-23 23:25:46 +00001167 ArraySize = ConvertedSize.take();
John McCall806054d2012-01-11 00:14:46 +00001168 QualType SizeType = ArraySize->getType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001169 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001170 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001171
Richard Smith0b458fd2012-02-04 05:35:53 +00001172 // C++98 [expr.new]p7:
1173 // The expression in a direct-new-declarator shall have integral type
1174 // with a non-negative value.
1175 //
1176 // Let's see if this is a constant < 0. If so, we reject it out of
1177 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1178 // array type.
1179 //
1180 // Note: such a construct has well-defined semantics in C++11: it throws
1181 // std::bad_array_new_length.
Sebastian Redl28507842009-02-26 14:39:58 +00001182 if (!ArraySize->isValueDependent()) {
1183 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +00001184 // We've already performed any required implicit conversion to integer or
1185 // unscoped enumeration type.
Richard Smith0b458fd2012-02-04 05:35:53 +00001186 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Sebastian Redl28507842009-02-26 14:39:58 +00001187 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001188 llvm::APInt::getNullValue(Value.getBitWidth()),
Richard Smith0b458fd2012-02-04 05:35:53 +00001189 Value.isUnsigned())) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001190 if (getLangOpts().CPlusPlus0x)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001191 Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001192 diag::warn_typecheck_negative_array_new_size)
Douglas Gregor2767ce22010-08-18 00:39:00 +00001193 << ArraySize->getSourceRange();
Richard Smith0b458fd2012-02-04 05:35:53 +00001194 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00001195 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001196 diag::err_typecheck_negative_array_size)
1197 << ArraySize->getSourceRange());
1198 } else if (!AllocType->isDependentType()) {
1199 unsigned ActiveSizeBits =
1200 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1201 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001202 if (getLangOpts().CPlusPlus0x)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001203 Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001204 diag::warn_array_new_too_large)
1205 << Value.toString(10)
1206 << ArraySize->getSourceRange();
1207 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00001208 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001209 diag::err_array_too_large)
1210 << Value.toString(10)
1211 << ArraySize->getSourceRange());
Douglas Gregor2767ce22010-08-18 00:39:00 +00001212 }
1213 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001214 } else if (TypeIdParens.isValid()) {
1215 // Can't have dynamic array size when the type-id is in parentheses.
1216 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1217 << ArraySize->getSourceRange()
1218 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1219 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001220
Douglas Gregor4bd40312010-07-13 15:54:32 +00001221 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001222 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001223 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001224
John McCallf85e1932011-06-15 23:02:42 +00001225 // ARC: warn about ABI issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00001226 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001227 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1228 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1229 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1230 << 0 << BaseAllocType;
1231 }
1232
John McCall7d166272011-05-15 07:14:44 +00001233 // Note that we do *not* convert the argument in any way. It can
1234 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001235 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001236
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001237 FunctionDecl *OperatorNew = 0;
1238 FunctionDecl *OperatorDelete = 0;
Sebastian Redlf53597f2009-03-15 17:47:39 +00001239 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1240 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001241
Sebastian Redl28507842009-02-26 14:39:58 +00001242 if (!AllocType->isDependentType() &&
Ahmed Charles13a140c2012-02-25 11:00:22 +00001243 !Expr::hasAnyTypeDependentArguments(
1244 llvm::makeArrayRef(PlaceArgs, NumPlaceArgs)) &&
Sebastian Redl28507842009-02-26 14:39:58 +00001245 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001246 SourceRange(PlacementLParen, PlacementRParen),
1247 UseGlobal, AllocType, ArraySize, PlaceArgs,
1248 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001249 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001250
1251 // If this is an array allocation, compute whether the usual array
1252 // deallocation function for the type has a size_t parameter.
1253 bool UsualArrayDeleteWantsSize = false;
1254 if (ArraySize && !AllocType->isDependentType())
1255 UsualArrayDeleteWantsSize
1256 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1257
Chris Lattner5f9e2722011-07-23 10:55:15 +00001258 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001259 if (OperatorNew) {
1260 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001261 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001262 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001263 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001264 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001265
Anders Carlsson28e94832010-05-03 02:07:56 +00001266 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001267 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlsson28e94832010-05-03 02:07:56 +00001268 AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001269 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001270
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001271 NumPlaceArgs = AllPlaceArgs.size();
1272 if (NumPlaceArgs > 0)
1273 PlaceArgs = &AllPlaceArgs[0];
Eli Friedmane61eb042012-02-18 04:48:30 +00001274
1275 DiagnoseSentinelCalls(OperatorNew, PlacementLParen,
1276 PlaceArgs, NumPlaceArgs);
1277
1278 // FIXME: Missing call to CheckFunctionCall or equivalent
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001279 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001280
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001281 // Warn if the type is over-aligned and is being allocated by global operator
1282 // new.
Nick Lewycky507a8a32012-02-04 03:30:14 +00001283 if (NumPlaceArgs == 0 && OperatorNew &&
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001284 (OperatorNew->isImplicit() ||
1285 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1286 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1287 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1288 if (Align > SuitableAlign)
1289 Diag(StartLoc, diag::warn_overaligned_type)
1290 << AllocType
1291 << unsigned(Align / Context.getCharWidth())
1292 << unsigned(SuitableAlign / Context.getCharWidth());
1293 }
1294 }
1295
Sebastian Redlbd45d252012-02-16 12:59:47 +00001296 QualType InitType = AllocType;
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001297 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlbd45d252012-02-16 12:59:47 +00001298 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1299 // dialect distinction.
1300 if (ResultType->isArrayType() || ArraySize) {
1301 if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1302 SourceRange InitRange(Inits[0]->getLocStart(),
1303 Inits[NumInits - 1]->getLocEnd());
1304 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1305 return ExprError();
1306 }
1307 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1308 // We do the initialization typechecking against the array type
1309 // corresponding to the number of initializers + 1 (to also check
1310 // default-initialization).
1311 unsigned NumElements = ILE->getNumInits() + 1;
1312 InitType = Context.getConstantArrayType(AllocType,
1313 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1314 ArrayType::Normal, 0);
1315 }
Anders Carlsson48c95012010-05-03 15:45:23 +00001316 }
1317
Douglas Gregor99a2e602009-12-16 01:38:02 +00001318 if (!AllocType->isDependentType() &&
Ahmed Charles13a140c2012-02-25 11:00:22 +00001319 !Expr::hasAnyTypeDependentArguments(
1320 llvm::makeArrayRef(Inits, NumInits))) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001321 // C++11 [expr.new]p15:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001322 // A new-expression that creates an object of type T initializes that
1323 // object as follows:
1324 InitializationKind Kind
1325 // - If the new-initializer is omitted, the object is default-
1326 // initialized (8.5); if no initialization is performed,
1327 // the object has indeterminate value
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001328 = initStyle == CXXNewExpr::NoInit
1329 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001330 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001331 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001332 : initStyle == CXXNewExpr::ListInit
1333 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1334 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1335 DirectInitRange.getBegin(),
1336 DirectInitRange.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001337
Douglas Gregor99a2e602009-12-16 01:38:02 +00001338 InitializedEntity Entity
Sebastian Redlbd45d252012-02-16 12:59:47 +00001339 = InitializedEntity::InitializeNew(StartLoc, InitType);
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001340 InitializationSequence InitSeq(*this, Entity, Kind, Inits, NumInits);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001341 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001342 MultiExprArg(Inits, NumInits));
Douglas Gregor99a2e602009-12-16 01:38:02 +00001343 if (FullInit.isInvalid())
1344 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001345
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001346 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1347 // we don't want the initialized object to be destructed.
1348 if (CXXBindTemporaryExpr *Binder =
1349 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1350 FullInit = Owned(Binder->getSubExpr());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001351
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001352 Initializer = FullInit.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001353 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001354
Douglas Gregor6d908702010-02-26 05:06:18 +00001355 // Mark the new and delete operators as referenced.
1356 if (OperatorNew)
Eli Friedman5f2987c2012-02-02 03:46:19 +00001357 MarkFunctionReferenced(StartLoc, OperatorNew);
Douglas Gregor6d908702010-02-26 05:06:18 +00001358 if (OperatorDelete)
Eli Friedman5f2987c2012-02-02 03:46:19 +00001359 MarkFunctionReferenced(StartLoc, OperatorDelete);
Douglas Gregor6d908702010-02-26 05:06:18 +00001360
John McCall84ff0fc2011-07-13 20:12:57 +00001361 // C++0x [expr.new]p17:
1362 // If the new expression creates an array of objects of class type,
1363 // access and ambiguity control are done for the destructor.
David Blaikie426d6ca2012-03-10 23:40:02 +00001364 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1365 if (ArraySize && !BaseAllocType->isDependentType()) {
1366 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1367 if (CXXDestructorDecl *dtor = LookupDestructor(
1368 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1369 MarkFunctionReferenced(StartLoc, dtor);
1370 CheckDestructorAccess(StartLoc, dtor,
1371 PDiag(diag::err_access_dtor)
1372 << BaseAllocType);
1373 DiagnoseUseOfDecl(dtor, StartLoc);
1374 }
John McCall84ff0fc2011-07-13 20:12:57 +00001375 }
1376 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001377
Sebastian Redlf53597f2009-03-15 17:47:39 +00001378 PlacementArgs.release();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001379
Ted Kremenekad7fe862010-02-11 22:51:03 +00001380 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001381 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001382 UsualArrayDeleteWantsSize,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001383 PlaceArgs, NumPlaceArgs, TypeIdParens,
1384 ArraySize, initStyle, Initializer,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001385 ResultType, AllocTypeInfo,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001386 StartLoc, DirectInitRange));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001387}
1388
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001389/// \brief Checks that a type is suitable as the allocated type
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001390/// in a new-expression.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001391bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001392 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001393 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1394 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001395 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001396 return Diag(Loc, diag::err_bad_new_type)
1397 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001398 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001399 return Diag(Loc, diag::err_bad_new_type)
1400 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001401 else if (!AllocType->isDependentType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001402 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001403 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001404 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001405 diag::err_allocation_of_abstract_type))
1406 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001407 else if (AllocType->isVariablyModifiedType())
1408 return Diag(Loc, diag::err_variably_modified_new_type)
1409 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001410 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1411 return Diag(Loc, diag::err_address_space_qualified_new)
1412 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikie4e4d0842012-03-11 07:00:24 +00001413 else if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001414 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1415 QualType BaseAllocType = Context.getBaseElementType(AT);
1416 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1417 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001418 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001419 << BaseAllocType;
1420 }
1421 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001422
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001423 return false;
1424}
1425
Douglas Gregor6d908702010-02-26 05:06:18 +00001426/// \brief Determine whether the given function is a non-placement
1427/// deallocation function.
1428static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1429 if (FD->isInvalidDecl())
1430 return false;
1431
1432 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1433 return Method->isUsualDeallocationFunction();
1434
1435 return ((FD->getOverloadedOperator() == OO_Delete ||
1436 FD->getOverloadedOperator() == OO_Array_Delete) &&
1437 FD->getNumParams() == 1);
1438}
1439
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001440/// FindAllocationFunctions - Finds the overloads of operator new and delete
1441/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001442bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1443 bool UseGlobal, QualType AllocType,
1444 bool IsArray, Expr **PlaceArgs,
1445 unsigned NumPlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001446 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001447 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001448 // --- Choosing an allocation function ---
1449 // C++ 5.3.4p8 - 14 & 18
1450 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1451 // in the scope of the allocated class.
1452 // 2) If an array size is given, look for operator new[], else look for
1453 // operator new.
1454 // 3) The first argument is always size_t. Append the arguments from the
1455 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001456
Chris Lattner5f9e2722011-07-23 10:55:15 +00001457 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001458 // We don't care about the actual value of this argument.
1459 // FIXME: Should the Sema create the expression and embed it in the syntax
1460 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001461 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001462 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001463 Context.getSizeType(),
1464 SourceLocation());
1465 AllocArgs[0] = &Size;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001466 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1467
Douglas Gregor6d908702010-02-26 05:06:18 +00001468 // C++ [expr.new]p8:
1469 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001470 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001471 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001472 // type, the allocation function's name is operator new[] and the
1473 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001474 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1475 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001476 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1477 IsArray ? OO_Array_Delete : OO_Delete);
1478
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001479 QualType AllocElemType = Context.getBaseElementType(AllocType);
1480
1481 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001482 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001483 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl00e68e22009-02-09 18:24:27 +00001484 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001485 AllocArgs.size(), Record, /*AllowMissing=*/true,
1486 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001487 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001488 }
1489 if (!OperatorNew) {
1490 // Didn't find a member overload. Look for a global one.
1491 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001492 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl00e68e22009-02-09 18:24:27 +00001493 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl7f662392008-12-04 22:20:51 +00001494 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1495 OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001496 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001497 }
1498
John McCall9c82afc2010-04-20 02:18:25 +00001499 // We don't need an operator delete if we're running under
1500 // -fno-exceptions.
David Blaikie4e4d0842012-03-11 07:00:24 +00001501 if (!getLangOpts().Exceptions) {
John McCall9c82afc2010-04-20 02:18:25 +00001502 OperatorDelete = 0;
1503 return false;
1504 }
1505
Anders Carlssond9583892009-05-31 20:26:12 +00001506 // FindAllocationOverload can change the passed in arguments, so we need to
1507 // copy them back.
1508 if (NumPlaceArgs > 0)
1509 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Douglas Gregor6d908702010-02-26 05:06:18 +00001511 // C++ [expr.new]p19:
1512 //
1513 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001514 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001515 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001516 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001517 // the scope of T. If this lookup fails to find the name, or if
1518 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001519 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001520 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001521 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001522 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001523 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001524 LookupQualifiedName(FoundDelete, RD);
1525 }
John McCall90c8c572010-03-18 08:19:33 +00001526 if (FoundDelete.isAmbiguous())
1527 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001528
1529 if (FoundDelete.empty()) {
1530 DeclareGlobalNewDelete();
1531 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1532 }
1533
1534 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001535
Chris Lattner5f9e2722011-07-23 10:55:15 +00001536 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001537
John McCalledeb6c92010-09-14 21:34:24 +00001538 // Whether we're looking for a placement operator delete is dictated
1539 // by whether we selected a placement operator new, not by whether
1540 // we had explicit placement arguments. This matters for things like
1541 // struct A { void *operator new(size_t, int = 0); ... };
1542 // A *a = new A()
1543 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1544
1545 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001546 // C++ [expr.new]p20:
1547 // A declaration of a placement deallocation function matches the
1548 // declaration of a placement allocation function if it has the
1549 // same number of parameters and, after parameter transformations
1550 // (8.3.5), all parameter types except the first are
1551 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001552 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001553 // To perform this comparison, we compute the function type that
1554 // the deallocation function should have, and use that type both
1555 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001556 //
1557 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001558 QualType ExpectedFunctionType;
1559 {
1560 const FunctionProtoType *Proto
1561 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001562
Chris Lattner5f9e2722011-07-23 10:55:15 +00001563 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001564 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001565 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1566 ArgTypes.push_back(Proto->getArgType(I));
1567
John McCalle23cf432010-12-14 08:05:40 +00001568 FunctionProtoType::ExtProtoInfo EPI;
1569 EPI.Variadic = Proto->isVariadic();
1570
Douglas Gregor6d908702010-02-26 05:06:18 +00001571 ExpectedFunctionType
1572 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalle23cf432010-12-14 08:05:40 +00001573 ArgTypes.size(), EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001574 }
1575
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001576 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001577 DEnd = FoundDelete.end();
1578 D != DEnd; ++D) {
1579 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001580 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001581 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1582 // Perform template argument deduction to try to match the
1583 // expected function type.
1584 TemplateDeductionInfo Info(Context, StartLoc);
1585 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1586 continue;
1587 } else
1588 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1589
1590 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001591 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001592 }
1593 } else {
1594 // C++ [expr.new]p20:
1595 // [...] Any non-placement deallocation function matches a
1596 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001597 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001598 DEnd = FoundDelete.end();
1599 D != DEnd; ++D) {
1600 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1601 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001602 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001603 }
1604 }
1605
1606 // C++ [expr.new]p20:
1607 // [...] If the lookup finds a single matching deallocation
1608 // function, that function will be called; otherwise, no
1609 // deallocation function will be called.
1610 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001611 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001612
1613 // C++0x [expr.new]p20:
1614 // If the lookup finds the two-parameter form of a usual
1615 // deallocation function (3.7.4.2) and that function, considered
1616 // as a placement deallocation function, would have been
1617 // selected as a match for the allocation function, the program
1618 // is ill-formed.
David Blaikie4e4d0842012-03-11 07:00:24 +00001619 if (NumPlaceArgs && getLangOpts().CPlusPlus0x &&
Douglas Gregor6d908702010-02-26 05:06:18 +00001620 isNonPlacementDeallocationFunction(OperatorDelete)) {
1621 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001622 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001623 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1624 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1625 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001626 } else {
1627 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001628 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001629 }
1630 }
1631
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001632 return false;
1633}
1634
Sebastian Redl7f662392008-12-04 22:20:51 +00001635/// FindAllocationOverload - Find an fitting overload for the allocation
1636/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001637bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1638 DeclarationName Name, Expr** Args,
1639 unsigned NumArgs, DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001640 bool AllowMissing, FunctionDecl *&Operator,
1641 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001642 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1643 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001644 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001645 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001646 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001647 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001648 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001649 }
1650
John McCall90c8c572010-03-18 08:19:33 +00001651 if (R.isAmbiguous())
1652 return true;
1653
1654 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001655
John McCall5769d612010-02-08 23:07:23 +00001656 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001657 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001658 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001659 // Even member operator new/delete are implicitly treated as
1660 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001661 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001662
John McCall9aa472c2010-03-19 07:35:19 +00001663 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1664 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001665 /*ExplicitTemplateArgs=*/0,
1666 llvm::makeArrayRef(Args, NumArgs),
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001667 Candidates,
1668 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001669 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001670 }
1671
John McCall9aa472c2010-03-19 07:35:19 +00001672 FunctionDecl *Fn = cast<FunctionDecl>(D);
Ahmed Charles13a140c2012-02-25 11:00:22 +00001673 AddOverloadCandidate(Fn, Alloc.getPair(),
1674 llvm::makeArrayRef(Args, NumArgs), Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001675 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001676 }
1677
1678 // Do the resolution.
1679 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001680 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001681 case OR_Success: {
1682 // Got one!
1683 FunctionDecl *FnDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00001684 MarkFunctionReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001685 // The first argument is size_t, and the first parameter must be size_t,
1686 // too. This is checked on declaration and can be assumed. (It can't be
1687 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001688 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001689 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1690 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001691 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1692 FnDecl->getParamDecl(i));
1693
1694 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1695 return true;
1696
John McCall60d7b3a2010-08-24 06:29:42 +00001697 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001698 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001699 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001700 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001701
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001702 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001703 }
Richard Smith9a561d52012-02-26 09:11:52 +00001704
Sebastian Redl7f662392008-12-04 22:20:51 +00001705 Operator = FnDecl;
Richard Smith9a561d52012-02-26 09:11:52 +00001706
1707 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1708 Best->FoundDecl, Diagnose) == AR_inaccessible)
1709 return true;
1710
Sebastian Redl7f662392008-12-04 22:20:51 +00001711 return false;
1712 }
1713
1714 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001715 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001716 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1717 << Name << Range;
Ahmed Charles13a140c2012-02-25 11:00:22 +00001718 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1719 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruth361d3802011-06-08 10:26:03 +00001720 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001721 return true;
1722
1723 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001724 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001725 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1726 << Name << Range;
Ahmed Charles13a140c2012-02-25 11:00:22 +00001727 Candidates.NoteCandidates(*this, OCD_ViableCandidates,
1728 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruth361d3802011-06-08 10:26:03 +00001729 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001730 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001731
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001732 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001733 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001734 Diag(StartLoc, diag::err_ovl_deleted_call)
1735 << Best->Function->isDeleted()
1736 << Name
1737 << getDeletedOrUnavailableSuffix(Best->Function)
1738 << Range;
Ahmed Charles13a140c2012-02-25 11:00:22 +00001739 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1740 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruth361d3802011-06-08 10:26:03 +00001741 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001742 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001743 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001744 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001745 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001746}
1747
1748
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001749/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1750/// delete. These are:
1751/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001752/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001753/// void* operator new(std::size_t) throw(std::bad_alloc);
1754/// void* operator new[](std::size_t) throw(std::bad_alloc);
1755/// void operator delete(void *) throw();
1756/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001757/// // C++0x:
1758/// void* operator new(std::size_t);
1759/// void* operator new[](std::size_t);
1760/// void operator delete(void *);
1761/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001762/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001763/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001764/// Note that the placement and nothrow forms of new are *not* implicitly
1765/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001766void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001767 if (GlobalNewDeleteDeclared)
1768 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001769
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001770 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001771 // [...] The following allocation and deallocation functions (18.4) are
1772 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001773 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001774 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001775 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001776 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001777 // void* operator new[](std::size_t) throw(std::bad_alloc);
1778 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001779 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001780 // C++0x:
1781 // void* operator new(std::size_t);
1782 // void* operator new[](std::size_t);
1783 // void operator delete(void*);
1784 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001785 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001786 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001787 // new, operator new[], operator delete, operator delete[].
1788 //
1789 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1790 // "std" or "bad_alloc" as necessary to form the exception specification.
1791 // However, we do not make these implicit declarations visible to name
1792 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001793 // Note that the C++0x versions of operator delete are deallocation functions,
1794 // and thus are implicitly noexcept.
David Blaikie4e4d0842012-03-11 07:00:24 +00001795 if (!StdBadAlloc && !getLangOpts().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001796 // The "std::bad_alloc" class has not yet been declared, so build it
1797 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001798 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1799 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001800 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001801 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001802 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001803 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001804 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001805
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001806 GlobalNewDeleteDeclared = true;
1807
1808 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1809 QualType SizeT = Context.getSizeType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001810 bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001811
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001812 DeclareGlobalAllocationFunction(
1813 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001814 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001815 DeclareGlobalAllocationFunction(
1816 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001817 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001818 DeclareGlobalAllocationFunction(
1819 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1820 Context.VoidTy, VoidPtr);
1821 DeclareGlobalAllocationFunction(
1822 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1823 Context.VoidTy, VoidPtr);
1824}
1825
1826/// DeclareGlobalAllocationFunction - Declares a single implicit global
1827/// allocation function if it doesn't already exist.
1828void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001829 QualType Return, QualType Argument,
1830 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001831 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1832
1833 // Check if this function is already declared.
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001834 {
Douglas Gregor5cc37092008-12-23 22:05:29 +00001835 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001836 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001837 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001838 // Only look at non-template functions, as it is the predefined,
1839 // non-templated allocation function we are trying to declare here.
1840 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1841 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001842 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001843 Func->getParamDecl(0)->getType().getUnqualifiedType());
1844 // FIXME: Do we need to check for default arguments here?
Douglas Gregor7b868622010-08-18 15:06:25 +00001845 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1846 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Sean Huntcf807c42010-08-18 23:23:40 +00001847 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001848 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001849 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001850 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001851 }
1852 }
1853
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001854 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001855 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001856 = (Name.getCXXOverloadedOperator() == OO_New ||
1857 Name.getCXXOverloadedOperator() == OO_Array_New);
David Blaikie4e4d0842012-03-11 07:00:24 +00001858 if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus0x) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001859 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001860 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001861 }
John McCalle23cf432010-12-14 08:05:40 +00001862
1863 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001864 if (HasBadAllocExceptionSpec) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001865 if (!getLangOpts().CPlusPlus0x) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001866 EPI.ExceptionSpecType = EST_Dynamic;
1867 EPI.NumExceptions = 1;
1868 EPI.Exceptions = &BadAllocType;
1869 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001870 } else {
David Blaikie4e4d0842012-03-11 07:00:24 +00001871 EPI.ExceptionSpecType = getLangOpts().CPlusPlus0x ?
Sebastian Redl8999fe12011-03-14 18:08:30 +00001872 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001873 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001874
John McCalle23cf432010-12-14 08:05:40 +00001875 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001876 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001877 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1878 SourceLocation(), Name,
John McCalld931b082010-08-26 03:08:43 +00001879 FnType, /*TInfo=*/0, SC_None,
1880 SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001881 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001882
Nuno Lopesfc284482009-12-16 16:59:22 +00001883 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00001884 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001885
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001886 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001887 SourceLocation(), 0,
1888 Argument, /*TInfo=*/0,
1889 SC_None, SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00001890 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001891
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001892 // FIXME: Also add this declaration to the IdentifierResolver, but
1893 // make sure it is at the end of the chain to coincide with the
1894 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00001895 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001896}
1897
Anders Carlsson78f74552009-11-15 18:45:20 +00001898bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1899 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001900 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001901 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00001902 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00001903 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001904
John McCalla24dc2e2009-11-17 02:14:36 +00001905 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00001906 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001907
Chandler Carruth23893242010-06-28 00:30:51 +00001908 Found.suppressDiagnostics();
1909
Chris Lattner5f9e2722011-07-23 10:55:15 +00001910 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00001911 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1912 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00001913 NamedDecl *ND = (*F)->getUnderlyingDecl();
1914
1915 // Ignore template operator delete members from the check for a usual
1916 // deallocation function.
1917 if (isa<FunctionTemplateDecl>(ND))
1918 continue;
1919
1920 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00001921 Matches.push_back(F.getPair());
1922 }
1923
1924 // There's exactly one suitable operator; pick it.
1925 if (Matches.size() == 1) {
1926 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00001927
1928 if (Operator->isDeleted()) {
1929 if (Diagnose) {
1930 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +00001931 NoteDeletedFunction(Operator);
Sean Hunt2be7e902011-05-12 22:46:29 +00001932 }
1933 return true;
1934 }
1935
Richard Smith9a561d52012-02-26 09:11:52 +00001936 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1937 Matches[0], Diagnose) == AR_inaccessible)
1938 return true;
1939
John McCall046a7462010-08-04 00:31:26 +00001940 return false;
1941
1942 // We found multiple suitable operators; complain about the ambiguity.
1943 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001944 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001945 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1946 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00001947
Chris Lattner5f9e2722011-07-23 10:55:15 +00001948 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00001949 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1950 Diag((*F)->getUnderlyingDecl()->getLocation(),
1951 diag::note_member_declared_here) << Name;
1952 }
John McCall046a7462010-08-04 00:31:26 +00001953 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00001954 }
1955
1956 // We did find operator delete/operator delete[] declarations, but
1957 // none of them were suitable.
1958 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001959 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00001960 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1961 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001962
Sean Huntcb45a0f2011-05-12 22:46:25 +00001963 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1964 F != FEnd; ++F)
1965 Diag((*F)->getUnderlyingDecl()->getLocation(),
1966 diag::note_member_declared_here) << Name;
1967 }
Anders Carlsson78f74552009-11-15 18:45:20 +00001968 return true;
1969 }
1970
1971 // Look for a global declaration.
1972 DeclareGlobalNewDelete();
1973 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001974
Anders Carlsson78f74552009-11-15 18:45:20 +00001975 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1976 Expr* DeallocArgs[1];
1977 DeallocArgs[0] = &Null;
1978 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00001979 DeallocArgs, 1, TUDecl, !Diagnose,
1980 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00001981 return true;
1982
1983 assert(Operator && "Did not find a deallocation function!");
1984 return false;
1985}
1986
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001987/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1988/// @code ::delete ptr; @endcode
1989/// or
1990/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00001991ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001992Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00001993 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00001994 // C++ [expr.delete]p1:
1995 // The operand shall have a pointer type, or a class type having a single
1996 // conversion function to a pointer type. The result has type void.
1997 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001998 // DR599 amends "pointer type" to "pointer to object type" in both cases.
1999
John Wiegley429bb272011-04-08 18:41:53 +00002000 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00002001 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002002 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00002003 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002004
John Wiegley429bb272011-04-08 18:41:53 +00002005 if (!Ex.get()->isTypeDependent()) {
John McCall5aba3eb2012-03-09 04:08:29 +00002006 // Perform lvalue-to-rvalue cast, if needed.
2007 Ex = DefaultLvalueConversion(Ex.take());
2008
John Wiegley429bb272011-04-08 18:41:53 +00002009 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002010
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002011 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002012 if (RequireCompleteType(StartLoc, Type,
Douglas Gregord10099e2012-05-04 16:32:21 +00002013 diag::err_delete_incomplete_class_type))
Douglas Gregor254a9422010-07-29 14:44:35 +00002014 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002015
Chris Lattner5f9e2722011-07-23 10:55:15 +00002016 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCall32daa422010-03-31 01:36:47 +00002017
Fariborz Jahanian53462782009-09-11 21:44:33 +00002018 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002019 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002020 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002021 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00002022 NamedDecl *D = I.getDecl();
2023 if (isa<UsingShadowDecl>(D))
2024 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2025
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002026 // Skip over templated conversion functions; they aren't considered.
John McCall32daa422010-03-31 01:36:47 +00002027 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002028 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002029
John McCall32daa422010-03-31 01:36:47 +00002030 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002031
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002032 QualType ConvType = Conv->getConversionType().getNonReferenceType();
2033 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00002034 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002035 ObjectPtrConversions.push_back(Conv);
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002036 }
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002037 if (ObjectPtrConversions.size() == 1) {
2038 // We have a single conversion to a pointer-to-object type. Perform
2039 // that conversion.
John McCall32daa422010-03-31 01:36:47 +00002040 // TODO: don't redo the conversion calculation.
John Wiegley429bb272011-04-08 18:41:53 +00002041 ExprResult Res =
2042 PerformImplicitConversion(Ex.get(),
John McCall32daa422010-03-31 01:36:47 +00002043 ObjectPtrConversions.front()->getConversionType(),
John Wiegley429bb272011-04-08 18:41:53 +00002044 AA_Converting);
2045 if (Res.isUsable()) {
2046 Ex = move(Res);
2047 Type = Ex.get()->getType();
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002048 }
2049 }
2050 else if (ObjectPtrConversions.size() > 1) {
2051 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002052 << Type << Ex.get()->getSourceRange();
John McCall32daa422010-03-31 01:36:47 +00002053 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
2054 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanian8b915e72009-09-15 22:15:23 +00002055 return ExprError();
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002056 }
Sebastian Redl28507842009-02-26 14:39:58 +00002057 }
2058
Sebastian Redlf53597f2009-03-15 17:47:39 +00002059 if (!Type->isPointerType())
2060 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002061 << Type << Ex.get()->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00002062
Ted Kremenek6217b802009-07-29 21:53:49 +00002063 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00002064 QualType PointeeElem = Context.getBaseElementType(Pointee);
2065
2066 if (unsigned AddressSpace = Pointee.getAddressSpace())
2067 return Diag(Ex.get()->getLocStart(),
2068 diag::err_address_space_qualified_delete)
2069 << Pointee.getUnqualifiedType() << AddressSpace;
2070
2071 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00002072 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002073 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00002074 // effectively bans deletion of "void*". However, most compilers support
2075 // this, so we treat it as a warning unless we're in a SFINAE context.
2076 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002077 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00002078 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00002079 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002080 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00002081 } else if (!Pointee->isDependentType()) {
2082 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregord10099e2012-05-04 16:32:21 +00002083 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmane52c9142011-07-26 22:25:31 +00002084 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2085 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2086 }
2087 }
2088
Douglas Gregor1070c9f2009-09-29 21:38:53 +00002089 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002090 // [Note: a pointer to a const type can be the operand of a
2091 // delete-expression; it is not necessary to cast away the constness
2092 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00002093 // of the delete-expression. ]
John McCallf85e1932011-06-15 23:02:42 +00002094 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnara30bb4202011-11-16 15:42:13 +00002095 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
2096 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002097
2098 if (Pointee->isArrayType() && !ArrayForm) {
2099 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00002100 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002101 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2102 ArrayForm = true;
2103 }
2104
Anders Carlssond67c4c32009-08-16 20:29:29 +00002105 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2106 ArrayForm ? OO_Array_Delete : OO_Delete);
2107
Eli Friedmane52c9142011-07-26 22:25:31 +00002108 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002109 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00002110 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2111 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00002112 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002113
John McCall6ec278d2011-01-27 09:37:56 +00002114 // If we're allocating an array of records, check whether the
2115 // usual operator delete[] has a size_t parameter.
2116 if (ArrayForm) {
2117 // If the user specifically asked to use the global allocator,
2118 // we'll need to do the lookup into the class.
2119 if (UseGlobal)
2120 UsualArrayDeleteWantsSize =
2121 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2122
2123 // Otherwise, the usual operator delete[] should be the
2124 // function we just found.
2125 else if (isa<CXXMethodDecl>(OperatorDelete))
2126 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2127 }
2128
Richard Smith213d70b2012-02-18 04:13:32 +00002129 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmane52c9142011-07-26 22:25:31 +00002130 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002131 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002132 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor9b623632010-10-12 23:32:35 +00002133 DiagnoseUseOfDecl(Dtor, StartLoc);
2134 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00002135
2136 // C++ [expr.delete]p3:
2137 // In the first alternative (delete object), if the static type of the
2138 // object to be deleted is different from its dynamic type, the static
2139 // type shall be a base class of the dynamic type of the object to be
2140 // deleted and the static type shall have a virtual destructor or the
2141 // behavior is undefined.
2142 //
2143 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00002144 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00002145 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00002146 if (dtor && !dtor->isVirtual()) {
2147 if (PointeeRD->isAbstract()) {
2148 // If the class is abstract, we warn by default, because we're
2149 // sure the code has undefined behavior.
2150 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2151 << PointeeElem;
2152 } else if (!ArrayForm) {
2153 // Otherwise, if this is not an array delete, it's a bit suspect,
2154 // but not necessarily wrong.
2155 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2156 }
2157 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00002158 }
John McCallf85e1932011-06-15 23:02:42 +00002159
David Blaikie4e4d0842012-03-11 07:00:24 +00002160 } else if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002161 PointeeElem->isObjCLifetimeType() &&
2162 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
2163 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
2164 ArrayForm) {
2165 Diag(StartLoc, diag::warn_err_new_delete_object_array)
2166 << 1 << PointeeElem;
Anders Carlssond67c4c32009-08-16 20:29:29 +00002167 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002168
Anders Carlssond67c4c32009-08-16 20:29:29 +00002169 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00002170 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00002171 DeclareGlobalNewDelete();
2172 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00002173 Expr *Arg = Ex.get();
Mike Stump1eb44332009-09-09 15:08:12 +00002174 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley429bb272011-04-08 18:41:53 +00002175 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00002176 OperatorDelete))
2177 return ExprError();
2178 }
Mike Stump1eb44332009-09-09 15:08:12 +00002179
Eli Friedman5f2987c2012-02-02 03:46:19 +00002180 MarkFunctionReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00002181
Douglas Gregord880f522011-02-01 15:50:11 +00002182 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00002183 if (PointeeRD) {
2184 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00002185 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00002186 PDiag(diag::err_access_dtor) << PointeeElem);
2187 }
2188 }
2189
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002190 }
2191
Sebastian Redlf53597f2009-03-15 17:47:39 +00002192 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00002193 ArrayFormAsWritten,
2194 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00002195 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002196}
2197
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002198/// \brief Check the use of the given variable as a C++ condition in an if,
2199/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00002200ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00002201 SourceLocation StmtLoc,
2202 bool ConvertToBoolean) {
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002203 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002204
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002205 // C++ [stmt.select]p2:
2206 // The declarator shall not specify a function or an array.
2207 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002208 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002209 diag::err_invalid_use_of_function_type)
2210 << ConditionVar->getSourceRange());
2211 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002212 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002213 diag::err_invalid_use_of_array_type)
2214 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00002215
John Wiegley429bb272011-04-08 18:41:53 +00002216 ExprResult Condition =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002217 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2218 SourceLocation(),
2219 ConditionVar,
John McCallf4b88a42012-03-10 09:33:50 +00002220 /*enclosing*/ false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002221 ConditionVar->getLocation(),
2222 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00002223 VK_LValue));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002224
Eli Friedman5f2987c2012-02-02 03:46:19 +00002225 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002226
John Wiegley429bb272011-04-08 18:41:53 +00002227 if (ConvertToBoolean) {
2228 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2229 if (Condition.isInvalid())
2230 return ExprError();
2231 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002232
John Wiegley429bb272011-04-08 18:41:53 +00002233 return move(Condition);
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002234}
2235
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002236/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002237ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002238 // C++ 6.4p4:
2239 // The value of a condition that is an initialized declaration in a statement
2240 // other than a switch statement is the value of the declared variable
2241 // implicitly converted to type bool. If that conversion is ill-formed, the
2242 // program is ill-formed.
2243 // The value of a condition that is an expression is the value of the
2244 // expression, implicitly converted to bool.
2245 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002246 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002247}
Douglas Gregor77a52232008-09-12 00:47:35 +00002248
2249/// Helper function to determine whether this is the (deprecated) C++
2250/// conversion from a string literal to a pointer to non-const char or
2251/// non-const wchar_t (for narrow and wide string literals,
2252/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002253bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002254Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2255 // Look inside the implicit cast, if it exists.
2256 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2257 From = Cast->getSubExpr();
2258
2259 // A string literal (2.13.4) that is not a wide string literal can
2260 // be converted to an rvalue of type "pointer to char"; a wide
2261 // string literal can be converted to an rvalue of type "pointer
2262 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002263 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002264 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002265 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002266 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002267 // This conversion is considered only when there is an
2268 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002269 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2270 switch (StrLit->getKind()) {
2271 case StringLiteral::UTF8:
2272 case StringLiteral::UTF16:
2273 case StringLiteral::UTF32:
2274 // We don't allow UTF literals to be implicitly converted
2275 break;
2276 case StringLiteral::Ascii:
2277 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2278 ToPointeeType->getKind() == BuiltinType::Char_S);
2279 case StringLiteral::Wide:
2280 return ToPointeeType->isWideCharType();
2281 }
2282 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002283 }
2284
2285 return false;
2286}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002287
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002288static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002289 SourceLocation CastLoc,
2290 QualType Ty,
2291 CastKind Kind,
2292 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002293 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002294 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002295 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002296 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002297 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002298 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002299 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCallca0408f2010-08-23 06:44:23 +00002300 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002301
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002302 if (S.CompleteConstructorCall(Constructor,
John McCallf312b1e2010-08-26 23:41:50 +00002303 MultiExprArg(&From, 1),
Douglas Gregorba70ab62010-04-16 22:17:36 +00002304 CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002305 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002306
John McCallb9abd8722012-04-07 03:04:20 +00002307 S.CheckConstructorAccess(CastLoc, Constructor,
2308 InitializedEntity::InitializeTemporary(Ty),
2309 Constructor->getAccess());
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002310
2311 ExprResult Result
2312 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2313 move_arg(ConstructorArgs),
2314 HadMultipleCandidates, /*ZeroInit*/ false,
2315 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002316 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002317 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002318
Douglas Gregorba70ab62010-04-16 22:17:36 +00002319 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2320 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002321
John McCall2de56d12010-08-25 11:45:40 +00002322 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002323 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002324
Douglas Gregorba70ab62010-04-16 22:17:36 +00002325 // Create an implicit call expr that calls it.
Eli Friedman3f01c8a2012-03-01 01:30:04 +00002326 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2327 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002328 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002329 if (Result.isInvalid())
2330 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00002331 // Record usage of conversion in an implicit cast.
2332 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2333 Result.get()->getType(),
2334 CK_UserDefinedConversion,
2335 Result.get(), 0,
2336 Result.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002337
John McCallca82a822011-09-21 08:36:56 +00002338 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2339
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002340 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002341 }
2342 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002343}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002344
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002345/// PerformImplicitConversion - Perform an implicit conversion of the
2346/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002347/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002348/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002349/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002350ExprResult
2351Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002352 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002353 AssignmentAction Action,
2354 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002355 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002356 case ImplicitConversionSequence::StandardConversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002357 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2358 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002359 if (Res.isInvalid())
2360 return ExprError();
2361 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002362 break;
John Wiegley429bb272011-04-08 18:41:53 +00002363 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002364
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002365 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002366
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002367 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002368 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002369 QualType BeforeToType;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002370 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002371 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002372 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002373
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002374 // If the user-defined conversion is specified by a conversion function,
2375 // the initial standard conversion sequence converts the source type to
2376 // the implicit object parameter of the conversion function.
2377 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002378 } else {
2379 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002380 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002381 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002382 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002383 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002384 // initial standard conversion sequence converts the source type to the
2385 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002386 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2387 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002388 }
Douglas Gregora3998bd2010-12-02 21:47:04 +00002389 // Watch out for elipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002390 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002391 ExprResult Res =
Richard Smithc8d7f582011-11-29 22:48:16 +00002392 PerformImplicitConversion(From, BeforeToType,
2393 ICS.UserDefined.Before, AA_Converting,
2394 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002395 if (Res.isInvalid())
2396 return ExprError();
2397 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002398 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002399
2400 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002401 = BuildCXXCastArgument(*this,
2402 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002403 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002404 CastKind, cast<CXXMethodDecl>(FD),
2405 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002406 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002407 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002408
2409 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002410 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002411
John Wiegley429bb272011-04-08 18:41:53 +00002412 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002413
Richard Smithc8d7f582011-11-29 22:48:16 +00002414 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2415 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002416 }
John McCall1d318332010-01-12 00:44:57 +00002417
2418 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002419 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002420 PDiag(diag::err_typecheck_ambiguous_condition)
2421 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002422 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002423
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002424 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002425 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002426
2427 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002428 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002429 }
2430
2431 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002432 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002433}
2434
Richard Smithc8d7f582011-11-29 22:48:16 +00002435/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002436/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002437/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002438/// expression. Flavor is the context in which we're performing this
2439/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002440ExprResult
Richard Smithc8d7f582011-11-29 22:48:16 +00002441Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002442 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002443 AssignmentAction Action,
2444 CheckedConversionKind CCK) {
2445 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2446
Mike Stump390b4cc2009-05-16 07:39:55 +00002447 // Overall FIXME: we are recomputing too many types here and doing far too
2448 // much extra work. What this means is that we need to keep track of more
2449 // information that is computed when we try the implicit conversion initially,
2450 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002451 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002452
Douglas Gregor225c41e2008-11-03 19:09:14 +00002453 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002454 // FIXME: When can ToType be a reference type?
2455 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002456 if (SCS.Second == ICK_Derived_To_Base) {
John McCallca0408f2010-08-23 06:44:23 +00002457 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002458 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCallca0408f2010-08-23 06:44:23 +00002459 MultiExprArg(*this, &From, 1),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002460 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002461 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002462 return ExprError();
2463 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2464 ToType, SCS.CopyConstructor,
2465 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002466 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002467 /*ZeroInit*/ false,
2468 CXXConstructExpr::CK_Complete,
2469 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002470 }
John Wiegley429bb272011-04-08 18:41:53 +00002471 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2472 ToType, SCS.CopyConstructor,
2473 MultiExprArg(*this, &From, 1),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002474 /*HadMultipleCandidates*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002475 /*ZeroInit*/ false,
2476 CXXConstructExpr::CK_Complete,
2477 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002478 }
2479
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002480 // Resolve overloaded function references.
2481 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2482 DeclAccessPair Found;
2483 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2484 true, Found);
2485 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002486 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002487
Daniel Dunbar96a00142012-03-09 18:35:03 +00002488 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley429bb272011-04-08 18:41:53 +00002489 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002490
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002491 From = FixOverloadedFunctionReference(From, Found, Fn);
2492 FromType = From->getType();
2493 }
2494
Richard Smithc8d7f582011-11-29 22:48:16 +00002495 // Perform the first implicit conversion.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002496 switch (SCS.First) {
2497 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002498 // Nothing to do.
2499 break;
2500
Eli Friedmand814eaf2012-01-24 22:51:26 +00002501 case ICK_Lvalue_To_Rvalue: {
John McCall3c3b7f92011-10-25 17:37:35 +00002502 assert(From->getObjectKind() != OK_ObjCProperty);
John McCallf6a16482010-12-04 03:47:34 +00002503 FromType = FromType.getUnqualifiedType();
Eli Friedmand814eaf2012-01-24 22:51:26 +00002504 ExprResult FromRes = DefaultLvalueConversion(From);
2505 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2506 From = FromRes.take();
John McCallf6a16482010-12-04 03:47:34 +00002507 break;
Eli Friedmand814eaf2012-01-24 22:51:26 +00002508 }
John McCallf6a16482010-12-04 03:47:34 +00002509
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002510 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002511 FromType = Context.getArrayDecayedType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002512 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2513 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002514 break;
2515
2516 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002517 FromType = Context.getPointerType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002518 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2519 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002520 break;
2521
2522 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002523 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002524 }
2525
Richard Smithc8d7f582011-11-29 22:48:16 +00002526 // Perform the second implicit conversion
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002527 switch (SCS.Second) {
2528 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002529 // If both sides are functions (or pointers/references to them), there could
2530 // be incompatible exception declarations.
2531 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002532 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002533 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002534 break;
2535
Douglas Gregor43c79c22009-12-09 00:47:37 +00002536 case ICK_NoReturn_Adjustment:
2537 // If both sides are functions (or pointers/references to them), there could
2538 // be incompatible exception declarations.
2539 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002540 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002541
Richard Smithc8d7f582011-11-29 22:48:16 +00002542 From = ImpCastExprToType(From, ToType, CK_NoOp,
2543 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002544 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002545
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002546 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002547 case ICK_Integral_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002548 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2549 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002550 break;
2551
2552 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002553 case ICK_Floating_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002554 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2555 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002556 break;
2557
2558 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002559 case ICK_Complex_Conversion: {
2560 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2561 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2562 CastKind CK;
2563 if (FromEl->isRealFloatingType()) {
2564 if (ToEl->isRealFloatingType())
2565 CK = CK_FloatingComplexCast;
2566 else
2567 CK = CK_FloatingComplexToIntegralComplex;
2568 } else if (ToEl->isRealFloatingType()) {
2569 CK = CK_IntegralComplexToFloatingComplex;
2570 } else {
2571 CK = CK_IntegralComplexCast;
2572 }
Richard Smithc8d7f582011-11-29 22:48:16 +00002573 From = ImpCastExprToType(From, ToType, CK,
2574 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002575 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002576 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002577
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002578 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002579 if (ToType->isRealFloatingType())
Richard Smithc8d7f582011-11-29 22:48:16 +00002580 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2581 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002582 else
Richard Smithc8d7f582011-11-29 22:48:16 +00002583 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2584 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002585 break;
2586
Douglas Gregorf9201e02009-02-11 23:02:49 +00002587 case ICK_Compatible_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002588 From = ImpCastExprToType(From, ToType, CK_NoOp,
2589 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002590 break;
2591
John McCallf85e1932011-06-15 23:02:42 +00002592 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002593 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002594 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002595 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002596 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002597 Diag(From->getLocStart(),
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002598 diag::ext_typecheck_convert_incompatible_pointer)
2599 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002600 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002601 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00002602 Diag(From->getLocStart(),
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002603 diag::ext_typecheck_convert_incompatible_pointer)
2604 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002605 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002606
Douglas Gregor926df6c2011-06-11 01:09:30 +00002607 if (From->getType()->isObjCObjectPointerType() &&
2608 ToType->isObjCObjectPointerType())
2609 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002610 }
David Blaikie4e4d0842012-03-11 07:00:24 +00002611 else if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002612 !CheckObjCARCUnavailableWeakConversion(ToType,
2613 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002614 if (Action == AA_Initializing)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002615 Diag(From->getLocStart(),
John McCall7f3a6d32011-09-09 06:12:06 +00002616 diag::err_arc_weak_unavailable_assign);
2617 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00002618 Diag(From->getLocStart(),
John McCall7f3a6d32011-09-09 06:12:06 +00002619 diag::err_arc_convesion_of_weak_unavailable)
2620 << (Action == AA_Casting) << From->getType() << ToType
2621 << From->getSourceRange();
2622 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002623
John McCalldaa8e4e2010-11-15 09:13:47 +00002624 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002625 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002626 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002627 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002628
2629 // Make sure we extend blocks if necessary.
2630 // FIXME: doing this here is really ugly.
2631 if (Kind == CK_BlockPointerToObjCPointerCast) {
2632 ExprResult E = From;
2633 (void) PrepareCastToObjCObjectPointer(E);
2634 From = E.take();
2635 }
2636
Richard Smithc8d7f582011-11-29 22:48:16 +00002637 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2638 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002639 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002640 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002641
Anders Carlsson61faec12009-09-12 04:46:44 +00002642 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002643 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002644 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002645 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002646 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002647 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002648 return ExprError();
Richard Smithc8d7f582011-11-29 22:48:16 +00002649 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2650 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002651 break;
2652 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002653
Abramo Bagnara737d5442011-04-07 09:26:19 +00002654 case ICK_Boolean_Conversion:
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002655 // Perform half-to-boolean conversion via float.
2656 if (From->getType()->isHalfType()) {
2657 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2658 FromType = Context.FloatTy;
2659 }
2660
Richard Smithc8d7f582011-11-29 22:48:16 +00002661 From = ImpCastExprToType(From, Context.BoolTy,
2662 ScalarTypeToBooleanCastKind(FromType),
2663 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002664 break;
2665
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002666 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002667 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002668 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002669 ToType.getNonReferenceType(),
2670 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002671 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002672 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002673 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002674 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002675
Richard Smithc8d7f582011-11-29 22:48:16 +00002676 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2677 CK_DerivedToBase, From->getValueKind(),
2678 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002679 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002680 }
2681
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002682 case ICK_Vector_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002683 From = ImpCastExprToType(From, ToType, CK_BitCast,
2684 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002685 break;
2686
2687 case ICK_Vector_Splat:
Richard Smithc8d7f582011-11-29 22:48:16 +00002688 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2689 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002690 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002691
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002692 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002693 // Case 1. x -> _Complex y
2694 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2695 QualType ElType = ToComplex->getElementType();
2696 bool isFloatingComplex = ElType->isRealFloatingType();
2697
2698 // x -> y
2699 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2700 // do nothing
2701 } else if (From->getType()->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002702 From = ImpCastExprToType(From, ElType,
2703 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002704 } else {
2705 assert(From->getType()->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002706 From = ImpCastExprToType(From, ElType,
2707 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002708 }
2709 // y -> _Complex y
Richard Smithc8d7f582011-11-29 22:48:16 +00002710 From = ImpCastExprToType(From, ToType,
2711 isFloatingComplex ? CK_FloatingRealToComplex
2712 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002713
2714 // Case 2. _Complex x -> y
2715 } else {
2716 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2717 assert(FromComplex);
2718
2719 QualType ElType = FromComplex->getElementType();
2720 bool isFloatingComplex = ElType->isRealFloatingType();
2721
2722 // _Complex x -> x
Richard Smithc8d7f582011-11-29 22:48:16 +00002723 From = ImpCastExprToType(From, ElType,
2724 isFloatingComplex ? CK_FloatingComplexToReal
2725 : CK_IntegralComplexToReal,
2726 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002727
2728 // x -> y
2729 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2730 // do nothing
2731 } else if (ToType->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002732 From = ImpCastExprToType(From, ToType,
2733 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2734 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002735 } else {
2736 assert(ToType->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002737 From = ImpCastExprToType(From, ToType,
2738 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2739 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002740 }
2741 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002742 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002743
2744 case ICK_Block_Pointer_Conversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002745 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2746 VK_RValue, /*BasePath=*/0, CCK).take();
John McCallf85e1932011-06-15 23:02:42 +00002747 break;
2748 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002749
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002750 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002751 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002752 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002753 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2754 if (FromRes.isInvalid())
2755 return ExprError();
2756 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002757 assert ((ConvTy == Sema::Compatible) &&
2758 "Improper transparent union conversion");
2759 (void)ConvTy;
2760 break;
2761 }
2762
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002763 case ICK_Lvalue_To_Rvalue:
2764 case ICK_Array_To_Pointer:
2765 case ICK_Function_To_Pointer:
2766 case ICK_Qualification:
2767 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002768 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002769 }
2770
2771 switch (SCS.Third) {
2772 case ICK_Identity:
2773 // Nothing to do.
2774 break;
2775
Sebastian Redl906082e2010-07-20 04:20:21 +00002776 case ICK_Qualification: {
2777 // The qualification keeps the category of the inner expression, unless the
2778 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002779 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002780 From->getValueKind() : VK_RValue;
Richard Smithc8d7f582011-11-29 22:48:16 +00002781 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2782 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002783
Douglas Gregor069a6da2011-03-14 16:13:32 +00002784 if (SCS.DeprecatedStringLiteralToCharPtr &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002785 !getLangOpts().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002786 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2787 << ToType.getNonReferenceType();
2788
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002789 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002790 }
2791
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002792 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002793 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002794 }
2795
Douglas Gregor47bfcca2012-04-12 20:42:30 +00002796 // If this conversion sequence involved a scalar -> atomic conversion, perform
2797 // that conversion now.
2798 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>())
2799 if (Context.hasSameType(ToAtomic->getValueType(), From->getType()))
2800 From = ImpCastExprToType(From, ToType, CK_NonAtomicToAtomic, VK_RValue, 0,
2801 CCK).take();
2802
John Wiegley429bb272011-04-08 18:41:53 +00002803 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002804}
2805
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002806ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002807 SourceLocation KWLoc,
2808 ParsedType Ty,
2809 SourceLocation RParen) {
2810 TypeSourceInfo *TSInfo;
2811 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002812
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002813 if (!TSInfo)
2814 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002815 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002816}
2817
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002818/// \brief Check the completeness of a type in a unary type trait.
2819///
2820/// If the particular type trait requires a complete type, tries to complete
2821/// it. If completing the type fails, a diagnostic is emitted and false
2822/// returned. If completing the type succeeds or no completion was required,
2823/// returns true.
2824static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2825 UnaryTypeTrait UTT,
2826 SourceLocation Loc,
2827 QualType ArgTy) {
2828 // C++0x [meta.unary.prop]p3:
2829 // For all of the class templates X declared in this Clause, instantiating
2830 // that template with a template argument that is a class template
2831 // specialization may result in the implicit instantiation of the template
2832 // argument if and only if the semantics of X require that the argument
2833 // must be a complete type.
2834 // We apply this rule to all the type trait expressions used to implement
2835 // these class templates. We also try to follow any GCC documented behavior
2836 // in these expressions to ensure portability of standard libraries.
2837 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002838 // is_complete_type somewhat obviously cannot require a complete type.
2839 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002840 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002841
2842 // These traits are modeled on the type predicates in C++0x
2843 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2844 // requiring a complete type, as whether or not they return true cannot be
2845 // impacted by the completeness of the type.
2846 case UTT_IsVoid:
2847 case UTT_IsIntegral:
2848 case UTT_IsFloatingPoint:
2849 case UTT_IsArray:
2850 case UTT_IsPointer:
2851 case UTT_IsLvalueReference:
2852 case UTT_IsRvalueReference:
2853 case UTT_IsMemberFunctionPointer:
2854 case UTT_IsMemberObjectPointer:
2855 case UTT_IsEnum:
2856 case UTT_IsUnion:
2857 case UTT_IsClass:
2858 case UTT_IsFunction:
2859 case UTT_IsReference:
2860 case UTT_IsArithmetic:
2861 case UTT_IsFundamental:
2862 case UTT_IsObject:
2863 case UTT_IsScalar:
2864 case UTT_IsCompound:
2865 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002866 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002867
2868 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2869 // which requires some of its traits to have the complete type. However,
2870 // the completeness of the type cannot impact these traits' semantics, and
2871 // so they don't require it. This matches the comments on these traits in
2872 // Table 49.
2873 case UTT_IsConst:
2874 case UTT_IsVolatile:
2875 case UTT_IsSigned:
2876 case UTT_IsUnsigned:
2877 return true;
2878
2879 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002880 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002881 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00002882 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002883 case UTT_IsStandardLayout:
2884 case UTT_IsPOD:
2885 case UTT_IsLiteral:
2886 case UTT_IsEmpty:
2887 case UTT_IsPolymorphic:
2888 case UTT_IsAbstract:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002889 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002890
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002891 // These traits require a complete type.
2892 case UTT_IsFinal:
2893
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002894 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002895 // [meta.unary.prop] despite not being named the same. They are specified
2896 // by both GCC and the Embarcadero C++ compiler, and require the complete
2897 // type due to the overarching C++0x type predicates being implemented
2898 // requiring the complete type.
2899 case UTT_HasNothrowAssign:
2900 case UTT_HasNothrowConstructor:
2901 case UTT_HasNothrowCopy:
2902 case UTT_HasTrivialAssign:
Sean Hunt023df372011-05-09 18:22:59 +00002903 case UTT_HasTrivialDefaultConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002904 case UTT_HasTrivialCopy:
2905 case UTT_HasTrivialDestructor:
2906 case UTT_HasVirtualDestructor:
2907 // Arrays of unknown bound are expressly allowed.
2908 QualType ElTy = ArgTy;
2909 if (ArgTy->isIncompleteArrayType())
2910 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2911
2912 // The void type is expressly allowed.
2913 if (ElTy->isVoidType())
2914 return true;
2915
2916 return !S.RequireCompleteType(
2917 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00002918 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00002919 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002920}
2921
2922static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2923 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00002924 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00002925
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002926 ASTContext &C = Self.Context;
2927 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002928 // Type trait expressions corresponding to the primary type category
2929 // predicates in C++0x [meta.unary.cat].
2930 case UTT_IsVoid:
2931 return T->isVoidType();
2932 case UTT_IsIntegral:
2933 return T->isIntegralType(C);
2934 case UTT_IsFloatingPoint:
2935 return T->isFloatingType();
2936 case UTT_IsArray:
2937 return T->isArrayType();
2938 case UTT_IsPointer:
2939 return T->isPointerType();
2940 case UTT_IsLvalueReference:
2941 return T->isLValueReferenceType();
2942 case UTT_IsRvalueReference:
2943 return T->isRValueReferenceType();
2944 case UTT_IsMemberFunctionPointer:
2945 return T->isMemberFunctionPointerType();
2946 case UTT_IsMemberObjectPointer:
2947 return T->isMemberDataPointerType();
2948 case UTT_IsEnum:
2949 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00002950 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002951 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002952 case UTT_IsClass:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002953 return T->isClassType() || T->isStructureType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002954 case UTT_IsFunction:
2955 return T->isFunctionType();
2956
2957 // Type trait expressions which correspond to the convenient composition
2958 // predicates in C++0x [meta.unary.comp].
2959 case UTT_IsReference:
2960 return T->isReferenceType();
2961 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002962 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002963 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002964 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002965 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002966 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002967 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00002968 // Note: semantic analysis depends on Objective-C lifetime types to be
2969 // considered scalar types. However, such types do not actually behave
2970 // like scalar types at run time (since they may require retain/release
2971 // operations), so we report them as non-scalar.
2972 if (T->isObjCLifetimeType()) {
2973 switch (T.getObjCLifetime()) {
2974 case Qualifiers::OCL_None:
2975 case Qualifiers::OCL_ExplicitNone:
2976 return true;
2977
2978 case Qualifiers::OCL_Strong:
2979 case Qualifiers::OCL_Weak:
2980 case Qualifiers::OCL_Autoreleasing:
2981 return false;
2982 }
2983 }
2984
Chandler Carruthcec0ced2011-05-01 09:29:55 +00002985 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002986 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00002987 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00002988 case UTT_IsMemberPointer:
2989 return T->isMemberPointerType();
2990
2991 // Type trait expressions which correspond to the type property predicates
2992 // in C++0x [meta.unary.prop].
2993 case UTT_IsConst:
2994 return T.isConstQualified();
2995 case UTT_IsVolatile:
2996 return T.isVolatileQualified();
2997 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00002998 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00002999 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00003000 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003001 case UTT_IsStandardLayout:
3002 return T->isStandardLayoutType();
3003 case UTT_IsPOD:
Benjamin Kramer470360d2012-04-28 10:00:33 +00003004 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003005 case UTT_IsLiteral:
3006 return T->isLiteralType();
3007 case UTT_IsEmpty:
3008 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3009 return !RD->isUnion() && RD->isEmpty();
3010 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003011 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00003012 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3013 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003014 return false;
3015 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00003016 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3017 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003018 return false;
Douglas Gregor5e9392b2011-12-03 18:14:24 +00003019 case UTT_IsFinal:
3020 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3021 return RD->hasAttr<FinalAttr>();
3022 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00003023 case UTT_IsSigned:
3024 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00003025 case UTT_IsUnsigned:
3026 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003027
3028 // Type trait expressions which query classes regarding their construction,
3029 // destruction, and copying. Rather than being based directly on the
3030 // related type predicates in the standard, they are specified by both
3031 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3032 // specifications.
3033 //
3034 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3035 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Sean Hunt023df372011-05-09 18:22:59 +00003036 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003037 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3038 // If __is_pod (type) is true then the trait is true, else if type is
3039 // a cv class or union type (or array thereof) with a trivial default
3040 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003041 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003042 return true;
3043 if (const RecordType *RT =
3044 C.getBaseElementType(T)->getAs<RecordType>())
Sean Hunt023df372011-05-09 18:22:59 +00003045 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003046 return false;
3047 case UTT_HasTrivialCopy:
3048 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3049 // If __is_pod (type) is true or type is a reference type then
3050 // the trait is true, else if type is a cv class or union type
3051 // with a trivial copy constructor ([class.copy]) then the trait
3052 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003053 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003054 return true;
3055 if (const RecordType *RT = T->getAs<RecordType>())
3056 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
3057 return false;
3058 case UTT_HasTrivialAssign:
3059 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3060 // If type is const qualified or is a reference type then the
3061 // trait is false. Otherwise if __is_pod (type) is true then the
3062 // trait is true, else if type is a cv class or union type with
3063 // a trivial copy assignment ([class.copy]) then the trait is
3064 // true, else it is false.
3065 // Note: the const and reference restrictions are interesting,
3066 // given that const and reference members don't prevent a class
3067 // from having a trivial copy assignment operator (but do cause
3068 // errors if the copy assignment operator is actually used, q.v.
3069 // [class.copy]p12).
3070
3071 if (C.getBaseElementType(T).isConstQualified())
3072 return false;
John McCallf85e1932011-06-15 23:02:42 +00003073 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003074 return true;
3075 if (const RecordType *RT = T->getAs<RecordType>())
3076 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
3077 return false;
3078 case UTT_HasTrivialDestructor:
3079 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3080 // If __is_pod (type) is true or type is a reference type
3081 // then the trait is true, else if type is a cv class or union
3082 // type (or array thereof) with a trivial destructor
3083 // ([class.dtor]) then the trait is true, else it is
3084 // false.
John McCallf85e1932011-06-15 23:02:42 +00003085 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003086 return true;
John McCallf85e1932011-06-15 23:02:42 +00003087
3088 // Objective-C++ ARC: autorelease types don't require destruction.
3089 if (T->isObjCLifetimeType() &&
3090 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3091 return true;
3092
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003093 if (const RecordType *RT =
3094 C.getBaseElementType(T)->getAs<RecordType>())
3095 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
3096 return false;
3097 // TODO: Propagate nothrowness for implicitly declared special members.
3098 case UTT_HasNothrowAssign:
3099 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3100 // If type is const qualified or is a reference type then the
3101 // trait is false. Otherwise if __has_trivial_assign (type)
3102 // is true then the trait is true, else if type is a cv class
3103 // or union type with copy assignment operators that are known
3104 // not to throw an exception then the trait is true, else it is
3105 // false.
3106 if (C.getBaseElementType(T).isConstQualified())
3107 return false;
3108 if (T->isReferenceType())
3109 return false;
John McCallf85e1932011-06-15 23:02:42 +00003110 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
3111 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003112 if (const RecordType *RT = T->getAs<RecordType>()) {
3113 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
3114 if (RD->hasTrivialCopyAssignment())
3115 return true;
3116
3117 bool FoundAssign = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003118 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redlf8aca862010-09-14 23:40:14 +00003119 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
3120 Sema::LookupOrdinaryName);
3121 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregord41679d2011-10-12 15:40:49 +00003122 Res.suppressDiagnostics();
Sebastian Redlf8aca862010-09-14 23:40:14 +00003123 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3124 Op != OpEnd; ++Op) {
Douglas Gregord41679d2011-10-12 15:40:49 +00003125 if (isa<FunctionTemplateDecl>(*Op))
3126 continue;
3127
Sebastian Redlf8aca862010-09-14 23:40:14 +00003128 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3129 if (Operator->isCopyAssignmentOperator()) {
3130 FoundAssign = true;
3131 const FunctionProtoType *CPT
3132 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +00003133 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3134 if (!CPT)
3135 return false;
Richard Smith7a614d82011-06-11 17:19:42 +00003136 if (CPT->getExceptionSpecType() == EST_Delayed)
3137 return false;
3138 if (!CPT->isNothrow(Self.Context))
3139 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003140 }
3141 }
3142 }
Douglas Gregord41679d2011-10-12 15:40:49 +00003143
Richard Smith7a614d82011-06-11 17:19:42 +00003144 return FoundAssign;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003145 }
3146 return false;
3147 case UTT_HasNothrowCopy:
3148 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3149 // If __has_trivial_copy (type) is true then the trait is true, else
3150 // if type is a cv class or union type with copy constructors that are
3151 // known not to throw an exception then the trait is true, else it is
3152 // false.
John McCallf85e1932011-06-15 23:02:42 +00003153 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003154 return true;
3155 if (const RecordType *RT = T->getAs<RecordType>()) {
3156 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3157 if (RD->hasTrivialCopyConstructor())
3158 return true;
3159
3160 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003161 unsigned FoundTQs;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003162 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl5f4e8992010-09-13 21:10:20 +00003163 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003164 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003165 // A template constructor is never a copy constructor.
3166 // FIXME: However, it may actually be selected at the actual overload
3167 // resolution point.
3168 if (isa<FunctionTemplateDecl>(*Con))
3169 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003170 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3171 if (Constructor->isCopyConstructor(FoundTQs)) {
3172 FoundConstructor = true;
3173 const FunctionProtoType *CPT
3174 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +00003175 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3176 if (!CPT)
3177 return false;
Richard Smith7a614d82011-06-11 17:19:42 +00003178 if (CPT->getExceptionSpecType() == EST_Delayed)
3179 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003180 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00003181 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00003182 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3183 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003184 }
3185 }
3186
Richard Smith7a614d82011-06-11 17:19:42 +00003187 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003188 }
3189 return false;
3190 case UTT_HasNothrowConstructor:
3191 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3192 // If __has_trivial_constructor (type) is true then the trait is
3193 // true, else if type is a cv class or union type (or array
3194 // thereof) with a default constructor that is known not to
3195 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003196 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003197 return true;
3198 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3199 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Hunt023df372011-05-09 18:22:59 +00003200 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003201 return true;
3202
Sebastian Redl751025d2010-09-13 22:02:47 +00003203 DeclContext::lookup_const_iterator Con, ConEnd;
3204 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3205 Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003206 // FIXME: In C++0x, a constructor template can be a default constructor.
3207 if (isa<FunctionTemplateDecl>(*Con))
3208 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00003209 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3210 if (Constructor->isDefaultConstructor()) {
3211 const FunctionProtoType *CPT
3212 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +00003213 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3214 if (!CPT)
3215 return false;
Richard Smith7a614d82011-06-11 17:19:42 +00003216 if (CPT->getExceptionSpecType() == EST_Delayed)
3217 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00003218 // TODO: check whether evaluating default arguments can throw.
3219 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003220 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00003221 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003222 }
3223 }
3224 return false;
3225 case UTT_HasVirtualDestructor:
3226 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3227 // If type is a class type with a virtual destructor ([class.dtor])
3228 // then the trait is true, else it is false.
3229 if (const RecordType *Record = T->getAs<RecordType>()) {
3230 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redlf8aca862010-09-14 23:40:14 +00003231 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003232 return Destructor->isVirtual();
3233 }
3234 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003235
3236 // These type trait expressions are modeled on the specifications for the
3237 // Embarcadero C++0x type trait functions:
3238 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3239 case UTT_IsCompleteType:
3240 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3241 // Returns True if and only if T is a complete type at the point of the
3242 // function call.
3243 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003244 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00003245 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003246}
3247
3248ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00003249 SourceLocation KWLoc,
3250 TypeSourceInfo *TSInfo,
3251 SourceLocation RParen) {
3252 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00003253 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3254 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00003255
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003256 bool Value = false;
3257 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003258 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003259
3260 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00003261 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00003262}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003263
Francois Pichet6ad6f282010-12-07 00:08:36 +00003264ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3265 SourceLocation KWLoc,
3266 ParsedType LhsTy,
3267 ParsedType RhsTy,
3268 SourceLocation RParen) {
3269 TypeSourceInfo *LhsTSInfo;
3270 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3271 if (!LhsTSInfo)
3272 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3273
3274 TypeSourceInfo *RhsTSInfo;
3275 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3276 if (!RhsTSInfo)
3277 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3278
3279 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3280}
3281
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003282static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3283 ArrayRef<TypeSourceInfo *> Args,
3284 SourceLocation RParenLoc) {
3285 switch (Kind) {
3286 case clang::TT_IsTriviallyConstructible: {
3287 // C++11 [meta.unary.prop]:
Dmitri Gribenko62348f02012-02-24 20:03:35 +00003288 // is_trivially_constructible is defined as:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003289 //
Dmitri Gribenko62348f02012-02-24 20:03:35 +00003290 // is_constructible<T, Args...>::value is true and the variable
3291 // definition for is_constructible, as defined below, is known to call no
3292 // operation that is not trivial.
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003293 //
3294 // The predicate condition for a template specialization
3295 // is_constructible<T, Args...> shall be satisfied if and only if the
3296 // following variable definition would be well-formed for some invented
3297 // variable t:
3298 //
3299 // T t(create<Args>()...);
3300 if (Args.empty()) {
3301 S.Diag(KWLoc, diag::err_type_trait_arity)
3302 << 1 << 1 << 1 << (int)Args.size();
3303 return false;
3304 }
3305
3306 bool SawVoid = false;
3307 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3308 if (Args[I]->getType()->isVoidType()) {
3309 SawVoid = true;
3310 continue;
3311 }
3312
3313 if (!Args[I]->getType()->isIncompleteType() &&
3314 S.RequireCompleteType(KWLoc, Args[I]->getType(),
3315 diag::err_incomplete_type_used_in_type_trait_expr))
3316 return false;
3317 }
3318
3319 // If any argument was 'void', of course it won't type-check.
3320 if (SawVoid)
3321 return false;
3322
3323 llvm::SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3324 llvm::SmallVector<Expr *, 2> ArgExprs;
3325 ArgExprs.reserve(Args.size() - 1);
3326 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3327 QualType T = Args[I]->getType();
3328 if (T->isObjectType() || T->isFunctionType())
3329 T = S.Context.getRValueReferenceType(T);
3330 OpaqueArgExprs.push_back(
Daniel Dunbar96a00142012-03-09 18:35:03 +00003331 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003332 T.getNonLValueExprType(S.Context),
3333 Expr::getValueKindForType(T)));
3334 ArgExprs.push_back(&OpaqueArgExprs.back());
3335 }
3336
3337 // Perform the initialization in an unevaluated context within a SFINAE
3338 // trap at translation unit scope.
3339 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3340 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3341 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3342 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3343 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3344 RParenLoc));
3345 InitializationSequence Init(S, To, InitKind,
3346 ArgExprs.begin(), ArgExprs.size());
3347 if (Init.Failed())
3348 return false;
3349
3350 ExprResult Result = Init.Perform(S, To, InitKind,
3351 MultiExprArg(ArgExprs.data(),
3352 ArgExprs.size()));
3353 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3354 return false;
3355
3356 // The initialization succeeded; not make sure there are no non-trivial
3357 // calls.
3358 return !Result.get()->hasNonTrivialCall(S.Context);
3359 }
3360 }
3361
3362 return false;
3363}
3364
3365ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3366 ArrayRef<TypeSourceInfo *> Args,
3367 SourceLocation RParenLoc) {
3368 bool Dependent = false;
3369 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3370 if (Args[I]->getType()->isDependentType()) {
3371 Dependent = true;
3372 break;
3373 }
3374 }
3375
3376 bool Value = false;
3377 if (!Dependent)
3378 Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3379
3380 return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind,
3381 Args, RParenLoc, Value);
3382}
3383
3384ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3385 ArrayRef<ParsedType> Args,
3386 SourceLocation RParenLoc) {
3387 llvm::SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
3388 ConvertedArgs.reserve(Args.size());
3389
3390 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3391 TypeSourceInfo *TInfo;
3392 QualType T = GetTypeFromParser(Args[I], &TInfo);
3393 if (!TInfo)
3394 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3395
3396 ConvertedArgs.push_back(TInfo);
3397 }
3398
3399 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3400}
3401
Francois Pichet6ad6f282010-12-07 00:08:36 +00003402static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3403 QualType LhsT, QualType RhsT,
3404 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003405 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3406 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003407
3408 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003409 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003410 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003411 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003412 // Base and Derived are not unions and name the same class type without
3413 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003414
John McCalld89d30f2011-01-28 22:02:36 +00003415 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3416 if (!lhsRecord) return false;
3417
3418 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3419 if (!rhsRecord) return false;
3420
3421 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3422 == (lhsRecord == rhsRecord));
3423
3424 if (lhsRecord == rhsRecord)
3425 return !lhsRecord->getDecl()->isUnion();
3426
3427 // C++0x [meta.rel]p2:
3428 // If Base and Derived are class types and are different types
3429 // (ignoring possible cv-qualifiers) then Derived shall be a
3430 // complete type.
3431 if (Self.RequireCompleteType(KeyLoc, RhsT,
3432 diag::err_incomplete_type_used_in_type_trait_expr))
3433 return false;
3434
3435 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3436 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3437 }
John Wiegley20c0da72011-04-27 23:09:49 +00003438 case BTT_IsSame:
3439 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003440 case BTT_TypeCompatible:
3441 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3442 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003443 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003444 case BTT_IsConvertibleTo: {
3445 // C++0x [meta.rel]p4:
3446 // Given the following function prototype:
3447 //
3448 // template <class T>
3449 // typename add_rvalue_reference<T>::type create();
3450 //
3451 // the predicate condition for a template specialization
3452 // is_convertible<From, To> shall be satisfied if and only if
3453 // the return expression in the following code would be
3454 // well-formed, including any implicit conversions to the return
3455 // type of the function:
3456 //
3457 // To test() {
3458 // return create<From>();
3459 // }
3460 //
3461 // Access checking is performed as if in a context unrelated to To and
3462 // From. Only the validity of the immediate context of the expression
3463 // of the return-statement (including conversions to the return type)
3464 // is considered.
3465 //
3466 // We model the initialization as a copy-initialization of a temporary
3467 // of the appropriate type, which for this expression is identical to the
3468 // return statement (since NRVO doesn't apply).
3469 if (LhsT->isObjectType() || LhsT->isFunctionType())
3470 LhsT = Self.Context.getRValueReferenceType(LhsT);
3471
3472 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003473 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003474 Expr::getValueKindForType(LhsT));
3475 Expr *FromPtr = &From;
3476 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3477 SourceLocation()));
3478
Eli Friedman3add9f02012-01-25 01:05:57 +00003479 // Perform the initialization in an unevaluated context within a SFINAE
3480 // trap at translation unit scope.
3481 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003482 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3483 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor9f361132011-01-27 20:28:01 +00003484 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003485 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003486 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003487
Douglas Gregor9f361132011-01-27 20:28:01 +00003488 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3489 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3490 }
Douglas Gregor25d0a0f2012-02-23 07:33:15 +00003491
3492 case BTT_IsTriviallyAssignable: {
3493 // C++11 [meta.unary.prop]p3:
3494 // is_trivially_assignable is defined as:
3495 // is_assignable<T, U>::value is true and the assignment, as defined by
3496 // is_assignable, is known to call no operation that is not trivial
3497 //
3498 // is_assignable is defined as:
3499 // The expression declval<T>() = declval<U>() is well-formed when
3500 // treated as an unevaluated operand (Clause 5).
3501 //
3502 // For both, T and U shall be complete types, (possibly cv-qualified)
3503 // void, or arrays of unknown bound.
3504 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3505 Self.RequireCompleteType(KeyLoc, LhsT,
3506 diag::err_incomplete_type_used_in_type_trait_expr))
3507 return false;
3508 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3509 Self.RequireCompleteType(KeyLoc, RhsT,
3510 diag::err_incomplete_type_used_in_type_trait_expr))
3511 return false;
3512
3513 // cv void is never assignable.
3514 if (LhsT->isVoidType() || RhsT->isVoidType())
3515 return false;
3516
3517 // Build expressions that emulate the effect of declval<T>() and
3518 // declval<U>().
3519 if (LhsT->isObjectType() || LhsT->isFunctionType())
3520 LhsT = Self.Context.getRValueReferenceType(LhsT);
3521 if (RhsT->isObjectType() || RhsT->isFunctionType())
3522 RhsT = Self.Context.getRValueReferenceType(RhsT);
3523 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3524 Expr::getValueKindForType(LhsT));
3525 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3526 Expr::getValueKindForType(RhsT));
3527
3528 // Attempt the assignment in an unevaluated context within a SFINAE
3529 // trap at translation unit scope.
3530 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3531 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3532 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3533 ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs);
3534 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3535 return false;
3536
3537 return !Result.get()->hasNonTrivialCall(Self.Context);
3538 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003539 }
3540 llvm_unreachable("Unknown type trait or not implemented");
3541}
3542
3543ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3544 SourceLocation KWLoc,
3545 TypeSourceInfo *LhsTSInfo,
3546 TypeSourceInfo *RhsTSInfo,
3547 SourceLocation RParen) {
3548 QualType LhsT = LhsTSInfo->getType();
3549 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003550
John McCalld89d30f2011-01-28 22:02:36 +00003551 if (BTT == BTT_TypeCompatible) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003552 if (getLangOpts().CPlusPlus) {
Francois Pichetf1872372010-12-08 22:35:30 +00003553 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3554 << SourceRange(KWLoc, RParen);
3555 return ExprError();
3556 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003557 }
3558
3559 bool Value = false;
3560 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3561 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3562
Francois Pichetf1872372010-12-08 22:35:30 +00003563 // Select trait result type.
3564 QualType ResultType;
3565 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003566 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003567 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3568 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003569 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003570 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Douglas Gregor25d0a0f2012-02-23 07:33:15 +00003571 case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy;
Francois Pichetf1872372010-12-08 22:35:30 +00003572 }
3573
Francois Pichet6ad6f282010-12-07 00:08:36 +00003574 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3575 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003576 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003577}
3578
John Wiegley21ff2e52011-04-28 00:16:57 +00003579ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3580 SourceLocation KWLoc,
3581 ParsedType Ty,
3582 Expr* DimExpr,
3583 SourceLocation RParen) {
3584 TypeSourceInfo *TSInfo;
3585 QualType T = GetTypeFromParser(Ty, &TSInfo);
3586 if (!TSInfo)
3587 TSInfo = Context.getTrivialTypeSourceInfo(T);
3588
3589 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3590}
3591
3592static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3593 QualType T, Expr *DimExpr,
3594 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003595 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003596
3597 switch(ATT) {
3598 case ATT_ArrayRank:
3599 if (T->isArrayType()) {
3600 unsigned Dim = 0;
3601 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3602 ++Dim;
3603 T = AT->getElementType();
3604 }
3605 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003606 }
John Wiegleycf566412011-04-28 02:06:46 +00003607 return 0;
3608
John Wiegley21ff2e52011-04-28 00:16:57 +00003609 case ATT_ArrayExtent: {
3610 llvm::APSInt Value;
3611 uint64_t Dim;
Richard Smith282e7e62012-02-04 09:53:13 +00003612 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
3613 Self.PDiag(diag::err_dimension_expr_not_constant_integer),
3614 false).isInvalid())
3615 return 0;
3616 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbare7d6ca02012-03-09 21:38:22 +00003617 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3618 << DimExpr->getSourceRange();
Richard Smith282e7e62012-02-04 09:53:13 +00003619 return 0;
John Wiegleycf566412011-04-28 02:06:46 +00003620 }
Richard Smith282e7e62012-02-04 09:53:13 +00003621 Dim = Value.getLimitedValue();
John Wiegley21ff2e52011-04-28 00:16:57 +00003622
3623 if (T->isArrayType()) {
3624 unsigned D = 0;
3625 bool Matched = false;
3626 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3627 if (Dim == D) {
3628 Matched = true;
3629 break;
3630 }
3631 ++D;
3632 T = AT->getElementType();
3633 }
3634
John Wiegleycf566412011-04-28 02:06:46 +00003635 if (Matched && T->isArrayType()) {
3636 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3637 return CAT->getSize().getLimitedValue();
3638 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003639 }
John Wiegleycf566412011-04-28 02:06:46 +00003640 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003641 }
3642 }
3643 llvm_unreachable("Unknown type trait or not implemented");
3644}
3645
3646ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3647 SourceLocation KWLoc,
3648 TypeSourceInfo *TSInfo,
3649 Expr* DimExpr,
3650 SourceLocation RParen) {
3651 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003652
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003653 // FIXME: This should likely be tracked as an APInt to remove any host
3654 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003655 uint64_t Value = 0;
3656 if (!T->isDependentType())
3657 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3658
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003659 // While the specification for these traits from the Embarcadero C++
3660 // compiler's documentation says the return type is 'unsigned int', Clang
3661 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3662 // compiler, there is no difference. On several other platforms this is an
3663 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003664 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003665 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003666 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003667}
3668
John Wiegley55262202011-04-25 06:54:41 +00003669ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003670 SourceLocation KWLoc,
3671 Expr *Queried,
3672 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003673 // If error parsing the expression, ignore.
3674 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003675 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003676
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003677 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003678
3679 return move(Result);
3680}
3681
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003682static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3683 switch (ET) {
3684 case ET_IsLValueExpr: return E->isLValue();
3685 case ET_IsRValueExpr: return E->isRValue();
3686 }
3687 llvm_unreachable("Expression trait not covered by switch");
3688}
3689
John Wiegley55262202011-04-25 06:54:41 +00003690ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003691 SourceLocation KWLoc,
3692 Expr *Queried,
3693 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003694 if (Queried->isTypeDependent()) {
3695 // Delay type-checking for type-dependent expressions.
3696 } else if (Queried->getType()->isPlaceholderType()) {
3697 ExprResult PE = CheckPlaceholderExpr(Queried);
3698 if (PE.isInvalid()) return ExprError();
3699 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3700 }
3701
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003702 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003703
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003704 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3705 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003706}
3707
Richard Trieudd225092011-09-15 21:56:47 +00003708QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003709 ExprValueKind &VK,
3710 SourceLocation Loc,
3711 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003712 assert(!LHS.get()->getType()->isPlaceholderType() &&
3713 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003714 "placeholders should have been weeded out by now");
3715
3716 // The LHS undergoes lvalue conversions if this is ->*.
3717 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003718 LHS = DefaultLvalueConversion(LHS.take());
3719 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003720 }
3721
3722 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003723 RHS = DefaultLvalueConversion(RHS.take());
3724 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003725
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003726 const char *OpSpelling = isIndirect ? "->*" : ".*";
3727 // C++ 5.5p2
3728 // The binary operator .* [p3: ->*] binds its second operand, which shall
3729 // be of type "pointer to member of T" (where T is a completely-defined
3730 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003731 QualType RHSType = RHS.get()->getType();
3732 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003733 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003734 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003735 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003736 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003737 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003738
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003739 QualType Class(MemPtr->getClass(), 0);
3740
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003741 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3742 // member pointer points must be completely-defined. However, there is no
3743 // reason for this semantic distinction, and the rule is not enforced by
3744 // other compilers. Therefore, we do not check this property, as it is
3745 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003746
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003747 // C++ 5.5p2
3748 // [...] to its first operand, which shall be of class T or of a class of
3749 // which T is an unambiguous and accessible base class. [p3: a pointer to
3750 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00003751 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003752 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003753 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3754 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003755 else {
3756 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00003757 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00003758 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003759 return QualType();
3760 }
3761 }
3762
Richard Trieudd225092011-09-15 21:56:47 +00003763 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003764 // If we want to check the hierarchy, we need a complete type.
Douglas Gregord10099e2012-05-04 16:32:21 +00003765 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
3766 OpSpelling, (int)isIndirect)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00003767 return QualType();
3768 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003769 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00003770 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00003771 // FIXME: Would it be useful to print full ambiguity paths, or is that
3772 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00003773 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003774 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3775 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00003776 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003777 return QualType();
3778 }
Eli Friedman3005efe2010-01-16 00:00:48 +00003779 // Cast LHS to type of use.
3780 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00003781 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00003782
John McCallf871d0c2010-08-07 06:22:56 +00003783 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00003784 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00003785 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3786 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003787 }
3788
Richard Trieudd225092011-09-15 21:56:47 +00003789 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00003790 // Diagnose use of pointer-to-member type which when used as
3791 // the functional cast in a pointer-to-member expression.
3792 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3793 return QualType();
3794 }
John McCallf89e55a2010-11-18 06:31:45 +00003795
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003796 // C++ 5.5p2
3797 // The result is an object or a function of the type specified by the
3798 // second operand.
3799 // The cv qualifiers are the union of those in the pointer and the left side,
3800 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003801 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00003802 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00003803
Douglas Gregor6b4df912011-01-26 16:40:18 +00003804 // C++0x [expr.mptr.oper]p6:
3805 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003806 // ill-formed if the second operand is a pointer to member function with
3807 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3808 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00003809 // is a pointer to member function with ref-qualifier &&.
3810 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3811 switch (Proto->getRefQualifier()) {
3812 case RQ_None:
3813 // Do nothing
3814 break;
3815
3816 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00003817 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003818 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003819 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003820 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003821
Douglas Gregor6b4df912011-01-26 16:40:18 +00003822 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00003823 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00003824 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00003825 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00003826 break;
3827 }
3828 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003829
John McCallf89e55a2010-11-18 06:31:45 +00003830 // C++ [expr.mptr.oper]p6:
3831 // The result of a .* expression whose second operand is a pointer
3832 // to a data member is of the same value category as its
3833 // first operand. The result of a .* expression whose second
3834 // operand is a pointer to a member function is a prvalue. The
3835 // result of an ->* expression is an lvalue if its second operand
3836 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00003837 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00003838 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00003839 return Context.BoundMemberTy;
3840 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00003841 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00003842 } else {
Richard Trieudd225092011-09-15 21:56:47 +00003843 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00003844 }
John McCallf89e55a2010-11-18 06:31:45 +00003845
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003846 return Result;
3847}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003848
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003849/// \brief Try to convert a type to another according to C++0x 5.16p3.
3850///
3851/// This is part of the parameter validation for the ? operator. If either
3852/// value operand is a class type, the two operands are attempted to be
3853/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003854/// It returns true if the program is ill-formed and has already been diagnosed
3855/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003856static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3857 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00003858 bool &HaveConversion,
3859 QualType &ToType) {
3860 HaveConversion = false;
3861 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003862
3863 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00003864 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003865 // C++0x 5.16p3
3866 // The process for determining whether an operand expression E1 of type T1
3867 // can be converted to match an operand expression E2 of type T2 is defined
3868 // as follows:
3869 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00003870 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003871 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003872 // E1 can be converted to match E2 if E1 can be implicitly converted to
3873 // type "lvalue reference to T2", subject to the constraint that in the
3874 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00003875 QualType T = Self.Context.getLValueReferenceType(ToType);
3876 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003877
Douglas Gregorb70cf442010-03-26 20:14:36 +00003878 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3879 if (InitSeq.isDirectReferenceBinding()) {
3880 ToType = T;
3881 HaveConversion = true;
3882 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003883 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003884
Douglas Gregorb70cf442010-03-26 20:14:36 +00003885 if (InitSeq.isAmbiguous())
3886 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003887 }
John McCallb1bdc622010-02-25 01:37:24 +00003888
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003889 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3890 // -- if E1 and E2 have class type, and the underlying class types are
3891 // the same or one is a base class of the other:
3892 QualType FTy = From->getType();
3893 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003894 const RecordType *FRec = FTy->getAs<RecordType>();
3895 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003896 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003897 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003898 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00003899 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003900 // E1 can be converted to match E2 if the class of T2 is the
3901 // same type as, or a base class of, the class of T1, and
3902 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00003903 if (FRec == TRec || FDerivedFromT) {
3904 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003905 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3906 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003907 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00003908 HaveConversion = true;
3909 return false;
3910 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003911
Douglas Gregorb70cf442010-03-26 20:14:36 +00003912 if (InitSeq.isAmbiguous())
3913 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003914 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003915 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003916
Douglas Gregorb70cf442010-03-26 20:14:36 +00003917 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003918 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003919
Douglas Gregorb70cf442010-03-26 20:14:36 +00003920 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3921 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003922 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00003923 // an rvalue).
3924 //
3925 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3926 // to the array-to-pointer or function-to-pointer conversions.
3927 if (!TTy->getAs<TagType>())
3928 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003929
Douglas Gregorb70cf442010-03-26 20:14:36 +00003930 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3931 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00003932 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00003933 ToType = TTy;
3934 if (InitSeq.isAmbiguous())
3935 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3936
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003937 return false;
3938}
3939
3940/// \brief Try to find a common type for two according to C++0x 5.16p5.
3941///
3942/// This is part of the parameter validation for the ? operator. If either
3943/// value operand is a class type, overload resolution is used to find a
3944/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00003945static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00003946 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00003947 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00003948 OverloadCandidateSet CandidateSet(QuestionLoc);
3949 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3950 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003951
3952 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00003953 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00003954 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003955 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00003956 ExprResult LHSRes =
3957 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3958 Best->Conversions[0], Sema::AA_Converting);
3959 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003960 break;
John Wiegley429bb272011-04-08 18:41:53 +00003961 LHS = move(LHSRes);
3962
3963 ExprResult RHSRes =
3964 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3965 Best->Conversions[1], Sema::AA_Converting);
3966 if (RHSRes.isInvalid())
3967 break;
3968 RHS = move(RHSRes);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003969 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00003970 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003971 return false;
John Wiegley429bb272011-04-08 18:41:53 +00003972 }
3973
Douglas Gregor20093b42009-12-09 23:02:17 +00003974 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00003975
3976 // Emit a better diagnostic if one of the expressions is a null pointer
3977 // constant and the other is a pointer type. In this case, the user most
3978 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00003979 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00003980 return true;
3981
3982 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00003983 << LHS.get()->getType() << RHS.get()->getType()
3984 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003985 return true;
3986
Douglas Gregor20093b42009-12-09 23:02:17 +00003987 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00003988 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00003989 << LHS.get()->getType() << RHS.get()->getType()
3990 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00003991 // FIXME: Print the possible common types by printing the return types of
3992 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003993 break;
3994
Douglas Gregor20093b42009-12-09 23:02:17 +00003995 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00003996 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003997 }
3998 return true;
3999}
4000
Sebastian Redl76458502009-04-17 16:30:52 +00004001/// \brief Perform an "extended" implicit conversion as returned by
4002/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00004003static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00004004 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00004005 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00004006 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00004007 Expr *Arg = E.take();
4008 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
4009 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregorb70cf442010-03-26 20:14:36 +00004010 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00004011 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004012
John Wiegley429bb272011-04-08 18:41:53 +00004013 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00004014 return false;
4015}
4016
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004017/// \brief Check the operands of ?: under C++ semantics.
4018///
4019/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4020/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley429bb272011-04-08 18:41:53 +00004021QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCall56ca35d2011-02-17 10:25:35 +00004022 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004023 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00004024 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4025 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004026
4027 // C++0x 5.16p1
4028 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00004029 if (!Cond.get()->isTypeDependent()) {
4030 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
4031 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004032 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004033 Cond = move(CondRes);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004034 }
4035
John McCallf89e55a2010-11-18 06:31:45 +00004036 // Assume r-value.
4037 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004038 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00004039
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004040 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00004041 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004042 return Context.DependentTy;
4043
4044 // C++0x 5.16p2
4045 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00004046 QualType LTy = LHS.get()->getType();
4047 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004048 bool LVoid = LTy->isVoidType();
4049 bool RVoid = RTy->isVoidType();
4050 if (LVoid || RVoid) {
4051 // ... then the [l2r] conversions are performed on the second and third
4052 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00004053 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4054 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4055 if (LHS.isInvalid() || RHS.isInvalid())
4056 return QualType();
4057 LTy = LHS.get()->getType();
4058 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004059
4060 // ... and one of the following shall hold:
4061 // -- The second or the third operand (but not both) is a throw-
4062 // expression; the result is of the type of the other and is an rvalue.
John Wiegley429bb272011-04-08 18:41:53 +00004063 bool LThrow = isa<CXXThrowExpr>(LHS.get());
4064 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004065 if (LThrow && !RThrow)
4066 return RTy;
4067 if (RThrow && !LThrow)
4068 return LTy;
4069
4070 // -- Both the second and third operands have type void; the result is of
4071 // type void and is an rvalue.
4072 if (LVoid && RVoid)
4073 return Context.VoidTy;
4074
4075 // Neither holds, error.
4076 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4077 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00004078 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004079 return QualType();
4080 }
4081
4082 // Neither is void.
4083
4084 // C++0x 5.16p3
4085 // Otherwise, if the second and third operand have different types, and
4086 // either has (cv) class type, and attempt is made to convert each of those
4087 // operands to the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004088 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004089 (LTy->isRecordType() || RTy->isRecordType())) {
4090 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
4091 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00004092 QualType L2RType, R2LType;
4093 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00004094 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004095 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004096 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004097 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004098
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004099 // If both can be converted, [...] the program is ill-formed.
4100 if (HaveL2R && HaveR2L) {
4101 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00004102 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004103 return QualType();
4104 }
4105
4106 // If exactly one conversion is possible, that conversion is applied to
4107 // the chosen operand and the converted operands are used in place of the
4108 // original operands for the remainder of this section.
4109 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00004110 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004111 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004112 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004113 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00004114 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004115 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004116 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004117 }
4118 }
4119
4120 // C++0x 5.16p4
John McCallf89e55a2010-11-18 06:31:45 +00004121 // If the second and third operands are glvalues of the same value
4122 // category and have the same type, the result is of that type and
4123 // value category and it is a bit-field if the second or the third
4124 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00004125 // We only extend this to bitfields, not to the crazy other kinds of
4126 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00004127 bool Same = Context.hasSameType(LTy, RTy);
John McCallf89e55a2010-11-18 06:31:45 +00004128 if (Same &&
John Wiegley429bb272011-04-08 18:41:53 +00004129 LHS.get()->isGLValue() &&
4130 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
4131 LHS.get()->isOrdinaryOrBitFieldObject() &&
4132 RHS.get()->isOrdinaryOrBitFieldObject()) {
4133 VK = LHS.get()->getValueKind();
4134 if (LHS.get()->getObjectKind() == OK_BitField ||
4135 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00004136 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00004137 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00004138 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004139
4140 // C++0x 5.16p5
4141 // Otherwise, the result is an rvalue. If the second and third operands
4142 // do not have the same type, and either has (cv) class type, ...
4143 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4144 // ... overload resolution is used to determine the conversions (if any)
4145 // to be applied to the operands. If the overload resolution fails, the
4146 // program is ill-formed.
4147 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4148 return QualType();
4149 }
4150
4151 // C++0x 5.16p6
4152 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
4153 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00004154 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4155 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4156 if (LHS.isInvalid() || RHS.isInvalid())
4157 return QualType();
4158 LTy = LHS.get()->getType();
4159 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004160
4161 // After those conversions, one of the following shall hold:
4162 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00004163 // is of that type. If the operands have class type, the result
4164 // is a prvalue temporary of the result type, which is
4165 // copy-initialized from either the second operand or the third
4166 // operand depending on the value of the first operand.
4167 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4168 if (LTy->isRecordType()) {
4169 // The operands have class type. Make a temporary copy.
4170 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004171 ExprResult LHSCopy = PerformCopyInitialization(Entity,
4172 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00004173 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00004174 if (LHSCopy.isInvalid())
4175 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004176
4177 ExprResult RHSCopy = PerformCopyInitialization(Entity,
4178 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00004179 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00004180 if (RHSCopy.isInvalid())
4181 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004182
John Wiegley429bb272011-04-08 18:41:53 +00004183 LHS = LHSCopy;
4184 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00004185 }
4186
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004187 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00004188 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004189
Douglas Gregorfb4a5432010-05-18 22:42:18 +00004190 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004191 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004192 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00004193
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004194 // -- The second and third operands have arithmetic or enumeration type;
4195 // the usual arithmetic conversions are performed to bring them to a
4196 // common type, and the result is of that type.
4197 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4198 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004199 if (LHS.isInvalid() || RHS.isInvalid())
4200 return QualType();
4201 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004202 }
4203
4204 // -- The second and third operands have pointer type, or one has pointer
4205 // type and the other is a null pointer constant; pointer conversions
4206 // and qualification conversions are performed to bring them to their
4207 // composite pointer type. The result is of the composite pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00004208 // -- The second and third operands have pointer to member type, or one has
4209 // pointer to member type and the other is a null pointer constant;
4210 // pointer to member conversions and qualification conversions are
4211 // performed to bring them to a common type, whose cv-qualification
4212 // shall match the cv-qualification of either the second or the third
4213 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004214 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004215 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004216 isSFINAEContext()? 0 : &NonStandardCompositeType);
4217 if (!Composite.isNull()) {
4218 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004219 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004220 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4221 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00004222 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004223
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004224 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004225 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004226
Douglas Gregor1927b1f2010-04-01 22:47:07 +00004227 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00004228 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4229 if (!Composite.isNull())
4230 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004231
Chandler Carruth7ef93242011-02-19 00:13:59 +00004232 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00004233 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00004234 return QualType();
4235
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004236 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00004237 << LHS.get()->getType() << RHS.get()->getType()
4238 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004239 return QualType();
4240}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004241
4242/// \brief Find a merged pointer type and convert the two expressions to it.
4243///
Douglas Gregor20b3e992009-08-24 17:42:35 +00004244/// This finds the composite pointer type (or member pointer type) for @p E1
4245/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
4246/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004247/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004248///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004249/// \param Loc The location of the operator requiring these two expressions to
4250/// be converted to the composite pointer type.
4251///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004252/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4253/// a non-standard (but still sane) composite type to which both expressions
4254/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4255/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004256QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004257 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004258 bool *NonStandardCompositeType) {
4259 if (NonStandardCompositeType)
4260 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004261
David Blaikie4e4d0842012-03-11 07:00:24 +00004262 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004263 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004264
Fariborz Jahanian0cedfbd2009-12-08 20:04:24 +00004265 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4266 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregor20b3e992009-08-24 17:42:35 +00004267 return QualType();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004268
4269 // C++0x 5.9p2
4270 // Pointer conversions and qualification conversions are performed on
4271 // pointer operands to bring them to their composite pointer type. If
4272 // one operand is a null pointer constant, the composite pointer type is
4273 // the type of the other operand.
Douglas Gregorce940492009-09-25 04:25:58 +00004274 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004275 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00004276 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004277 else
John Wiegley429bb272011-04-08 18:41:53 +00004278 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004279 return T2;
4280 }
Douglas Gregorce940492009-09-25 04:25:58 +00004281 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004282 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00004283 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004284 else
John Wiegley429bb272011-04-08 18:41:53 +00004285 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004286 return T1;
4287 }
Mike Stump1eb44332009-09-09 15:08:12 +00004288
Douglas Gregor20b3e992009-08-24 17:42:35 +00004289 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004290 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4291 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004292 return QualType();
4293
4294 // Otherwise, of one of the operands has type "pointer to cv1 void," then
4295 // the other has type "pointer to cv2 T" and the composite pointer type is
4296 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4297 // Otherwise, the composite pointer type is a pointer type similar to the
4298 // type of one of the operands, with a cv-qualification signature that is
4299 // the union of the cv-qualification signatures of the operand types.
4300 // In practice, the first part here is redundant; it's subsumed by the second.
4301 // What we do here is, we build the two possible composite types, and try the
4302 // conversions in both directions. If only one works, or if the two composite
4303 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00004304 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00004305 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00004306 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004307 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00004308 ContainingClassVector;
4309 ContainingClassVector MemberOfClass;
4310 QualType Composite1 = Context.getCanonicalType(T1),
4311 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004312 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00004313 do {
4314 const PointerType *Ptr1, *Ptr2;
4315 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4316 (Ptr2 = Composite2->getAs<PointerType>())) {
4317 Composite1 = Ptr1->getPointeeType();
4318 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004319
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004320 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004321 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004322 if (NonStandardCompositeType &&
4323 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4324 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004325
Douglas Gregor20b3e992009-08-24 17:42:35 +00004326 QualifierUnion.push_back(
4327 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4328 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
4329 continue;
4330 }
Mike Stump1eb44332009-09-09 15:08:12 +00004331
Douglas Gregor20b3e992009-08-24 17:42:35 +00004332 const MemberPointerType *MemPtr1, *MemPtr2;
4333 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4334 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4335 Composite1 = MemPtr1->getPointeeType();
4336 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004337
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004338 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004339 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004340 if (NonStandardCompositeType &&
4341 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4342 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004343
Douglas Gregor20b3e992009-08-24 17:42:35 +00004344 QualifierUnion.push_back(
4345 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4346 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4347 MemPtr2->getClass()));
4348 continue;
4349 }
Mike Stump1eb44332009-09-09 15:08:12 +00004350
Douglas Gregor20b3e992009-08-24 17:42:35 +00004351 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00004352
Douglas Gregor20b3e992009-08-24 17:42:35 +00004353 // Cannot unwrap any more types.
4354 break;
4355 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00004356
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004357 if (NeedConstBefore && NonStandardCompositeType) {
4358 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004359 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004360 // requirements of C++ [conv.qual]p4 bullet 3.
4361 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4362 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4363 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4364 *NonStandardCompositeType = true;
4365 }
4366 }
4367 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004368
Douglas Gregor20b3e992009-08-24 17:42:35 +00004369 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004370 ContainingClassVector::reverse_iterator MOC
4371 = MemberOfClass.rbegin();
4372 for (QualifierVector::reverse_iterator
4373 I = QualifierUnion.rbegin(),
4374 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00004375 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00004376 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004377 if (MOC->first && MOC->second) {
4378 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00004379 Composite1 = Context.getMemberPointerType(
4380 Context.getQualifiedType(Composite1, Quals),
4381 MOC->first);
4382 Composite2 = Context.getMemberPointerType(
4383 Context.getQualifiedType(Composite2, Quals),
4384 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004385 } else {
4386 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00004387 Composite1
4388 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4389 Composite2
4390 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00004391 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004392 }
4393
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004394 // Try to convert to the first composite pointer type.
4395 InitializedEntity Entity1
4396 = InitializedEntity::InitializeTemporary(Composite1);
4397 InitializationKind Kind
4398 = InitializationKind::CreateCopy(Loc, SourceLocation());
4399 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4400 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump1eb44332009-09-09 15:08:12 +00004401
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004402 if (E1ToC1 && E2ToC1) {
4403 // Conversion to Composite1 is viable.
4404 if (!Context.hasSameType(Composite1, Composite2)) {
4405 // Composite2 is a different type from Composite1. Check whether
4406 // Composite2 is also viable.
4407 InitializedEntity Entity2
4408 = InitializedEntity::InitializeTemporary(Composite2);
4409 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4410 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4411 if (E1ToC2 && E2ToC2) {
4412 // Both Composite1 and Composite2 are viable and are different;
4413 // this is an ambiguity.
4414 return QualType();
4415 }
4416 }
4417
4418 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004419 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004420 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004421 if (E1Result.isInvalid())
4422 return QualType();
4423 E1 = E1Result.takeAs<Expr>();
4424
4425 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004426 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004427 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004428 if (E2Result.isInvalid())
4429 return QualType();
4430 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004431
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004432 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004433 }
4434
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004435 // Check whether Composite2 is viable.
4436 InitializedEntity Entity2
4437 = InitializedEntity::InitializeTemporary(Composite2);
4438 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4439 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4440 if (!E1ToC2 || !E2ToC2)
4441 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004442
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004443 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004444 ExprResult E1Result
John McCallca0408f2010-08-23 06:44:23 +00004445 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004446 if (E1Result.isInvalid())
4447 return QualType();
4448 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004449
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004450 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004451 ExprResult E2Result
John McCallca0408f2010-08-23 06:44:23 +00004452 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004453 if (E2Result.isInvalid())
4454 return QualType();
4455 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004456
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004457 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004458}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004459
John McCall60d7b3a2010-08-24 06:29:42 +00004460ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004461 if (!E)
4462 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004463
John McCallf85e1932011-06-15 23:02:42 +00004464 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4465
4466 // If the result is a glvalue, we shouldn't bind it.
4467 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004468 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004469
John McCallf85e1932011-06-15 23:02:42 +00004470 // In ARC, calls that return a retainable type can return retained,
4471 // in which case we have to insert a consuming cast.
David Blaikie4e4d0842012-03-11 07:00:24 +00004472 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004473 E->getType()->isObjCRetainableType()) {
4474
4475 bool ReturnsRetained;
4476
4477 // For actual calls, we compute this by examining the type of the
4478 // called value.
4479 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4480 Expr *Callee = Call->getCallee()->IgnoreParens();
4481 QualType T = Callee->getType();
4482
4483 if (T == Context.BoundMemberTy) {
4484 // Handle pointer-to-members.
4485 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4486 T = BinOp->getRHS()->getType();
4487 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4488 T = Mem->getMemberDecl()->getType();
4489 }
4490
4491 if (const PointerType *Ptr = T->getAs<PointerType>())
4492 T = Ptr->getPointeeType();
4493 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4494 T = Ptr->getPointeeType();
4495 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4496 T = MemPtr->getPointeeType();
4497
4498 const FunctionType *FTy = T->getAs<FunctionType>();
4499 assert(FTy && "call to value not of function type?");
4500 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4501
4502 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4503 // type always produce a +1 object.
4504 } else if (isa<StmtExpr>(E)) {
4505 ReturnsRetained = true;
4506
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004507 // We hit this case with the lambda conversion-to-block optimization;
4508 // we don't want any extra casts here.
4509 } else if (isa<CastExpr>(E) &&
4510 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
4511 return Owned(E);
4512
John McCallf85e1932011-06-15 23:02:42 +00004513 // For message sends and property references, we try to find an
4514 // actual method. FIXME: we should infer retention by selector in
4515 // cases where we don't have an actual method.
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004516 } else {
4517 ObjCMethodDecl *D = 0;
4518 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4519 D = Send->getMethodDecl();
Patrick Beardeb382ec2012-04-19 00:25:12 +00004520 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4521 D = BoxedExpr->getBoxingMethod();
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004522 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4523 D = ArrayLit->getArrayWithObjectsMethod();
4524 } else if (ObjCDictionaryLiteral *DictLit
4525 = dyn_cast<ObjCDictionaryLiteral>(E)) {
4526 D = DictLit->getDictWithObjectsMethod();
4527 }
John McCallf85e1932011-06-15 23:02:42 +00004528
4529 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004530
4531 // Don't do reclaims on performSelector calls; despite their
4532 // return type, the invoked method doesn't necessarily actually
4533 // return an object.
4534 if (!ReturnsRetained &&
4535 D && D->getMethodFamily() == OMF_performSelector)
4536 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004537 }
4538
John McCall567c5862011-11-14 19:53:16 +00004539 // Don't reclaim an object of Class type.
4540 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4541 return Owned(E);
4542
John McCall7e5e5f42011-07-07 06:58:02 +00004543 ExprNeedsCleanups = true;
4544
John McCall33e56f32011-09-10 06:18:15 +00004545 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4546 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004547 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4548 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004549 }
4550
David Blaikie4e4d0842012-03-11 07:00:24 +00004551 if (!getLangOpts().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00004552 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004553
Peter Collingbourneb4ab8432012-01-26 03:33:51 +00004554 // Search for the base element type (cf. ASTContext::getBaseElementType) with
4555 // a fast path for the common case that the type is directly a RecordType.
4556 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4557 const RecordType *RT = 0;
4558 while (!RT) {
4559 switch (T->getTypeClass()) {
4560 case Type::Record:
4561 RT = cast<RecordType>(T);
4562 break;
4563 case Type::ConstantArray:
4564 case Type::IncompleteArray:
4565 case Type::VariableArray:
4566 case Type::DependentSizedArray:
4567 T = cast<ArrayType>(T)->getElementType().getTypePtr();
4568 break;
4569 default:
4570 return Owned(E);
4571 }
4572 }
Mike Stump1eb44332009-09-09 15:08:12 +00004573
Richard Smith76f3f692012-02-22 02:04:18 +00004574 // That should be enough to guarantee that this type is complete, if we're
4575 // not processing a decltype expression.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004576 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith213d70b2012-02-18 04:13:32 +00004577 if (RD->isInvalidDecl() || RD->isDependentContext())
John McCall86ff3082010-02-04 22:26:26 +00004578 return Owned(E);
Richard Smith76f3f692012-02-22 02:04:18 +00004579
4580 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
4581 CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD);
John McCallf85e1932011-06-15 23:02:42 +00004582
John McCallf85e1932011-06-15 23:02:42 +00004583 if (Destructor) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00004584 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004585 CheckDestructorAccess(E->getExprLoc(), Destructor,
4586 PDiag(diag::err_access_dtor_temp)
4587 << E->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00004588 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00004589
Richard Smith76f3f692012-02-22 02:04:18 +00004590 // If destructor is trivial, we can avoid the extra copy.
4591 if (Destructor->isTrivial())
4592 return Owned(E);
Richard Smith213d70b2012-02-18 04:13:32 +00004593
John McCall80ee6e82011-11-10 05:35:25 +00004594 // We need a cleanup, but we don't need to remember the temporary.
John McCallf85e1932011-06-15 23:02:42 +00004595 ExprNeedsCleanups = true;
Richard Smith76f3f692012-02-22 02:04:18 +00004596 }
Richard Smith213d70b2012-02-18 04:13:32 +00004597
4598 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smith76f3f692012-02-22 02:04:18 +00004599 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
4600
4601 if (IsDecltype)
4602 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
4603
4604 return Owned(Bind);
Anders Carlssondef11992009-05-30 20:36:53 +00004605}
4606
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004607ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004608Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004609 if (SubExpr.isInvalid())
4610 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004611
John McCall4765fa02010-12-06 08:20:24 +00004612 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004613}
4614
John McCall80ee6e82011-11-10 05:35:25 +00004615Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4616 assert(SubExpr && "sub expression can't be null!");
4617
Eli Friedmand2cce132012-02-02 23:15:15 +00004618 CleanupVarDeclMarking();
4619
John McCall80ee6e82011-11-10 05:35:25 +00004620 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4621 assert(ExprCleanupObjects.size() >= FirstCleanup);
4622 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4623 if (!ExprNeedsCleanups)
4624 return SubExpr;
4625
4626 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4627 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4628 ExprCleanupObjects.size() - FirstCleanup);
4629
4630 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4631 DiscardCleanupsInEvaluationContext();
4632
4633 return E;
4634}
4635
John McCall4765fa02010-12-06 08:20:24 +00004636Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004637 assert(SubStmt && "sub statement can't be null!");
4638
Eli Friedmand2cce132012-02-02 23:15:15 +00004639 CleanupVarDeclMarking();
4640
John McCallf85e1932011-06-15 23:02:42 +00004641 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004642 return SubStmt;
4643
4644 // FIXME: In order to attach the temporaries, wrap the statement into
4645 // a StmtExpr; currently this is only used for asm statements.
4646 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4647 // a new AsmStmtWithTemporaries.
4648 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4649 SourceLocation(),
4650 SourceLocation());
4651 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4652 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004653 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004654}
4655
Richard Smith76f3f692012-02-22 02:04:18 +00004656/// Process the expression contained within a decltype. For such expressions,
4657/// certain semantic checks on temporaries are delayed until this point, and
4658/// are omitted for the 'topmost' call in the decltype expression. If the
4659/// topmost call bound a temporary, strip that temporary off the expression.
4660ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
4661 ExpressionEvaluationContextRecord &Rec = ExprEvalContexts.back();
4662 assert(Rec.IsDecltype && "not in a decltype expression");
4663
4664 // C++11 [expr.call]p11:
4665 // If a function call is a prvalue of object type,
4666 // -- if the function call is either
4667 // -- the operand of a decltype-specifier, or
4668 // -- the right operand of a comma operator that is the operand of a
4669 // decltype-specifier,
4670 // a temporary object is not introduced for the prvalue.
4671
4672 // Recursively rebuild ParenExprs and comma expressions to strip out the
4673 // outermost CXXBindTemporaryExpr, if any.
4674 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4675 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
4676 if (SubExpr.isInvalid())
4677 return ExprError();
4678 if (SubExpr.get() == PE->getSubExpr())
4679 return Owned(E);
4680 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take());
4681 }
4682 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4683 if (BO->getOpcode() == BO_Comma) {
4684 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
4685 if (RHS.isInvalid())
4686 return ExprError();
4687 if (RHS.get() == BO->getRHS())
4688 return Owned(E);
4689 return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(),
4690 BO_Comma, BO->getType(),
4691 BO->getValueKind(),
4692 BO->getObjectKind(),
4693 BO->getOperatorLoc()));
4694 }
4695 }
4696
4697 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
4698 if (TopBind)
4699 E = TopBind->getSubExpr();
4700
4701 // Disable the special decltype handling now.
4702 Rec.IsDecltype = false;
4703
4704 // Perform the semantic checks we delayed until this point.
4705 CallExpr *TopCall = dyn_cast<CallExpr>(E);
4706 for (unsigned I = 0, N = Rec.DelayedDecltypeCalls.size(); I != N; ++I) {
4707 CallExpr *Call = Rec.DelayedDecltypeCalls[I];
4708 if (Call == TopCall)
4709 continue;
4710
4711 if (CheckCallReturnType(Call->getCallReturnType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00004712 Call->getLocStart(),
Richard Smith76f3f692012-02-22 02:04:18 +00004713 Call, Call->getDirectCallee()))
4714 return ExprError();
4715 }
4716
4717 // Now all relevant types are complete, check the destructors are accessible
4718 // and non-deleted, and annotate them on the temporaries.
4719 for (unsigned I = 0, N = Rec.DelayedDecltypeBinds.size(); I != N; ++I) {
4720 CXXBindTemporaryExpr *Bind = Rec.DelayedDecltypeBinds[I];
4721 if (Bind == TopBind)
4722 continue;
4723
4724 CXXTemporary *Temp = Bind->getTemporary();
4725
4726 CXXRecordDecl *RD =
4727 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
4728 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4729 Temp->setDestructor(Destructor);
4730
4731 MarkFunctionReferenced(E->getExprLoc(), Destructor);
4732 CheckDestructorAccess(E->getExprLoc(), Destructor,
4733 PDiag(diag::err_access_dtor_temp)
4734 << E->getType());
4735 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
4736
4737 // We need a cleanup, but we don't need to remember the temporary.
4738 ExprNeedsCleanups = true;
4739 }
4740
4741 // Possibly strip off the top CXXBindTemporaryExpr.
4742 return Owned(E);
4743}
4744
John McCall60d7b3a2010-08-24 06:29:42 +00004745ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004746Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00004747 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00004748 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004749 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00004750 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00004751 if (Result.isInvalid()) return ExprError();
4752 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00004753
John McCall3c3b7f92011-10-25 17:37:35 +00004754 Result = CheckPlaceholderExpr(Base);
4755 if (Result.isInvalid()) return ExprError();
4756 Base = Result.take();
4757
John McCall9ae2f072010-08-23 23:25:46 +00004758 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004759 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004760 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00004761 // If we have a pointer to a dependent type and are using the -> operator,
4762 // the object type is the type that the pointer points to. We might still
4763 // have enough information about that type to do something useful.
4764 if (OpKind == tok::arrow)
4765 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4766 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004767
John McCallb3d87482010-08-24 05:47:05 +00004768 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00004769 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004770 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004771 }
Mike Stump1eb44332009-09-09 15:08:12 +00004772
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004773 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00004774 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004775 // returned, with the original second operand.
4776 if (OpKind == tok::arrow) {
John McCallc4e83212009-09-30 01:01:30 +00004777 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00004778 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004779 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00004780 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004781
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004782 while (BaseType->isRecordType()) {
John McCall9ae2f072010-08-23 23:25:46 +00004783 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4784 if (Result.isInvalid())
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004785 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00004786 Base = Result.get();
4787 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00004788 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00004789 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00004790 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00004791 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004792 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00004793 for (unsigned i = 0; i < Locations.size(); i++)
4794 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00004795 return ExprError();
4796 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004797 }
Mike Stump1eb44332009-09-09 15:08:12 +00004798
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004799 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
Douglas Gregor31658df2009-11-20 19:58:21 +00004800 BaseType = BaseType->getPointeeType();
4801 }
Mike Stump1eb44332009-09-09 15:08:12 +00004802
Douglas Gregor1d7049a2012-01-12 16:11:24 +00004803 // Objective-C properties allow "." access on Objective-C pointer types,
4804 // so adjust the base type to the object type itself.
4805 if (BaseType->isObjCObjectPointerType())
4806 BaseType = BaseType->getPointeeType();
4807
4808 // C++ [basic.lookup.classref]p2:
4809 // [...] If the type of the object expression is of pointer to scalar
4810 // type, the unqualified-id is looked up in the context of the complete
4811 // postfix-expression.
4812 //
4813 // This also indicates that we could be parsing a pseudo-destructor-name.
4814 // Note that Objective-C class and object types can be pseudo-destructor
4815 // expressions or normal member (ivar or property) access expressions.
4816 if (BaseType->isObjCObjectOrInterfaceType()) {
4817 MayBePseudoDestructor = true;
4818 } else if (!BaseType->isRecordType()) {
John McCallb3d87482010-08-24 05:47:05 +00004819 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00004820 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00004821 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00004822 }
Mike Stump1eb44332009-09-09 15:08:12 +00004823
Douglas Gregorcefc3af2012-04-16 07:05:22 +00004824 // The object type must be complete (or dependent), or
4825 // C++11 [expr.prim.general]p3:
4826 // Unlike the object expression in other contexts, *this is not required to
4827 // be of complete type for purposes of class member access (5.2.5) outside
4828 // the member function body.
Douglas Gregor03c57052009-11-17 05:17:33 +00004829 if (!BaseType->isDependentType() &&
Douglas Gregorcefc3af2012-04-16 07:05:22 +00004830 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00004831 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor03c57052009-11-17 05:17:33 +00004832 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004833
Douglas Gregorc68afe22009-09-03 21:38:09 +00004834 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004835 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00004836 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00004837 // type C (or of pointer to a class type C), the unqualified-id is looked
4838 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00004839 ObjectType = ParsedType::make(BaseType);
Mike Stump1eb44332009-09-09 15:08:12 +00004840 return move(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00004841}
4842
John McCall60d7b3a2010-08-24 06:29:42 +00004843ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00004844 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00004845 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00004846 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4847 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00004848 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004849
Douglas Gregor77549082010-02-24 21:29:12 +00004850 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00004851 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00004852 /*LPLoc*/ ExpectedLParenLoc,
John McCallf312b1e2010-08-26 23:41:50 +00004853 MultiExprArg(),
Douglas Gregor77549082010-02-24 21:29:12 +00004854 /*RPLoc*/ ExpectedLParenLoc);
4855}
Douglas Gregord4dca082010-02-24 18:44:31 +00004856
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004857static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie91ec7892011-12-16 16:03:09 +00004858 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004859 if (Base->hasPlaceholderType()) {
4860 ExprResult result = S.CheckPlaceholderExpr(Base);
4861 if (result.isInvalid()) return true;
4862 Base = result.take();
4863 }
4864 ObjectType = Base->getType();
4865
David Blaikie91ec7892011-12-16 16:03:09 +00004866 // C++ [expr.pseudo]p2:
4867 // The left-hand side of the dot operator shall be of scalar type. The
4868 // left-hand side of the arrow operator shall be of pointer to scalar type.
4869 // This scalar type is the object type.
Eli Friedmane0dbedf2012-01-25 04:29:24 +00004870 // Note that this is rather different from the normal handling for the
4871 // arrow operator.
David Blaikie91ec7892011-12-16 16:03:09 +00004872 if (OpKind == tok::arrow) {
4873 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4874 ObjectType = Ptr->getPointeeType();
4875 } else if (!Base->isTypeDependent()) {
4876 // The user wrote "p->" when she probably meant "p."; fix it.
4877 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4878 << ObjectType << true
4879 << FixItHint::CreateReplacement(OpLoc, ".");
4880 if (S.isSFINAEContext())
4881 return true;
4882
4883 OpKind = tok::period;
4884 }
4885 }
4886
4887 return false;
4888}
4889
John McCall60d7b3a2010-08-24 06:29:42 +00004890ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004891 SourceLocation OpLoc,
4892 tok::TokenKind OpKind,
4893 const CXXScopeSpec &SS,
4894 TypeSourceInfo *ScopeTypeInfo,
4895 SourceLocation CCLoc,
4896 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004897 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00004898 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004899 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004900
Eli Friedman8c9fe202012-01-25 04:35:06 +00004901 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00004902 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4903 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004904
Douglas Gregorb57fb492010-02-24 22:38:50 +00004905 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004906 if (getLangOpts().MicrosoftMode && ObjectType->isVoidType())
Nico Weber2d757ec2012-01-23 06:08:16 +00004907 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Nico Weberdf1be862012-01-23 05:50:57 +00004908 else
4909 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4910 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00004911 return ExprError();
4912 }
4913
4914 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004915 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00004916 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004917 if (DestructedTypeInfo) {
4918 QualType DestructedType = DestructedTypeInfo->getType();
4919 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004920 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00004921 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4922 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4923 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4924 << ObjectType << DestructedType << Base->getSourceRange()
4925 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004926
John McCallf85e1932011-06-15 23:02:42 +00004927 // Recover by setting the destructed type to the object type.
4928 DestructedType = ObjectType;
4929 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004930 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00004931 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4932 } else if (DestructedType.getObjCLifetime() !=
4933 ObjectType.getObjCLifetime()) {
4934
4935 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4936 // Okay: just pretend that the user provided the correctly-qualified
4937 // type.
4938 } else {
4939 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4940 << ObjectType << DestructedType << Base->getSourceRange()
4941 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4942 }
4943
4944 // Recover by setting the destructed type to the object type.
4945 DestructedType = ObjectType;
4946 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4947 DestructedTypeStart);
4948 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4949 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00004950 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00004951 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004952
Douglas Gregorb57fb492010-02-24 22:38:50 +00004953 // C++ [expr.pseudo]p2:
4954 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4955 // form
4956 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004957 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00004958 //
4959 // shall designate the same scalar type.
4960 if (ScopeTypeInfo) {
4961 QualType ScopeType = ScopeTypeInfo->getType();
4962 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00004963 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004964
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004965 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00004966 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00004967 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004968 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004969
Douglas Gregorb57fb492010-02-24 22:38:50 +00004970 ScopeType = QualType();
4971 ScopeTypeInfo = 0;
4972 }
4973 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004974
John McCall9ae2f072010-08-23 23:25:46 +00004975 Expr *Result
4976 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4977 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00004978 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00004979 ScopeTypeInfo,
4980 CCLoc,
4981 TildeLoc,
4982 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004983
Douglas Gregorb57fb492010-02-24 22:38:50 +00004984 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00004985 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004986
John McCall9ae2f072010-08-23 23:25:46 +00004987 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00004988}
4989
John McCall60d7b3a2010-08-24 06:29:42 +00004990ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00004991 SourceLocation OpLoc,
4992 tok::TokenKind OpKind,
4993 CXXScopeSpec &SS,
4994 UnqualifiedId &FirstTypeName,
4995 SourceLocation CCLoc,
4996 SourceLocation TildeLoc,
4997 UnqualifiedId &SecondTypeName,
4998 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00004999 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5000 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5001 "Invalid first type name in pseudo-destructor");
5002 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5003 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5004 "Invalid second type name in pseudo-destructor");
5005
Eli Friedman8c9fe202012-01-25 04:35:06 +00005006 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00005007 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5008 return ExprError();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005009
5010 // Compute the object type that we should use for name lookup purposes. Only
5011 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00005012 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005013 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00005014 if (ObjectType->isRecordType())
5015 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00005016 else if (ObjectType->isDependentType())
5017 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005018 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005019
5020 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00005021 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00005022 QualType DestructedType;
5023 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005024 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00005025 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005026 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00005027 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00005028 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005029 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005030 ((SS.isSet() && !computeDeclContext(SS, false)) ||
5031 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005032 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005033 // couldn't find anything useful in scope. Just store the identifier and
5034 // it's location, and we'll perform (qualified) name lookup again at
5035 // template instantiation time.
5036 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5037 SecondTypeName.StartLocation);
5038 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005039 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00005040 diag::err_pseudo_dtor_destructor_non_type)
5041 << SecondTypeName.Identifier << ObjectType;
5042 if (isSFINAEContext())
5043 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005044
Douglas Gregor77549082010-02-24 21:29:12 +00005045 // Recover by assuming we had the right type all along.
5046 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00005047 } else
Douglas Gregor77549082010-02-24 21:29:12 +00005048 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005049 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00005050 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00005051 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00005052 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5053 TemplateId->getTemplateArgs(),
5054 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00005055 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005056 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00005057 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00005058 TemplateId->TemplateNameLoc,
5059 TemplateId->LAngleLoc,
5060 TemplateArgsPtr,
5061 TemplateId->RAngleLoc);
5062 if (T.isInvalid() || !T.get()) {
5063 // Recover by assuming we had the right type all along.
5064 DestructedType = ObjectType;
5065 } else
5066 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005067 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005068
5069 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00005070 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005071 if (!DestructedType.isNull()) {
5072 if (!DestructedTypeInfo)
5073 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00005074 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005075 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5076 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005077
Douglas Gregorb57fb492010-02-24 22:38:50 +00005078 // Convert the name of the scope type (the type prior to '::') into a type.
5079 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00005080 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005081 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00005082 FirstTypeName.Identifier) {
5083 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005084 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00005085 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00005086 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00005087 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005088 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00005089 diag::err_pseudo_dtor_destructor_non_type)
5090 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005091
Douglas Gregorb57fb492010-02-24 22:38:50 +00005092 if (isSFINAEContext())
5093 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005094
Douglas Gregorb57fb492010-02-24 22:38:50 +00005095 // Just drop this type. It's unnecessary anyway.
5096 ScopeType = QualType();
5097 } else
5098 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005099 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00005100 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00005101 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb57fb492010-02-24 22:38:50 +00005102 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5103 TemplateId->getTemplateArgs(),
5104 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00005105 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005106 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00005107 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00005108 TemplateId->TemplateNameLoc,
5109 TemplateId->LAngleLoc,
5110 TemplateArgsPtr,
5111 TemplateId->RAngleLoc);
5112 if (T.isInvalid() || !T.get()) {
5113 // Recover by dropping this type.
5114 ScopeType = QualType();
5115 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005116 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005117 }
5118 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005119
Douglas Gregorb4a418f2010-02-24 23:02:30 +00005120 if (!ScopeType.isNull() && !ScopeTypeInfo)
5121 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5122 FirstTypeName.StartLocation);
5123
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005124
John McCall9ae2f072010-08-23 23:25:46 +00005125 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00005126 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005127 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00005128}
5129
David Blaikie91ec7892011-12-16 16:03:09 +00005130ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5131 SourceLocation OpLoc,
5132 tok::TokenKind OpKind,
5133 SourceLocation TildeLoc,
5134 const DeclSpec& DS,
5135 bool HasTrailingLParen) {
Eli Friedman8c9fe202012-01-25 04:35:06 +00005136 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00005137 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5138 return ExprError();
5139
5140 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5141
5142 TypeLocBuilder TLB;
5143 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5144 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5145 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5146 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5147
5148 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5149 0, SourceLocation(), TildeLoc,
5150 Destructed, HasTrailingLParen);
5151}
5152
John Wiegley429bb272011-04-08 18:41:53 +00005153ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman3f01c8a2012-03-01 01:30:04 +00005154 CXXConversionDecl *Method,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005155 bool HadMultipleCandidates) {
Eli Friedman23f02672012-03-01 04:01:32 +00005156 if (Method->getParent()->isLambda() &&
5157 Method->getConversionType()->isBlockPointerType()) {
5158 // This is a lambda coversion to block pointer; check if the argument
5159 // is a LambdaExpr.
5160 Expr *SubE = E;
5161 CastExpr *CE = dyn_cast<CastExpr>(SubE);
5162 if (CE && CE->getCastKind() == CK_NoOp)
5163 SubE = CE->getSubExpr();
5164 SubE = SubE->IgnoreParens();
5165 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5166 SubE = BE->getSubExpr();
5167 if (isa<LambdaExpr>(SubE)) {
5168 // For the conversion to block pointer on a lambda expression, we
5169 // construct a special BlockLiteral instead; this doesn't really make
5170 // a difference in ARC, but outside of ARC the resulting block literal
5171 // follows the normal lifetime rules for block literals instead of being
5172 // autoreleased.
5173 DiagnosticErrorTrap Trap(Diags);
5174 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5175 E->getExprLoc(),
5176 Method, E);
5177 if (Exp.isInvalid())
5178 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5179 return Exp;
5180 }
5181 }
5182
5183
John Wiegley429bb272011-04-08 18:41:53 +00005184 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
5185 FoundDecl, Method);
5186 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005187 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00005188
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005189 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00005190 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnara960809e2011-11-16 22:46:05 +00005191 SourceLocation(), Context.BoundMemberTy,
John McCallf89e55a2010-11-18 06:31:45 +00005192 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005193 if (HadMultipleCandidates)
5194 ME->setHadMultipleCandidates(true);
5195
John McCallf89e55a2010-11-18 06:31:45 +00005196 QualType ResultType = Method->getResultType();
5197 ExprValueKind VK = Expr::getValueKindForType(ResultType);
5198 ResultType = ResultType.getNonLValueExprType(Context);
5199
Eli Friedman5f2987c2012-02-02 03:46:19 +00005200 MarkFunctionReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005201 CXXMemberCallExpr *CE =
John McCallf89e55a2010-11-18 06:31:45 +00005202 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00005203 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005204 return CE;
5205}
5206
Sebastian Redl2e156222010-09-10 20:55:43 +00005207ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5208 SourceLocation RParen) {
Richard Smithe6975e92012-04-17 00:58:00 +00005209 CanThrowResult CanThrow = canThrow(Operand);
Sebastian Redl2e156222010-09-10 20:55:43 +00005210 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
Richard Smithe6975e92012-04-17 00:58:00 +00005211 CanThrow, KeyLoc, RParen));
Sebastian Redl2e156222010-09-10 20:55:43 +00005212}
5213
5214ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5215 Expr *Operand, SourceLocation RParen) {
5216 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00005217}
5218
John McCallf6a16482010-12-04 03:47:34 +00005219/// Perform the conversions required for an expression used in a
5220/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00005221ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall3c3b7f92011-10-25 17:37:35 +00005222 if (E->hasPlaceholderType()) {
5223 ExprResult result = CheckPlaceholderExpr(E);
5224 if (result.isInvalid()) return Owned(E);
5225 E = result.take();
5226 }
5227
John McCalla878cda2010-12-02 02:07:15 +00005228 // C99 6.3.2.1:
5229 // [Except in specific positions,] an lvalue that does not have
5230 // array type is converted to the value stored in the
5231 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00005232 if (E->isRValue()) {
5233 // In C, function designators (i.e. expressions of function type)
5234 // are r-values, but we still want to do function-to-pointer decay
5235 // on them. This is both technically correct and convenient for
5236 // some clients.
David Blaikie4e4d0842012-03-11 07:00:24 +00005237 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalle6d134b2011-06-27 21:24:11 +00005238 return DefaultFunctionArrayConversion(E);
5239
5240 return Owned(E);
5241 }
John McCalla878cda2010-12-02 02:07:15 +00005242
John McCallf6a16482010-12-04 03:47:34 +00005243 // Otherwise, this rule does not apply in C++, at least not for the moment.
David Blaikie4e4d0842012-03-11 07:00:24 +00005244 if (getLangOpts().CPlusPlus) return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00005245
5246 // GCC seems to also exclude expressions of incomplete enum type.
5247 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5248 if (!T->getDecl()->isComplete()) {
5249 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00005250 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
5251 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00005252 }
5253 }
5254
John Wiegley429bb272011-04-08 18:41:53 +00005255 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5256 if (Res.isInvalid())
5257 return Owned(E);
5258 E = Res.take();
5259
John McCall85515d62010-12-04 12:29:11 +00005260 if (!E->getType()->isVoidType())
5261 RequireCompleteType(E->getExprLoc(), E->getType(),
5262 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00005263 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00005264}
5265
John Wiegley429bb272011-04-08 18:41:53 +00005266ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
5267 ExprResult FullExpr = Owned(FE);
5268
5269 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00005270 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00005271
John Wiegley429bb272011-04-08 18:41:53 +00005272 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00005273 return ExprError();
5274
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00005275 // Top-level message sends default to 'id' when we're in a debugger.
David Blaikie4e4d0842012-03-11 07:00:24 +00005276 if (getLangOpts().DebuggerCastResultToId &&
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00005277 FullExpr.get()->getType() == Context.UnknownAnyTy &&
5278 isa<ObjCMessageExpr>(FullExpr.get())) {
5279 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
5280 if (FullExpr.isInvalid())
5281 return ExprError();
5282 }
5283
John McCallfb8721c2011-04-10 19:13:55 +00005284 FullExpr = CheckPlaceholderExpr(FullExpr.take());
5285 if (FullExpr.isInvalid())
5286 return ExprError();
Douglas Gregor353ee242011-03-07 02:05:23 +00005287
John Wiegley429bb272011-04-08 18:41:53 +00005288 FullExpr = IgnoredValueConversions(FullExpr.take());
5289 if (FullExpr.isInvalid())
5290 return ExprError();
5291
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005292 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall4765fa02010-12-06 08:20:24 +00005293 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00005294}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00005295
5296StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
5297 if (!FullStmt) return StmtError();
5298
John McCall4765fa02010-12-06 08:20:24 +00005299 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00005300}
Francois Pichet1e862692011-05-06 20:48:22 +00005301
Douglas Gregorba0513d2011-10-25 01:33:02 +00005302Sema::IfExistsResult
5303Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
5304 CXXScopeSpec &SS,
5305 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet1e862692011-05-06 20:48:22 +00005306 DeclarationName TargetName = TargetNameInfo.getName();
5307 if (!TargetName)
Douglas Gregor3896fc52011-10-24 22:31:10 +00005308 return IER_DoesNotExist;
Douglas Gregorba0513d2011-10-25 01:33:02 +00005309
Douglas Gregor3896fc52011-10-24 22:31:10 +00005310 // If the name itself is dependent, then the result is dependent.
5311 if (TargetName.isDependentName())
5312 return IER_Dependent;
Douglas Gregorba0513d2011-10-25 01:33:02 +00005313
Francois Pichet1e862692011-05-06 20:48:22 +00005314 // Do the redeclaration lookup in the current scope.
5315 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
5316 Sema::NotForRedeclaration);
Douglas Gregor3896fc52011-10-24 22:31:10 +00005317 LookupParsedName(R, S, &SS);
Francois Pichet1e862692011-05-06 20:48:22 +00005318 R.suppressDiagnostics();
Douglas Gregor3896fc52011-10-24 22:31:10 +00005319
5320 switch (R.getResultKind()) {
5321 case LookupResult::Found:
5322 case LookupResult::FoundOverloaded:
5323 case LookupResult::FoundUnresolvedValue:
5324 case LookupResult::Ambiguous:
5325 return IER_Exists;
5326
5327 case LookupResult::NotFound:
5328 return IER_DoesNotExist;
5329
5330 case LookupResult::NotFoundInCurrentInstantiation:
5331 return IER_Dependent;
5332 }
David Blaikie7530c032012-01-17 06:56:22 +00005333
5334 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet1e862692011-05-06 20:48:22 +00005335}
Douglas Gregorba0513d2011-10-25 01:33:02 +00005336
Douglas Gregor65019ac2011-10-25 03:44:56 +00005337Sema::IfExistsResult
5338Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5339 bool IsIfExists, CXXScopeSpec &SS,
5340 UnqualifiedId &Name) {
Douglas Gregorba0513d2011-10-25 01:33:02 +00005341 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor65019ac2011-10-25 03:44:56 +00005342
5343 // Check for unexpanded parameter packs.
5344 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5345 collectUnexpandedParameterPacks(SS, Unexpanded);
5346 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
5347 if (!Unexpanded.empty()) {
5348 DiagnoseUnexpandedParameterPacks(KeywordLoc,
5349 IsIfExists? UPPC_IfExists
5350 : UPPC_IfNotExists,
5351 Unexpanded);
5352 return IER_Error;
5353 }
5354
Douglas Gregorba0513d2011-10-25 01:33:02 +00005355 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
5356}