blob: e6dd5fb1af4106aa68834a2bc40595384c0450d5 [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//===----------------------------------------------------------------------===//
James Dennett306f1792012-06-22 05:14:59 +00009///
10/// \file
11/// \brief Implements semantic analysis for C++ expressions.
12///
13//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +000014
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "TypeLocBuilder.h"
Steve Naroff210679c2007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Richard Smith6c3af3d2013-01-17 01:17:56 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000022#include "clang/AST/ExprCXX.h"
Fariborz Jahaniand4266622010-06-16 18:56:04 +000023#include "clang/AST/ExprObjC.h"
Douglas Gregorb57fb492010-02-24 22:38:50 +000024#include "clang/AST/TypeLoc.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000025#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlb5a57a62008-12-03 20:26:15 +000026#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000027#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/Initialization.h"
30#include "clang/Sema/Lookup.h"
31#include "clang/Sema/ParsedTemplate.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlbd45d252012-02-16 12:59:47 +000035#include "llvm/ADT/APInt.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000036#include "llvm/ADT/STLExtras.h"
Chandler Carruth73e0a912011-05-01 07:23:17 +000037#include "llvm/Support/ErrorHandling.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000038using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000039using namespace sema;
Reid Spencer5f016e22007-07-11 17:01:13 +000040
Richard Smith2db075b2013-03-26 01:15:19 +000041/// \brief Handle the result of the special case name lookup for inheriting
42/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
43/// constructor names in member using declarations, even if 'X' is not the
44/// name of the corresponding type.
45ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
46 SourceLocation NameLoc,
47 IdentifierInfo &Name) {
48 NestedNameSpecifier *NNS = SS.getScopeRep();
49
50 // Convert the nested-name-specifier into a type.
51 QualType Type;
52 switch (NNS->getKind()) {
53 case NestedNameSpecifier::TypeSpec:
54 case NestedNameSpecifier::TypeSpecWithTemplate:
55 Type = QualType(NNS->getAsType(), 0);
56 break;
57
58 case NestedNameSpecifier::Identifier:
59 // Strip off the last layer of the nested-name-specifier and build a
60 // typename type for it.
61 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
62 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
63 NNS->getAsIdentifier());
64 break;
65
66 case NestedNameSpecifier::Global:
67 case NestedNameSpecifier::Namespace:
68 case NestedNameSpecifier::NamespaceAlias:
69 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
70 }
71
72 // This reference to the type is located entirely at the location of the
73 // final identifier in the qualified-id.
74 return CreateParsedType(Type,
75 Context.getTrivialTypeSourceInfo(Type, NameLoc));
76}
77
John McCallb3d87482010-08-24 05:47:05 +000078ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000079 IdentifierInfo &II,
John McCallb3d87482010-08-24 05:47:05 +000080 SourceLocation NameLoc,
81 Scope *S, CXXScopeSpec &SS,
82 ParsedType ObjectTypePtr,
83 bool EnteringContext) {
Douglas Gregor124b8782010-02-16 19:09:40 +000084 // Determine where to perform name lookup.
85
86 // FIXME: This area of the standard is very messy, and the current
87 // wording is rather unclear about which scopes we search for the
88 // destructor name; see core issues 399 and 555. Issue 399 in
89 // particular shows where the current description of destructor name
90 // lookup is completely out of line with existing practice, e.g.,
91 // this appears to be ill-formed:
92 //
93 // namespace N {
94 // template <typename T> struct S {
95 // ~S();
96 // };
97 // }
98 //
99 // void f(N::S<int>* s) {
100 // s->N::S<int>::~S();
101 // }
102 //
Douglas Gregor93649fd2010-02-23 00:15:22 +0000103 // See also PR6358 and PR6359.
Sebastian Redlc0fee502010-07-07 23:17:38 +0000104 // For this reason, we're currently only doing the C++03 version of this
105 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregor124b8782010-02-16 19:09:40 +0000106 QualType SearchType;
107 DeclContext *LookupCtx = 0;
108 bool isDependent = false;
109 bool LookInScope = false;
110
111 // If we have an object type, it's because we are in a
112 // pseudo-destructor-expression or a member access expression, and
113 // we know what type we're looking for.
114 if (ObjectTypePtr)
115 SearchType = GetTypeFromParser(ObjectTypePtr);
116
117 if (SS.isSet()) {
Douglas Gregor93649fd2010-02-23 00:15:22 +0000118 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000119
Douglas Gregor93649fd2010-02-23 00:15:22 +0000120 bool AlreadySearched = false;
121 bool LookAtPrefix = true;
Sebastian Redlc0fee502010-07-07 23:17:38 +0000122 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000123 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redlc0fee502010-07-07 23:17:38 +0000124 // the type-names are looked up as types in the scope designated by the
125 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi00995302011-01-27 07:09:49 +0000126 //
127 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redlc0fee502010-07-07 23:17:38 +0000128 //
129 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth5e895a82010-02-21 10:19:54 +0000130 // a qualified-id of the form:
Douglas Gregor124b8782010-02-16 19:09:40 +0000131 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +0000132 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregor124b8782010-02-16 19:09:40 +0000133 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000134 // the class-names are looked up as types in the scope designated by
Sebastian Redlc0fee502010-07-07 23:17:38 +0000135 // the nested-name-specifier.
Douglas Gregor124b8782010-02-16 19:09:40 +0000136 //
Sebastian Redlc0fee502010-07-07 23:17:38 +0000137 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000138 // code below is permitted to look at the prefix of the
Sebastian Redlc0fee502010-07-07 23:17:38 +0000139 // nested-name-specifier.
140 DeclContext *DC = computeDeclContext(SS, EnteringContext);
141 if (DC && DC->isFileContext()) {
142 AlreadySearched = true;
143 LookupCtx = DC;
144 isDependent = false;
145 } else if (DC && isa<CXXRecordDecl>(DC))
146 LookAtPrefix = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000147
Sebastian Redlc0fee502010-07-07 23:17:38 +0000148 // The second case from the C++03 rules quoted further above.
Douglas Gregor93649fd2010-02-23 00:15:22 +0000149 NestedNameSpecifier *Prefix = 0;
150 if (AlreadySearched) {
151 // Nothing left to do.
152 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
153 CXXScopeSpec PrefixSS;
Douglas Gregor7e384942011-02-25 16:07:42 +0000154 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor93649fd2010-02-23 00:15:22 +0000155 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
156 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000157 } else if (ObjectTypePtr) {
Douglas Gregor124b8782010-02-16 19:09:40 +0000158 LookupCtx = computeDeclContext(SearchType);
159 isDependent = SearchType->isDependentType();
160 } else {
161 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor93649fd2010-02-23 00:15:22 +0000162 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregor124b8782010-02-16 19:09:40 +0000163 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000164
Douglas Gregoredc90502010-02-25 04:46:04 +0000165 LookInScope = false;
Douglas Gregor124b8782010-02-16 19:09:40 +0000166 } else if (ObjectTypePtr) {
167 // C++ [basic.lookup.classref]p3:
168 // If the unqualified-id is ~type-name, the type-name is looked up
169 // in the context of the entire postfix-expression. If the type T
170 // of the object expression is of a class type C, the type-name is
171 // also looked up in the scope of class C. At least one of the
172 // lookups shall find a name that refers to (possibly
173 // cv-qualified) T.
174 LookupCtx = computeDeclContext(SearchType);
175 isDependent = SearchType->isDependentType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000176 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregor124b8782010-02-16 19:09:40 +0000177 "Caller should have completed object type");
178
179 LookInScope = true;
180 } else {
181 // Perform lookup into the current scope (only).
182 LookInScope = true;
183 }
184
Douglas Gregor7ec18732011-03-04 22:32:08 +0000185 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregor124b8782010-02-16 19:09:40 +0000186 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
187 for (unsigned Step = 0; Step != 2; ++Step) {
188 // Look for the name first in the computed lookup context (if we
Douglas Gregor7ec18732011-03-04 22:32:08 +0000189 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregor124b8782010-02-16 19:09:40 +0000190 // we're allowed to look there).
191 Found.clear();
192 if (Step == 0 && LookupCtx)
193 LookupQualifiedName(Found, LookupCtx);
Douglas Gregora2e7dd22010-02-25 01:56:36 +0000194 else if (Step == 1 && LookInScope && S)
Douglas Gregor124b8782010-02-16 19:09:40 +0000195 LookupName(Found, S);
196 else
197 continue;
198
199 // FIXME: Should we be suppressing ambiguities here?
200 if (Found.isAmbiguous())
John McCallb3d87482010-08-24 05:47:05 +0000201 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000202
203 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
204 QualType T = Context.getTypeDeclType(Type);
Douglas Gregor124b8782010-02-16 19:09:40 +0000205
206 if (SearchType.isNull() || SearchType->isDependentType() ||
207 Context.hasSameUnqualifiedType(T, SearchType)) {
208 // We found our type!
209
John McCallb3d87482010-08-24 05:47:05 +0000210 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000211 }
John Wiegley36784e72011-03-08 08:13:22 +0000212
Douglas Gregor7ec18732011-03-04 22:32:08 +0000213 if (!SearchType.isNull())
214 NonMatchingTypeDecl = Type;
Douglas Gregor124b8782010-02-16 19:09:40 +0000215 }
216
217 // If the name that we found is a class template name, and it is
218 // the same name as the template name in the last part of the
219 // nested-name-specifier (if present) or the object type, then
220 // this is the destructor for that class.
221 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000222 // issue 399, for which there isn't even an obvious direction.
Douglas Gregor124b8782010-02-16 19:09:40 +0000223 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
224 QualType MemberOfType;
225 if (SS.isSet()) {
226 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
227 // Figure out the type of the context, if it has one.
John McCall3cb0ebd2010-03-10 03:28:59 +0000228 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
229 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregor124b8782010-02-16 19:09:40 +0000230 }
231 }
232 if (MemberOfType.isNull())
233 MemberOfType = SearchType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000234
Douglas Gregor124b8782010-02-16 19:09:40 +0000235 if (MemberOfType.isNull())
236 continue;
237
238 // We're referring into a class template specialization. If the
239 // class template we found is the same as the template being
240 // specialized, we found what we are looking for.
241 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
242 if (ClassTemplateSpecializationDecl *Spec
243 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
244 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
245 Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000246 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000247 }
248
249 continue;
250 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000251
Douglas Gregor124b8782010-02-16 19:09:40 +0000252 // We're referring to an unresolved class template
253 // specialization. Determine whether we class template we found
254 // is the same as the template being specialized or, if we don't
255 // know which template is being specialized, that it at least
256 // has the same name.
257 if (const TemplateSpecializationType *SpecType
258 = MemberOfType->getAs<TemplateSpecializationType>()) {
259 TemplateName SpecName = SpecType->getTemplateName();
260
261 // The class template we found is the same template being
262 // specialized.
263 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
264 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallb3d87482010-08-24 05:47:05 +0000265 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000266
267 continue;
268 }
269
270 // The class template we found has the same name as the
271 // (dependent) template name being specialized.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000272 if (DependentTemplateName *DepTemplate
Douglas Gregor124b8782010-02-16 19:09:40 +0000273 = SpecName.getAsDependentTemplateName()) {
274 if (DepTemplate->isIdentifier() &&
275 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallb3d87482010-08-24 05:47:05 +0000276 return ParsedType::make(MemberOfType);
Douglas Gregor124b8782010-02-16 19:09:40 +0000277
278 continue;
279 }
280 }
281 }
282 }
283
284 if (isDependent) {
285 // We didn't find our type, but that's okay: it's dependent
286 // anyway.
Douglas Gregore29425b2011-02-28 22:42:13 +0000287
288 // FIXME: What if we have no nested-name-specifier?
289 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
290 SS.getWithLocInContext(Context),
291 II, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000292 return ParsedType::make(T);
Douglas Gregor124b8782010-02-16 19:09:40 +0000293 }
294
Douglas Gregor7ec18732011-03-04 22:32:08 +0000295 if (NonMatchingTypeDecl) {
296 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
297 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
298 << T << SearchType;
299 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
300 << T;
301 } else if (ObjectTypePtr)
302 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000303 << &II;
David Blaikie36771d92013-03-20 17:42:13 +0000304 else {
305 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
306 diag::err_destructor_class_name);
307 if (S) {
308 const DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
309 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
310 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
311 Class->getNameAsString());
312 }
313 }
Douglas Gregor124b8782010-02-16 19:09:40 +0000314
John McCallb3d87482010-08-24 05:47:05 +0000315 return ParsedType();
Douglas Gregor124b8782010-02-16 19:09:40 +0000316}
317
David Blaikie53a75c02011-12-08 16:13:53 +0000318ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie4db8c442011-12-12 04:13:55 +0000319 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikie53a75c02011-12-08 16:13:53 +0000320 return ParsedType();
321 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
322 && "only get destructor types from declspecs");
323 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
324 QualType SearchType = GetTypeFromParser(ObjectType);
325 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
326 return ParsedType::make(T);
327 }
328
329 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
330 << T << SearchType;
331 return ParsedType();
332}
333
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000334/// \brief Build a C++ typeid expression with a type operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000335ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000336 SourceLocation TypeidLoc,
337 TypeSourceInfo *Operand,
338 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000339 // C++ [expr.typeid]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000340 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000341 // that is the operand of typeid are always ignored.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000342 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000343 // type, the class shall be completely-defined.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000344 Qualifiers Quals;
345 QualType T
346 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
347 Quals);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000348 if (T->getAs<RecordType>() &&
349 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
350 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000351
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000352 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
353 Operand,
354 SourceRange(TypeidLoc, RParenLoc)));
355}
356
357/// \brief Build a C++ typeid expression with an expression operand.
John McCall60d7b3a2010-08-24 06:29:42 +0000358ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000359 SourceLocation TypeidLoc,
360 Expr *E,
361 SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000362 if (E && !E->isTypeDependent()) {
John McCall6dbba4f2011-10-11 23:14:30 +0000363 if (E->getType()->isPlaceholderType()) {
364 ExprResult result = CheckPlaceholderExpr(E);
365 if (result.isInvalid()) return ExprError();
366 E = result.take();
367 }
368
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000369 QualType T = E->getType();
370 if (const RecordType *RecordT = T->getAs<RecordType>()) {
371 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
372 // C++ [expr.typeid]p3:
373 // [...] If the type of the expression is a class type, the class
374 // shall be completely-defined.
375 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
376 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000377
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000378 // C++ [expr.typeid]p3:
Sebastian Redl906082e2010-07-20 04:20:21 +0000379 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000380 // polymorphic class type [...] [the] expression is an unevaluated
381 // operand. [...]
Richard Smith0d729102012-08-13 20:08:14 +0000382 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedmanef331b72012-01-20 01:26:23 +0000383 // The subexpression is potentially evaluated; switch the context
384 // and recheck the subexpression.
Benjamin Krameraccaf192012-11-14 15:08:31 +0000385 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedmanef331b72012-01-20 01:26:23 +0000386 if (Result.isInvalid()) return ExprError();
387 E = Result.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000388
389 // We require a vtable to query the type at run time.
390 MarkVTableUsed(TypeidLoc, RecordD);
391 }
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000392 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000393
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000394 // C++ [expr.typeid]p4:
395 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000396 // cv-qualified type, the result of the typeid expression refers to a
397 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000398 // type.
Douglas Gregord1c1d7b2010-06-02 06:16:02 +0000399 Qualifiers Quals;
400 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
401 if (!Context.hasSameType(T, UnqualT)) {
402 T = UnqualT;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000403 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000404 }
405 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000406
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000407 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCall9ae2f072010-08-23 23:25:46 +0000408 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000409 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000410}
411
412/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCall60d7b3a2010-08-24 06:29:42 +0000413ExprResult
Sebastian Redlc42e1182008-11-11 11:37:55 +0000414Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
415 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000416 // Find the std::type_info type.
Sebastian Redlce0682f2011-03-31 19:29:24 +0000417 if (!getStdNamespace())
Sebastian Redlf53597f2009-03-15 17:47:39 +0000418 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000419
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000420 if (!CXXTypeInfoDecl) {
421 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
422 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
423 LookupQualifiedName(R, getStdNamespace());
424 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Webered36b2a2012-06-19 23:58:27 +0000425 // Microsoft's typeinfo doesn't have type_info in std but in the global
426 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
427 if (!CXXTypeInfoDecl && LangOpts.MicrosoftMode) {
428 LookupQualifiedName(R, Context.getTranslationUnitDecl());
429 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
430 }
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000431 if (!CXXTypeInfoDecl)
432 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
433 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000434
Nico Weber11d1a692012-05-20 01:27:21 +0000435 if (!getLangOpts().RTTI) {
436 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
437 }
438
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000439 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000440
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000441 if (isType) {
442 // The operand is a type; handle it as such.
443 TypeSourceInfo *TInfo = 0;
John McCallb3d87482010-08-24 05:47:05 +0000444 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
445 &TInfo);
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000446 if (T.isNull())
447 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000448
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000449 if (!TInfo)
450 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000451
Douglas Gregor57fdc8a2010-04-26 22:37:10 +0000452 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000453 }
Mike Stump1eb44332009-09-09 15:08:12 +0000454
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000455 // The operand is an expression.
John McCall9ae2f072010-08-23 23:25:46 +0000456 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000457}
458
Francois Pichet01b7c302010-09-08 12:20:18 +0000459/// \brief Build a Microsoft __uuidof expression with a type operand.
460ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
461 SourceLocation TypeidLoc,
462 TypeSourceInfo *Operand,
463 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000464 if (!Operand->getType()->isDependentType()) {
David Majnemer29b37a02013-09-07 06:59:46 +0000465 bool HasMultipleGUIDs = false;
466 if (!CXXUuidofExpr::GetUuidAttrOfType(Operand->getType(),
467 &HasMultipleGUIDs)) {
468 if (HasMultipleGUIDs)
469 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
470 else
471 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
472 }
Francois Pichet6915c522010-12-27 01:32:00 +0000473 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000474
Francois Pichet01b7c302010-09-08 12:20:18 +0000475 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
476 Operand,
477 SourceRange(TypeidLoc, RParenLoc)));
478}
479
480/// \brief Build a Microsoft __uuidof expression with an expression operand.
481ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
482 SourceLocation TypeidLoc,
483 Expr *E,
484 SourceLocation RParenLoc) {
Francois Pichet6915c522010-12-27 01:32:00 +0000485 if (!E->getType()->isDependentType()) {
David Majnemer29b37a02013-09-07 06:59:46 +0000486 bool HasMultipleGUIDs = false;
487 if (!CXXUuidofExpr::GetUuidAttrOfType(E->getType(), &HasMultipleGUIDs) &&
488 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
489 if (HasMultipleGUIDs)
490 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
491 else
492 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
493 }
Francois Pichet6915c522010-12-27 01:32:00 +0000494 }
David Majnemer29b37a02013-09-07 06:59:46 +0000495
Francois Pichet01b7c302010-09-08 12:20:18 +0000496 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
497 E,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000498 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet01b7c302010-09-08 12:20:18 +0000499}
500
501/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
502ExprResult
503Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
504 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000505 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet01b7c302010-09-08 12:20:18 +0000506 if (!MSVCGuidDecl) {
507 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
508 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
509 LookupQualifiedName(R, Context.getTranslationUnitDecl());
510 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
511 if (!MSVCGuidDecl)
512 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000513 }
514
Francois Pichet01b7c302010-09-08 12:20:18 +0000515 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000516
Francois Pichet01b7c302010-09-08 12:20:18 +0000517 if (isType) {
518 // The operand is a type; handle it as such.
519 TypeSourceInfo *TInfo = 0;
520 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
521 &TInfo);
522 if (T.isNull())
523 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000524
Francois Pichet01b7c302010-09-08 12:20:18 +0000525 if (!TInfo)
526 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
527
528 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
529 }
530
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000531 // The operand is an expression.
Francois Pichet01b7c302010-09-08 12:20:18 +0000532 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
533}
534
Steve Naroff1b273c42007-09-16 14:56:35 +0000535/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCall60d7b3a2010-08-24 06:29:42 +0000536ExprResult
Steve Naroff1b273c42007-09-16 14:56:35 +0000537Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor2f639b92008-10-24 15:36:09 +0000538 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 "Unknown C++ Boolean value!");
Sebastian Redlf53597f2009-03-15 17:47:39 +0000540 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
541 Context.BoolTy, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +0000542}
Chris Lattner50dd2892008-02-26 00:51:44 +0000543
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000544/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCall60d7b3a2010-08-24 06:29:42 +0000545ExprResult
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000546Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
547 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
548}
549
Chris Lattner50dd2892008-02-26 00:51:44 +0000550/// ActOnCXXThrow - Parse throw expressions.
John McCall60d7b3a2010-08-24 06:29:42 +0000551ExprResult
Douglas Gregorbca01b42011-07-06 22:04:06 +0000552Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
553 bool IsThrownVarInScope = false;
554 if (Ex) {
555 // C++0x [class.copymove]p31:
556 // When certain criteria are met, an implementation is allowed to omit the
557 // copy/move construction of a class object [...]
558 //
559 // - in a throw-expression, when the operand is the name of a
560 // non-volatile automatic object (other than a function or catch-
561 // clause parameter) whose scope does not extend beyond the end of the
562 // innermost enclosing try-block (if there is one), the copy/move
563 // operation from the operand to the exception object (15.1) can be
564 // omitted by constructing the automatic object directly into the
565 // exception object
566 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
567 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
568 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
569 for( ; S; S = S->getParent()) {
570 if (S->isDeclScope(Var)) {
571 IsThrownVarInScope = true;
572 break;
573 }
574
575 if (S->getFlags() &
576 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
577 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
578 Scope::TryScope))
579 break;
580 }
581 }
582 }
583 }
584
585 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
586}
587
588ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
589 bool IsThrownVarInScope) {
Anders Carlsson729b8532011-02-23 03:46:46 +0000590 // Don't report an error if 'throw' is used in system headers.
David Blaikie4e4d0842012-03-11 07:00:24 +0000591 if (!getLangOpts().CXXExceptions &&
Anders Carlsson729b8532011-02-23 03:46:46 +0000592 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb1fba312011-02-19 21:53:09 +0000593 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregorbca01b42011-07-06 22:04:06 +0000594
John Wiegley429bb272011-04-08 18:41:53 +0000595 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregorbca01b42011-07-06 22:04:06 +0000596 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley429bb272011-04-08 18:41:53 +0000597 if (ExRes.isInvalid())
598 return ExprError();
599 Ex = ExRes.take();
600 }
Douglas Gregorbca01b42011-07-06 22:04:06 +0000601
602 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
603 IsThrownVarInScope));
Sebastian Redl972041f2009-04-27 20:27:31 +0000604}
605
606/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000607ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
608 bool IsThrownVarInScope) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000609 // C++ [except.throw]p3:
Douglas Gregor154fe982009-12-23 22:04:40 +0000610 // A throw-expression initializes a temporary object, called the exception
611 // object, the type of which is determined by removing any top-level
612 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000613 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor154fe982009-12-23 22:04:40 +0000614 // or "pointer to function returning T", [...]
615 if (E->getType().hasQualifiers())
John Wiegley429bb272011-04-08 18:41:53 +0000616 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +0000617 E->getValueKind()).take();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000618
John Wiegley429bb272011-04-08 18:41:53 +0000619 ExprResult Res = DefaultFunctionArrayConversion(E);
620 if (Res.isInvalid())
621 return ExprError();
622 E = Res.take();
Sebastian Redl972041f2009-04-27 20:27:31 +0000623
624 // If the type of the exception would be an incomplete type or a pointer
625 // to an incomplete type other than (cv) void the program is ill-formed.
626 QualType Ty = E->getType();
John McCallac418162010-04-22 01:10:34 +0000627 bool isPointer = false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000628 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000629 Ty = Ptr->getPointeeType();
John McCallac418162010-04-22 01:10:34 +0000630 isPointer = true;
Sebastian Redl972041f2009-04-27 20:27:31 +0000631 }
632 if (!isPointer || !Ty->isVoidType()) {
633 if (RequireCompleteType(ThrowLoc, Ty,
Douglas Gregord10099e2012-05-04 16:32:21 +0000634 isPointer? diag::err_throw_incomplete_ptr
635 : diag::err_throw_incomplete,
636 E->getSourceRange()))
John Wiegley429bb272011-04-08 18:41:53 +0000637 return ExprError();
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +0000638
Douglas Gregorbf422f92010-04-15 18:05:39 +0000639 if (RequireNonAbstractType(ThrowLoc, E->getType(),
Douglas Gregor6a26e2e2012-05-04 17:09:59 +0000640 diag::err_throw_abstract_type, E))
John Wiegley429bb272011-04-08 18:41:53 +0000641 return ExprError();
Sebastian Redl972041f2009-04-27 20:27:31 +0000642 }
643
John McCallac418162010-04-22 01:10:34 +0000644 // Initialize the exception result. This implicitly weeds out
645 // abstract types or types with inaccessible copy constructors.
Douglas Gregorbca01b42011-07-06 22:04:06 +0000646
647 // C++0x [class.copymove]p31:
648 // When certain criteria are met, an implementation is allowed to omit the
649 // copy/move construction of a class object [...]
650 //
651 // - in a throw-expression, when the operand is the name of a
652 // non-volatile automatic object (other than a function or catch-clause
653 // parameter) whose scope does not extend beyond the end of the
654 // innermost enclosing try-block (if there is one), the copy/move
655 // operation from the operand to the exception object (15.1) can be
656 // omitted by constructing the automatic object directly into the
657 // exception object
658 const VarDecl *NRVOVariable = 0;
659 if (IsThrownVarInScope)
660 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
661
John McCallac418162010-04-22 01:10:34 +0000662 InitializedEntity Entity =
Douglas Gregor72dfa272011-01-21 22:46:35 +0000663 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregorbca01b42011-07-06 22:04:06 +0000664 /*NRVO=*/NRVOVariable != 0);
John Wiegley429bb272011-04-08 18:41:53 +0000665 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregorbca01b42011-07-06 22:04:06 +0000666 QualType(), E,
667 IsThrownVarInScope);
John McCallac418162010-04-22 01:10:34 +0000668 if (Res.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000669 return ExprError();
670 E = Res.take();
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000671
Eli Friedman5ed9b932010-06-03 20:39:03 +0000672 // If the exception has class type, we need additional handling.
673 const RecordType *RecordTy = Ty->getAs<RecordType>();
674 if (!RecordTy)
John Wiegley429bb272011-04-08 18:41:53 +0000675 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000676 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
677
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000678 // If we are throwing a polymorphic class type or pointer thereof,
679 // exception handling will make use of the vtable.
Eli Friedman5ed9b932010-06-03 20:39:03 +0000680 MarkVTableUsed(ThrowLoc, RD);
681
Eli Friedman98efb9f2010-10-12 20:32:36 +0000682 // If a pointer is thrown, the referenced object will not be destroyed.
683 if (isPointer)
John Wiegley429bb272011-04-08 18:41:53 +0000684 return Owned(E);
Eli Friedman98efb9f2010-10-12 20:32:36 +0000685
Richard Smith213d70b2012-02-18 04:13:32 +0000686 // If the class has a destructor, we must be able to call it.
687 if (RD->hasIrrelevantDestructor())
John Wiegley429bb272011-04-08 18:41:53 +0000688 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000689
Sebastian Redl28357452012-03-05 19:35:43 +0000690 CXXDestructorDecl *Destructor = LookupDestructor(RD);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000691 if (!Destructor)
John Wiegley429bb272011-04-08 18:41:53 +0000692 return Owned(E);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000693
Eli Friedman5f2987c2012-02-02 03:46:19 +0000694 MarkFunctionReferenced(E->getExprLoc(), Destructor);
Eli Friedman5ed9b932010-06-03 20:39:03 +0000695 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregored8abf12010-07-08 06:14:04 +0000696 PDiag(diag::err_access_dtor_exception) << Ty);
Richard Smith82f145d2013-05-04 06:44:46 +0000697 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
698 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +0000699 return Owned(E);
Chris Lattner50dd2892008-02-26 00:51:44 +0000700}
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000701
Eli Friedman72899c32012-01-07 04:59:52 +0000702QualType Sema::getCurrentThisType() {
703 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000704 QualType ThisTy = CXXThisTypeOverride;
Richard Smith7a614d82011-06-11 17:19:42 +0000705 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
706 if (method && method->isInstance())
707 ThisTy = method->getThisType(Context);
Richard Smith7a614d82011-06-11 17:19:42 +0000708 }
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000709
Richard Smith7a614d82011-06-11 17:19:42 +0000710 return ThisTy;
John McCall5808ce42011-02-03 08:15:49 +0000711}
712
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000713Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
714 Decl *ContextDecl,
715 unsigned CXXThisTypeQuals,
716 bool Enabled)
717 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
718{
719 if (!Enabled || !ContextDecl)
720 return;
721
722 CXXRecordDecl *Record = 0;
723 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
724 Record = Template->getTemplatedDecl();
725 else
726 Record = cast<CXXRecordDecl>(ContextDecl);
727
728 S.CXXThisTypeOverride
729 = S.Context.getPointerType(
730 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
731
732 this->Enabled = true;
733}
734
735
736Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
737 if (Enabled) {
738 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
739 }
740}
741
Ben Langmuir3a2f9122013-04-29 13:32:41 +0000742static Expr *captureThis(ASTContext &Context, RecordDecl *RD,
743 QualType ThisTy, SourceLocation Loc) {
744 FieldDecl *Field
745 = FieldDecl::Create(Context, RD, Loc, Loc, 0, ThisTy,
746 Context.getTrivialTypeSourceInfo(ThisTy, Loc),
747 0, false, ICIS_NoInit);
748 Field->setImplicit(true);
749 Field->setAccess(AS_private);
750 RD->addDecl(Field);
751 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/true);
752}
753
Douglas Gregora1f21142012-02-01 17:04:21 +0000754void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) {
Eli Friedman72899c32012-01-07 04:59:52 +0000755 // We don't need to capture this in an unevaluated context.
John McCallaeeacf72013-05-03 00:10:13 +0000756 if (isUnevaluatedContext() && !Explicit)
Eli Friedman72899c32012-01-07 04:59:52 +0000757 return;
758
759 // Otherwise, check that we can capture 'this'.
760 unsigned NumClosures = 0;
761 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000762 if (CapturingScopeInfo *CSI =
763 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
764 if (CSI->CXXThisCaptureIndex != 0) {
765 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman72899c32012-01-07 04:59:52 +0000766 break;
767 }
Douglas Gregora1f21142012-02-01 17:04:21 +0000768
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000769 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000770 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregora1f21142012-02-01 17:04:21 +0000771 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6afcf882013-04-16 19:37:38 +0000772 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Douglas Gregora1f21142012-02-01 17:04:21 +0000773 Explicit) {
774 // This closure can capture 'this'; continue looking upwards.
Eli Friedman72899c32012-01-07 04:59:52 +0000775 NumClosures++;
Douglas Gregora1f21142012-02-01 17:04:21 +0000776 Explicit = false;
Eli Friedman72899c32012-01-07 04:59:52 +0000777 continue;
778 }
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000779 // This context can't implicitly capture 'this'; fail out.
Douglas Gregora1f21142012-02-01 17:04:21 +0000780 Diag(Loc, diag::err_this_capture) << Explicit;
Eli Friedman72899c32012-01-07 04:59:52 +0000781 return;
782 }
Eli Friedman72899c32012-01-07 04:59:52 +0000783 break;
784 }
785
786 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
787 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
788 // contexts.
789 for (unsigned idx = FunctionScopes.size() - 1;
790 NumClosures; --idx, --NumClosures) {
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000791 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Eli Friedman668165a2012-02-11 02:51:16 +0000792 Expr *ThisExpr = 0;
Douglas Gregor999713e2012-02-18 09:37:24 +0000793 QualType ThisTy = getCurrentThisType();
Ben Langmuir3a2f9122013-04-29 13:32:41 +0000794 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI))
Eli Friedman668165a2012-02-11 02:51:16 +0000795 // For lambda expressions, build a field and an initializing expression.
Ben Langmuir3a2f9122013-04-29 13:32:41 +0000796 ThisExpr = captureThis(Context, LSI->Lambda, ThisTy, Loc);
797 else if (CapturedRegionScopeInfo *RSI
798 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
799 ThisExpr = captureThis(Context, RSI->TheRecordDecl, ThisTy, Loc);
Tareq A. Siraj6afcf882013-04-16 19:37:38 +0000800
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000801 bool isNested = NumClosures > 1;
Douglas Gregor999713e2012-02-18 09:37:24 +0000802 CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
Eli Friedman72899c32012-01-07 04:59:52 +0000803 }
804}
805
Richard Smith7a614d82011-06-11 17:19:42 +0000806ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCall5808ce42011-02-03 08:15:49 +0000807 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
808 /// is a non-lvalue expression whose value is the address of the object for
809 /// which the function is called.
810
Douglas Gregor341350e2011-10-18 16:47:30 +0000811 QualType ThisTy = getCurrentThisType();
Richard Smith7a614d82011-06-11 17:19:42 +0000812 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCall5808ce42011-02-03 08:15:49 +0000813
Eli Friedman72899c32012-01-07 04:59:52 +0000814 CheckCXXThisCapture(Loc);
Richard Smith7a614d82011-06-11 17:19:42 +0000815 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000816}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000817
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000818bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
819 // If we're outside the body of a member function, then we'll have a specified
820 // type for 'this'.
821 if (CXXThisTypeOverride.isNull())
822 return false;
823
824 // Determine whether we're looking into a class that's currently being
825 // defined.
826 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
827 return Class && Class->isBeingDefined();
828}
829
John McCall60d7b3a2010-08-24 06:29:42 +0000830ExprResult
Douglas Gregorab6677e2010-09-08 00:15:04 +0000831Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000832 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000833 MultiExprArg exprs,
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000834 SourceLocation RParenLoc) {
Douglas Gregorae4c77d2010-02-05 19:11:37 +0000835 if (!TypeRep)
836 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000837
John McCall9d125032010-01-15 18:39:57 +0000838 TypeSourceInfo *TInfo;
839 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
840 if (!TInfo)
841 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregorab6677e2010-09-08 00:15:04 +0000842
843 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
844}
845
846/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
847/// Can be interpreted either as function-style casting ("int(x)")
848/// or class type construction ("ClassType(x,y,z)")
849/// or creation of a value-initialized type ("int()").
850ExprResult
851Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
852 SourceLocation LParenLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000853 MultiExprArg Exprs,
Douglas Gregorab6677e2010-09-08 00:15:04 +0000854 SourceLocation RParenLoc) {
855 QualType Ty = TInfo->getType();
Douglas Gregorab6677e2010-09-08 00:15:04 +0000856 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000857
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000858 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Douglas Gregorab6677e2010-09-08 00:15:04 +0000859 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000860 LParenLoc,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000861 Exprs,
Douglas Gregord81e6ca2009-05-20 18:46:25 +0000862 RParenLoc));
Douglas Gregorba498172009-03-13 21:01:28 +0000863 }
864
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000865 bool ListInitialization = LParenLoc.isInvalid();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000866 assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000867 && "List initialization must have initializer list as expression.");
868 SourceRange FullRange = SourceRange(TyBeginLoc,
869 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
870
Douglas Gregor506ae412009-01-16 18:33:17 +0000871 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000872 // If the expression list is a single expression, the type conversion
873 // expression is equivalent (in definedness, and if defined in meaning) to the
874 // corresponding cast expression.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000875 if (Exprs.size() == 1 && !ListInitialization) {
John McCallb45ae252011-10-05 07:41:44 +0000876 Expr *Arg = Exprs[0];
John McCallb45ae252011-10-05 07:41:44 +0000877 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000878 }
879
Eli Friedmanc60ccf52012-02-29 00:00:28 +0000880 QualType ElemTy = Ty;
881 if (Ty->isArrayType()) {
882 if (!ListInitialization)
883 return ExprError(Diag(TyBeginLoc,
884 diag::err_value_init_for_array_type) << FullRange);
885 ElemTy = Context.getBaseElementType(Ty);
886 }
887
888 if (!Ty->isVoidType() &&
889 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregord10099e2012-05-04 16:32:21 +0000890 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedmanc60ccf52012-02-29 00:00:28 +0000891 return ExprError();
892
893 if (RequireNonAbstractType(TyBeginLoc, Ty,
894 diag::err_allocation_of_abstract_type))
895 return ExprError();
896
Douglas Gregor19311e72010-09-08 21:40:08 +0000897 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000898 InitializationKind Kind =
899 Exprs.size() ? ListInitialization
900 ? InitializationKind::CreateDirectList(TyBeginLoc)
901 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
902 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
903 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
904 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000905
Richard Smith25b24eb2013-09-23 02:20:00 +0000906 if (Result.isInvalid() || !ListInitialization)
907 return Result;
908
909 Expr *Inner = Result.get();
910 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
911 Inner = BTE->getSubExpr();
912 if (isa<InitListExpr>(Inner)) {
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000913 // If the list-initialization doesn't involve a constructor call, we'll get
914 // the initializer-list (with corrected type) back, but that's not what we
915 // want, since it will be treated as an initializer list in further
916 // processing. Explicitly insert a cast here.
Richard Smith25b24eb2013-09-23 02:20:00 +0000917 QualType ResultType = Result.get()->getType();
918 Result = Owned(CXXFunctionalCastExpr::Create(
919 Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
920 CK_NoOp, Result.take(), /*Path=*/ 0, LParenLoc, RParenLoc));
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000921 }
922
Douglas Gregor19311e72010-09-08 21:40:08 +0000923 // FIXME: Improve AST representation?
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000924 return Result;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +0000925}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000926
John McCall6ec278d2011-01-27 09:37:56 +0000927/// doesUsualArrayDeleteWantSize - Answers whether the usual
928/// operator delete[] for the given type has a size_t parameter.
929static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
930 QualType allocType) {
931 const RecordType *record =
932 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
933 if (!record) return false;
934
935 // Try to find an operator delete[] in class scope.
936
937 DeclarationName deleteName =
938 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
939 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
940 S.LookupQualifiedName(ops, record->getDecl());
941
942 // We're just doing this for information.
943 ops.suppressDiagnostics();
944
945 // Very likely: there's no operator delete[].
946 if (ops.empty()) return false;
947
948 // If it's ambiguous, it should be illegal to call operator delete[]
949 // on this thing, so it doesn't matter if we allocate extra space or not.
950 if (ops.isAmbiguous()) return false;
951
952 LookupResult::Filter filter = ops.makeFilter();
953 while (filter.hasNext()) {
954 NamedDecl *del = filter.next()->getUnderlyingDecl();
955
956 // C++0x [basic.stc.dynamic.deallocation]p2:
957 // A template instance is never a usual deallocation function,
958 // regardless of its signature.
959 if (isa<FunctionTemplateDecl>(del)) {
960 filter.erase();
961 continue;
962 }
963
964 // C++0x [basic.stc.dynamic.deallocation]p2:
965 // If class T does not declare [an operator delete[] with one
966 // parameter] but does declare a member deallocation function
967 // named operator delete[] with exactly two parameters, the
968 // second of which has type std::size_t, then this function
969 // is a usual deallocation function.
970 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
971 filter.erase();
972 continue;
973 }
974 }
975 filter.done();
976
977 if (!ops.isSingleResult()) return false;
978
979 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
980 return (del->getNumParams() == 2);
981}
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +0000982
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000983/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettef2b5b32012-06-15 22:23:43 +0000984///
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000985/// E.g.:
Sebastian Redl4c5d3202008-11-21 19:14:01 +0000986/// @code new (memory) int[size][4] @endcode
987/// or
988/// @code ::new Foo(23, "hello") @endcode
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000989///
990/// \param StartLoc The first location of the expression.
991/// \param UseGlobal True if 'new' was prefixed with '::'.
992/// \param PlacementLParen Opening paren of the placement arguments.
993/// \param PlacementArgs Placement new arguments.
994/// \param PlacementRParen Closing paren of the placement arguments.
995/// \param TypeIdParens If the type is in parens, the source range.
996/// \param D The type to be allocated, as well as array dimensions.
James Dennettef2b5b32012-06-15 22:23:43 +0000997/// \param Initializer The initializing expression or initializer-list, or null
998/// if there is none.
John McCall60d7b3a2010-08-24 06:29:42 +0000999ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001000Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redlf53597f2009-03-15 17:47:39 +00001001 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001002 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001003 Declarator &D, Expr *Initializer) {
Richard Smitha2c36462013-04-26 16:15:35 +00001004 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
Richard Smith34b41d92011-02-20 03:19:35 +00001005
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001006 Expr *ArraySize = 0;
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001007 // If the specified type is an array, unwrap it and save the expression.
1008 if (D.getNumTypeObjects() > 0 &&
1009 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
James Dennettef2b5b32012-06-15 22:23:43 +00001010 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith34b41d92011-02-20 03:19:35 +00001011 if (TypeContainsAuto)
1012 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1013 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001014 if (Chunk.Arr.hasStatic)
Sebastian Redlf53597f2009-03-15 17:47:39 +00001015 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1016 << D.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001017 if (!Chunk.Arr.NumElts)
Sebastian Redlf53597f2009-03-15 17:47:39 +00001018 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1019 << D.getSourceRange());
Sebastian Redl8ce35b02009-10-25 21:45:37 +00001020
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001021 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redl8ce35b02009-10-25 21:45:37 +00001022 D.DropFirstTypeObject();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001023 }
1024
Douglas Gregor043cad22009-09-11 00:18:58 +00001025 // Every dimension shall be of constant size.
Sebastian Redl8ce35b02009-10-25 21:45:37 +00001026 if (ArraySize) {
1027 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor043cad22009-09-11 00:18:58 +00001028 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1029 break;
1030
1031 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1032 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smith282e7e62012-02-04 09:53:13 +00001033 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Larisse Voufo539470e2013-06-15 20:17:46 +00001034 if (getLangOpts().CPlusPlus1y) {
1035 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1036 // shall be a converted constant expression (5.19) of type std::size_t
1037 // and shall evaluate to a strictly positive value.
1038 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1039 assert(IntWidth && "Builtin type of size 0?");
1040 llvm::APSInt Value(IntWidth);
1041 Array.NumElts
1042 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1043 CCEK_NewExpr)
1044 .take();
1045 } else {
1046 Array.NumElts
1047 = VerifyIntegerConstantExpression(NumElts, 0,
1048 diag::err_new_array_nonconst)
1049 .take();
1050 }
Richard Smith282e7e62012-02-04 09:53:13 +00001051 if (!Array.NumElts)
1052 return ExprError();
Douglas Gregor043cad22009-09-11 00:18:58 +00001053 }
1054 }
1055 }
1056 }
Sebastian Redl8ce35b02009-10-25 21:45:37 +00001057
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00001058 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCallbf1a0282010-06-04 23:28:52 +00001059 QualType AllocType = TInfo->getType();
Chris Lattnereaaebc72009-04-25 08:06:05 +00001060 if (D.isInvalidType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00001061 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001062
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001063 SourceRange DirectInitRange;
1064 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1065 DirectInitRange = List->getSourceRange();
1066
David Blaikie53056412012-11-07 00:12:38 +00001067 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +00001068 PlacementLParen,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001069 PlacementArgs,
Douglas Gregor3433cf72009-05-21 00:00:09 +00001070 PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001071 TypeIdParens,
Mike Stump1eb44332009-09-09 15:08:12 +00001072 AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001073 TInfo,
John McCall9ae2f072010-08-23 23:25:46 +00001074 ArraySize,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001075 DirectInitRange,
1076 Initializer,
Richard Smith34b41d92011-02-20 03:19:35 +00001077 TypeContainsAuto);
Douglas Gregor3433cf72009-05-21 00:00:09 +00001078}
1079
Sebastian Redlbd45d252012-02-16 12:59:47 +00001080static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1081 Expr *Init) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001082 if (!Init)
1083 return true;
Sebastian Redl1f278052012-02-17 08:42:32 +00001084 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1085 return PLE->getNumExprs() == 0;
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001086 if (isa<ImplicitValueInitExpr>(Init))
1087 return true;
1088 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1089 return !CCE->isListInitialization() &&
1090 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlbd45d252012-02-16 12:59:47 +00001091 else if (Style == CXXNewExpr::ListInit) {
1092 assert(isa<InitListExpr>(Init) &&
1093 "Shouldn't create list CXXConstructExprs for arrays.");
1094 return true;
1095 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001096 return false;
1097}
1098
John McCall60d7b3a2010-08-24 06:29:42 +00001099ExprResult
David Blaikie53056412012-11-07 00:12:38 +00001100Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregor3433cf72009-05-21 00:00:09 +00001101 SourceLocation PlacementLParen,
1102 MultiExprArg PlacementArgs,
1103 SourceLocation PlacementRParen,
Douglas Gregor4bd40312010-07-13 15:54:32 +00001104 SourceRange TypeIdParens,
Douglas Gregor3433cf72009-05-21 00:00:09 +00001105 QualType AllocType,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001106 TypeSourceInfo *AllocTypeInfo,
John McCall9ae2f072010-08-23 23:25:46 +00001107 Expr *ArraySize,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001108 SourceRange DirectInitRange,
1109 Expr *Initializer,
Richard Smith34b41d92011-02-20 03:19:35 +00001110 bool TypeMayContainAuto) {
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001111 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie53056412012-11-07 00:12:38 +00001112 SourceLocation StartLoc = Range.getBegin();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001113
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001114 CXXNewExpr::InitializationStyle initStyle;
1115 if (DirectInitRange.isValid()) {
1116 assert(Initializer && "Have parens but no initializer.");
1117 initStyle = CXXNewExpr::CallInit;
1118 } else if (Initializer && isa<InitListExpr>(Initializer))
1119 initStyle = CXXNewExpr::ListInit;
1120 else {
1121 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1122 isa<CXXConstructExpr>(Initializer)) &&
1123 "Initializer expression that cannot have been implicitly created.");
1124 initStyle = CXXNewExpr::NoInit;
1125 }
1126
1127 Expr **Inits = &Initializer;
1128 unsigned NumInits = Initializer ? 1 : 0;
Richard Smith73ed67c2012-11-26 08:32:48 +00001129 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1130 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1131 Inits = List->getExprs();
1132 NumInits = List->getNumExprs();
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001133 }
1134
Richard Smith73ed67c2012-11-26 08:32:48 +00001135 // Determine whether we've already built the initializer.
1136 bool HaveCompleteInit = false;
1137 if (Initializer && isa<CXXConstructExpr>(Initializer) &&
1138 !isa<CXXTemporaryObjectExpr>(Initializer))
1139 HaveCompleteInit = true;
1140 else if (Initializer && isa<ImplicitValueInitExpr>(Initializer))
1141 HaveCompleteInit = true;
1142
Richard Smith8ad6c862012-07-08 04:13:07 +00001143 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smithdc7a4f52013-04-30 13:56:41 +00001144 if (TypeMayContainAuto && AllocType->isUndeducedType()) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001145 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith34b41d92011-02-20 03:19:35 +00001146 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1147 << AllocType << TypeRange);
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001148 if (initStyle == CXXNewExpr::ListInit)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001149 return ExprError(Diag(Inits[0]->getLocStart(),
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001150 diag::err_auto_new_requires_parens)
1151 << AllocType << TypeRange);
1152 if (NumInits > 1) {
1153 Expr *FirstBad = Inits[1];
Daniel Dunbar96a00142012-03-09 18:35:03 +00001154 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith34b41d92011-02-20 03:19:35 +00001155 diag::err_auto_new_ctor_multiple_expressions)
1156 << AllocType << TypeRange);
1157 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001158 Expr *Deduce = Inits[0];
Richard Smith9b131752013-04-30 21:23:01 +00001159 QualType DeducedType;
Richard Smith8ad6c862012-07-08 04:13:07 +00001160 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith34b41d92011-02-20 03:19:35 +00001161 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001162 << AllocType << Deduce->getType()
1163 << TypeRange << Deduce->getSourceRange());
Richard Smith9b131752013-04-30 21:23:01 +00001164 if (DeducedType.isNull())
Richard Smitha085da82011-03-17 16:11:59 +00001165 return ExprError();
Richard Smith9b131752013-04-30 21:23:01 +00001166 AllocType = DeducedType;
Richard Smith34b41d92011-02-20 03:19:35 +00001167 }
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001168
Douglas Gregor3caf04e2010-05-16 16:01:03 +00001169 // Per C++0x [expr.new]p5, the type being constructed may be a
1170 // typedef of an array type.
John McCall9ae2f072010-08-23 23:25:46 +00001171 if (!ArraySize) {
Douglas Gregor3caf04e2010-05-16 16:01:03 +00001172 if (const ConstantArrayType *Array
1173 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001174 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1175 Context.getSizeType(),
1176 TypeRange.getEnd());
Douglas Gregor3caf04e2010-05-16 16:01:03 +00001177 AllocType = Array->getElementType();
1178 }
1179 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001180
Douglas Gregora0750762010-10-06 16:00:31 +00001181 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1182 return ExprError();
1183
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001184 if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001185 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1186 diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001187 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001188 }
1189
John McCallf85e1932011-06-15 23:02:42 +00001190 // In ARC, infer 'retaining' for the allocated
David Blaikie4e4d0842012-03-11 07:00:24 +00001191 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001192 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1193 AllocType->isObjCLifetimeType()) {
1194 AllocType = Context.getLifetimeQualifiedType(AllocType,
1195 AllocType->getObjCARCImplicitLifetime());
1196 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001197
John McCallf85e1932011-06-15 23:02:42 +00001198 QualType ResultType = Context.getPointerType(AllocType);
1199
John McCall76da55d2013-04-16 07:28:30 +00001200 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1201 ExprResult result = CheckPlaceholderExpr(ArraySize);
1202 if (result.isInvalid()) return ExprError();
1203 ArraySize = result.take();
1204 }
Richard Smithf39aec12012-02-04 07:07:42 +00001205 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1206 // integral or enumeration type with a non-negative value."
1207 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1208 // enumeration type, or a class type for which a single non-explicit
1209 // conversion function to integral or unscoped enumeration type exists.
Richard Smith097e0a22013-05-21 19:05:48 +00001210 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufo904df3e2013-06-18 03:08:53 +00001211 // std::size_t.
Sebastian Redl28507842009-02-26 14:39:58 +00001212 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo539470e2013-06-15 20:17:46 +00001213 ExprResult ConvertedSize;
1214 if (getLangOpts().CPlusPlus1y) {
1215 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1216 assert(IntWidth && "Builtin type of size 0?");
1217 llvm::APSInt Value(IntWidth);
1218 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1219 AA_Converting);
Richard Smith097e0a22013-05-21 19:05:48 +00001220
Larisse Voufo904df3e2013-06-18 03:08:53 +00001221 if (!ConvertedSize.isInvalid() &&
1222 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo0bb51992013-06-18 01:27:47 +00001223 // Diagnose the compatibility of this conversion.
1224 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1225 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo539470e2013-06-15 20:17:46 +00001226 } else {
1227 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1228 protected:
1229 Expr *ArraySize;
1230
1231 public:
1232 SizeConvertDiagnoser(Expr *ArraySize)
1233 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1234 ArraySize(ArraySize) {}
1235
1236 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1237 QualType T) {
1238 return S.Diag(Loc, diag::err_array_size_not_integral)
1239 << S.getLangOpts().CPlusPlus11 << T;
1240 }
1241
1242 virtual SemaDiagnosticBuilder diagnoseIncomplete(
1243 Sema &S, SourceLocation Loc, QualType T) {
1244 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1245 << T << ArraySize->getSourceRange();
1246 }
1247
1248 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
1249 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
1250 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1251 }
1252
1253 virtual SemaDiagnosticBuilder noteExplicitConv(
1254 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
1255 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1256 << ConvTy->isEnumeralType() << ConvTy;
1257 }
1258
1259 virtual SemaDiagnosticBuilder diagnoseAmbiguous(
1260 Sema &S, SourceLocation Loc, QualType T) {
1261 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1262 }
1263
1264 virtual SemaDiagnosticBuilder noteAmbiguous(
1265 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
1266 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1267 << ConvTy->isEnumeralType() << ConvTy;
1268 }
Richard Smith097e0a22013-05-21 19:05:48 +00001269
Larisse Voufo539470e2013-06-15 20:17:46 +00001270 virtual SemaDiagnosticBuilder diagnoseConversion(
1271 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
1272 return S.Diag(Loc,
1273 S.getLangOpts().CPlusPlus11
1274 ? diag::warn_cxx98_compat_array_size_conversion
1275 : diag::ext_array_size_conversion)
1276 << T << ConvTy->isEnumeralType() << ConvTy;
1277 }
1278 } SizeDiagnoser(ArraySize);
Richard Smith097e0a22013-05-21 19:05:48 +00001279
Larisse Voufo539470e2013-06-15 20:17:46 +00001280 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1281 SizeDiagnoser);
1282 }
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001283 if (ConvertedSize.isInvalid())
1284 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001285
John McCall9ae2f072010-08-23 23:25:46 +00001286 ArraySize = ConvertedSize.take();
John McCall806054d2012-01-11 00:14:46 +00001287 QualType SizeType = ArraySize->getType();
Larisse Voufo539470e2013-06-15 20:17:46 +00001288
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001289 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor6bc574d2010-06-30 00:20:43 +00001290 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001291
Richard Smith0b458fd2012-02-04 05:35:53 +00001292 // C++98 [expr.new]p7:
1293 // The expression in a direct-new-declarator shall have integral type
1294 // with a non-negative value.
1295 //
1296 // Let's see if this is a constant < 0. If so, we reject it out of
1297 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1298 // array type.
1299 //
1300 // Note: such a construct has well-defined semantics in C++11: it throws
1301 // std::bad_array_new_length.
Sebastian Redl28507842009-02-26 14:39:58 +00001302 if (!ArraySize->isValueDependent()) {
1303 llvm::APSInt Value;
Richard Smith282e7e62012-02-04 09:53:13 +00001304 // We've already performed any required implicit conversion to integer or
1305 // unscoped enumeration type.
Richard Smith0b458fd2012-02-04 05:35:53 +00001306 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Sebastian Redl28507842009-02-26 14:39:58 +00001307 if (Value < llvm::APSInt(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001308 llvm::APInt::getNullValue(Value.getBitWidth()),
Richard Smith0b458fd2012-02-04 05:35:53 +00001309 Value.isUnsigned())) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001310 if (getLangOpts().CPlusPlus11)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001311 Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001312 diag::warn_typecheck_negative_array_new_size)
Douglas Gregor2767ce22010-08-18 00:39:00 +00001313 << ArraySize->getSourceRange();
Richard Smith0b458fd2012-02-04 05:35:53 +00001314 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00001315 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001316 diag::err_typecheck_negative_array_size)
1317 << ArraySize->getSourceRange());
1318 } else if (!AllocType->isDependentType()) {
1319 unsigned ActiveSizeBits =
1320 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1321 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001322 if (getLangOpts().CPlusPlus11)
Daniel Dunbar96a00142012-03-09 18:35:03 +00001323 Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001324 diag::warn_array_new_too_large)
1325 << Value.toString(10)
1326 << ArraySize->getSourceRange();
1327 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00001328 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smith0b458fd2012-02-04 05:35:53 +00001329 diag::err_array_too_large)
1330 << Value.toString(10)
1331 << ArraySize->getSourceRange());
Douglas Gregor2767ce22010-08-18 00:39:00 +00001332 }
1333 }
Douglas Gregor4bd40312010-07-13 15:54:32 +00001334 } else if (TypeIdParens.isValid()) {
1335 // Can't have dynamic array size when the type-id is in parentheses.
1336 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1337 << ArraySize->getSourceRange()
1338 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1339 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001340
Douglas Gregor4bd40312010-07-13 15:54:32 +00001341 TypeIdParens = SourceRange();
Sebastian Redl28507842009-02-26 14:39:58 +00001342 }
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001343 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001344
John McCall7d166272011-05-15 07:14:44 +00001345 // Note that we do *not* convert the argument in any way. It can
1346 // be signed, larger than size_t, whatever.
Sebastian Redlcee63fb2008-12-02 14:43:59 +00001347 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001348
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001349 FunctionDecl *OperatorNew = 0;
1350 FunctionDecl *OperatorDelete = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001351
Sebastian Redl28507842009-02-26 14:39:58 +00001352 if (!AllocType->isDependentType() &&
Dmitri Gribenkodaaa4682013-05-10 13:22:23 +00001353 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl28507842009-02-26 14:39:58 +00001354 FindAllocationFunctions(StartLoc,
Sebastian Redl00e68e22009-02-09 18:24:27 +00001355 SourceRange(PlacementLParen, PlacementRParen),
Dmitri Gribenkodaaa4682013-05-10 13:22:23 +00001356 UseGlobal, AllocType, ArraySize, PlacementArgs,
1357 OperatorNew, OperatorDelete))
Sebastian Redlf53597f2009-03-15 17:47:39 +00001358 return ExprError();
John McCall6ec278d2011-01-27 09:37:56 +00001359
1360 // If this is an array allocation, compute whether the usual array
1361 // deallocation function for the type has a size_t parameter.
1362 bool UsualArrayDeleteWantsSize = false;
1363 if (ArraySize && !AllocType->isDependentType())
1364 UsualArrayDeleteWantsSize
1365 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1366
Chris Lattner5f9e2722011-07-23 10:55:15 +00001367 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001368 if (OperatorNew) {
1369 // Add default arguments, if any.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001370 const FunctionProtoType *Proto =
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001371 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001372 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00001373 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001374
Dmitri Gribenkodaaa4682013-05-10 13:22:23 +00001375 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1,
1376 PlacementArgs, AllPlaceArgs, CallType))
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001377 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001378
Dmitri Gribenkodaaa4682013-05-10 13:22:23 +00001379 if (!AllPlaceArgs.empty())
1380 PlacementArgs = AllPlaceArgs;
Eli Friedmane61eb042012-02-18 04:48:30 +00001381
Dmitri Gribenkodaaa4682013-05-10 13:22:23 +00001382 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +00001383
1384 // FIXME: Missing call to CheckFunctionCall or equivalent
Fariborz Jahanian498429f2009-11-19 18:39:40 +00001385 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001386
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001387 // Warn if the type is over-aligned and is being allocated by global operator
1388 // new.
Dmitri Gribenkodaaa4682013-05-10 13:22:23 +00001389 if (PlacementArgs.empty() && OperatorNew &&
Nick Lewyckyfca84b22012-01-24 21:15:41 +00001390 (OperatorNew->isImplicit() ||
1391 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1392 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1393 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1394 if (Align > SuitableAlign)
1395 Diag(StartLoc, diag::warn_overaligned_type)
1396 << AllocType
1397 << unsigned(Align / Context.getCharWidth())
1398 << unsigned(SuitableAlign / Context.getCharWidth());
1399 }
1400 }
1401
Sebastian Redlbd45d252012-02-16 12:59:47 +00001402 QualType InitType = AllocType;
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001403 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlbd45d252012-02-16 12:59:47 +00001404 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1405 // dialect distinction.
1406 if (ResultType->isArrayType() || ArraySize) {
1407 if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1408 SourceRange InitRange(Inits[0]->getLocStart(),
1409 Inits[NumInits - 1]->getLocEnd());
1410 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1411 return ExprError();
1412 }
1413 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1414 // We do the initialization typechecking against the array type
1415 // corresponding to the number of initializers + 1 (to also check
1416 // default-initialization).
1417 unsigned NumElements = ILE->getNumInits() + 1;
1418 InitType = Context.getConstantArrayType(AllocType,
1419 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1420 ArrayType::Normal, 0);
1421 }
Anders Carlsson48c95012010-05-03 15:45:23 +00001422 }
1423
Richard Smith73ed67c2012-11-26 08:32:48 +00001424 // If we can perform the initialization, and we've not already done so,
1425 // do it now.
Douglas Gregor99a2e602009-12-16 01:38:02 +00001426 if (!AllocType->isDependentType() &&
Ahmed Charles13a140c2012-02-25 11:00:22 +00001427 !Expr::hasAnyTypeDependentArguments(
Richard Smith73ed67c2012-11-26 08:32:48 +00001428 llvm::makeArrayRef(Inits, NumInits)) &&
1429 !HaveCompleteInit) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001430 // C++11 [expr.new]p15:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001431 // A new-expression that creates an object of type T initializes that
1432 // object as follows:
1433 InitializationKind Kind
1434 // - If the new-initializer is omitted, the object is default-
1435 // initialized (8.5); if no initialization is performed,
1436 // the object has indeterminate value
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001437 = initStyle == CXXNewExpr::NoInit
1438 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001439 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor99a2e602009-12-16 01:38:02 +00001440 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001441 : initStyle == CXXNewExpr::ListInit
1442 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1443 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1444 DirectInitRange.getBegin(),
1445 DirectInitRange.getEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001446
Douglas Gregor99a2e602009-12-16 01:38:02 +00001447 InitializedEntity Entity
Sebastian Redlbd45d252012-02-16 12:59:47 +00001448 = InitializedEntity::InitializeNew(StartLoc, InitType);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00001449 InitializationSequence InitSeq(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001450 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001451 MultiExprArg(Inits, NumInits));
Douglas Gregor99a2e602009-12-16 01:38:02 +00001452 if (FullInit.isInvalid())
1453 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001454
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001455 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1456 // we don't want the initialized object to be destructed.
1457 if (CXXBindTemporaryExpr *Binder =
1458 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1459 FullInit = Owned(Binder->getSubExpr());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001460
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001461 Initializer = FullInit.take();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001462 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001463
Douglas Gregor6d908702010-02-26 05:06:18 +00001464 // Mark the new and delete operators as referenced.
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00001465 if (OperatorNew) {
Richard Smith82f145d2013-05-04 06:44:46 +00001466 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1467 return ExprError();
Eli Friedman5f2987c2012-02-02 03:46:19 +00001468 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00001469 }
1470 if (OperatorDelete) {
Richard Smith82f145d2013-05-04 06:44:46 +00001471 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1472 return ExprError();
Eli Friedman5f2987c2012-02-02 03:46:19 +00001473 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00001474 }
Douglas Gregor6d908702010-02-26 05:06:18 +00001475
John McCall84ff0fc2011-07-13 20:12:57 +00001476 // C++0x [expr.new]p17:
1477 // If the new expression creates an array of objects of class type,
1478 // access and ambiguity control are done for the destructor.
David Blaikie426d6ca2012-03-10 23:40:02 +00001479 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1480 if (ArraySize && !BaseAllocType->isDependentType()) {
1481 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1482 if (CXXDestructorDecl *dtor = LookupDestructor(
1483 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1484 MarkFunctionReferenced(StartLoc, dtor);
1485 CheckDestructorAccess(StartLoc, dtor,
1486 PDiag(diag::err_access_dtor)
1487 << BaseAllocType);
Richard Smith82f145d2013-05-04 06:44:46 +00001488 if (DiagnoseUseOfDecl(dtor, StartLoc))
1489 return ExprError();
David Blaikie426d6ca2012-03-10 23:40:02 +00001490 }
John McCall84ff0fc2011-07-13 20:12:57 +00001491 }
1492 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001493
Ted Kremenekad7fe862010-02-11 22:51:03 +00001494 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00001495 OperatorDelete,
John McCall6ec278d2011-01-27 09:37:56 +00001496 UsualArrayDeleteWantsSize,
Dmitri Gribenkodaaa4682013-05-10 13:22:23 +00001497 PlacementArgs, TypeIdParens,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001498 ArraySize, initStyle, Initializer,
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001499 ResultType, AllocTypeInfo,
David Blaikie53056412012-11-07 00:12:38 +00001500 Range, DirectInitRange));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001501}
1502
Sebastian Redl2aed8b82012-02-16 12:22:20 +00001503/// \brief Checks that a type is suitable as the allocated type
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001504/// in a new-expression.
Douglas Gregor3433cf72009-05-21 00:00:09 +00001505bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00001506 SourceRange R) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001507 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1508 // abstract class type or array thereof.
Douglas Gregore7450f52009-03-24 19:52:54 +00001509 if (AllocType->isFunctionType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001510 return Diag(Loc, diag::err_bad_new_type)
1511 << AllocType << 0 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001512 else if (AllocType->isReferenceType())
Douglas Gregor3433cf72009-05-21 00:00:09 +00001513 return Diag(Loc, diag::err_bad_new_type)
1514 << AllocType << 1 << R;
Douglas Gregore7450f52009-03-24 19:52:54 +00001515 else if (!AllocType->isDependentType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001516 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001517 return true;
Douglas Gregor3433cf72009-05-21 00:00:09 +00001518 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregore7450f52009-03-24 19:52:54 +00001519 diag::err_allocation_of_abstract_type))
1520 return true;
Douglas Gregora0750762010-10-06 16:00:31 +00001521 else if (AllocType->isVariablyModifiedType())
1522 return Diag(Loc, diag::err_variably_modified_new_type)
1523 << AllocType;
Douglas Gregor5666d362011-04-15 19:46:20 +00001524 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1525 return Diag(Loc, diag::err_address_space_qualified_new)
1526 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikie4e4d0842012-03-11 07:00:24 +00001527 else if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00001528 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1529 QualType BaseAllocType = Context.getBaseElementType(AT);
1530 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1531 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001532 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001533 << BaseAllocType;
1534 }
1535 }
Douglas Gregor5666d362011-04-15 19:46:20 +00001536
Sebastian Redl4c5d3202008-11-21 19:14:01 +00001537 return false;
1538}
1539
Douglas Gregor6d908702010-02-26 05:06:18 +00001540/// \brief Determine whether the given function is a non-placement
1541/// deallocation function.
1542static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1543 if (FD->isInvalidDecl())
1544 return false;
1545
1546 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1547 return Method->isUsualDeallocationFunction();
1548
1549 return ((FD->getOverloadedOperator() == OO_Delete ||
1550 FD->getOverloadedOperator() == OO_Array_Delete) &&
1551 FD->getNumParams() == 1);
1552}
1553
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001554/// FindAllocationFunctions - Finds the overloads of operator new and delete
1555/// that are appropriate for the allocation.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001556bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1557 bool UseGlobal, QualType AllocType,
Dmitri Gribenkodaaa4682013-05-10 13:22:23 +00001558 bool IsArray, MultiExprArg PlaceArgs,
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001559 FunctionDecl *&OperatorNew,
Mike Stump1eb44332009-09-09 15:08:12 +00001560 FunctionDecl *&OperatorDelete) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001561 // --- Choosing an allocation function ---
1562 // C++ 5.3.4p8 - 14 & 18
1563 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1564 // in the scope of the allocated class.
1565 // 2) If an array size is given, look for operator new[], else look for
1566 // operator new.
1567 // 3) The first argument is always size_t. Append the arguments from the
1568 // placement form.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001569
Dmitri Gribenkodaaa4682013-05-10 13:22:23 +00001570 SmallVector<Expr*, 8> AllocArgs(1 + PlaceArgs.size());
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001571 // We don't care about the actual value of this argument.
1572 // FIXME: Should the Sema create the expression and embed it in the syntax
1573 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00001574 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001575 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssond67c4c32009-08-16 20:29:29 +00001576 Context.getSizeType(),
1577 SourceLocation());
1578 AllocArgs[0] = &Size;
Dmitri Gribenkodaaa4682013-05-10 13:22:23 +00001579 std::copy(PlaceArgs.begin(), PlaceArgs.end(), AllocArgs.begin() + 1);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001580
Douglas Gregor6d908702010-02-26 05:06:18 +00001581 // C++ [expr.new]p8:
1582 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001583 // function's name is operator new and the deallocation function's
Douglas Gregor6d908702010-02-26 05:06:18 +00001584 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001585 // type, the allocation function's name is operator new[] and the
1586 // deallocation function's name is operator delete[].
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001587 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1588 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6d908702010-02-26 05:06:18 +00001589 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1590 IsArray ? OO_Array_Delete : OO_Delete);
1591
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001592 QualType AllocElemType = Context.getBaseElementType(AllocType);
1593
1594 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump1eb44332009-09-09 15:08:12 +00001595 CXXRecordDecl *Record
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001596 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Dmitri Gribenkoa7b7d0e2013-05-10 00:20:06 +00001597 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, Record,
1598 /*AllowMissing=*/true, OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001599 return true;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001600 }
Aaron Ballman5537e0a2013-05-30 01:55:39 +00001601
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001602 if (!OperatorNew) {
1603 // Didn't find a member overload. Look for a global one.
1604 DeclareGlobalNewDelete();
Sebastian Redl7f662392008-12-04 22:20:51 +00001605 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Aaron Ballman5537e0a2013-05-30 01:55:39 +00001606 bool FallbackEnabled = IsArray && Context.getLangOpts().MicrosoftMode;
Dmitri Gribenkoa7b7d0e2013-05-10 00:20:06 +00001607 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
Aaron Ballman5537e0a2013-05-30 01:55:39 +00001608 /*AllowMissing=*/FallbackEnabled, OperatorNew,
1609 /*Diagnose=*/!FallbackEnabled)) {
1610 if (!FallbackEnabled)
1611 return true;
1612
1613 // MSVC will fall back on trying to find a matching global operator new
1614 // if operator new[] cannot be found. Also, MSVC will leak by not
1615 // generating a call to operator delete or operator delete[], but we
1616 // will not replicate that bug.
1617 NewName = Context.DeclarationNames.getCXXOperatorName(OO_New);
1618 DeleteName = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
1619 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
Dmitri Gribenkoa7b7d0e2013-05-10 00:20:06 +00001620 /*AllowMissing=*/false, OperatorNew))
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001621 return true;
Aaron Ballman5537e0a2013-05-30 01:55:39 +00001622 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001623 }
1624
John McCall9c82afc2010-04-20 02:18:25 +00001625 // We don't need an operator delete if we're running under
1626 // -fno-exceptions.
David Blaikie4e4d0842012-03-11 07:00:24 +00001627 if (!getLangOpts().Exceptions) {
John McCall9c82afc2010-04-20 02:18:25 +00001628 OperatorDelete = 0;
1629 return false;
1630 }
1631
Anders Carlssond9583892009-05-31 20:26:12 +00001632 // FindAllocationOverload can change the passed in arguments, so we need to
1633 // copy them back.
Dmitri Gribenkodaaa4682013-05-10 13:22:23 +00001634 if (!PlaceArgs.empty())
1635 std::copy(AllocArgs.begin() + 1, AllocArgs.end(), PlaceArgs.data());
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Douglas Gregor6d908702010-02-26 05:06:18 +00001637 // C++ [expr.new]p19:
1638 //
1639 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001640 // deallocation function's name is looked up in the global
Douglas Gregor6d908702010-02-26 05:06:18 +00001641 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001642 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6d908702010-02-26 05:06:18 +00001643 // the scope of T. If this lookup fails to find the name, or if
1644 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi00995302011-01-27 07:09:49 +00001645 // deallocation function's name is looked up in the global scope.
Douglas Gregor6d908702010-02-26 05:06:18 +00001646 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001647 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001648 CXXRecordDecl *RD
Argyrios Kyrtzidisd2932982010-08-25 23:14:56 +00001649 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6d908702010-02-26 05:06:18 +00001650 LookupQualifiedName(FoundDelete, RD);
1651 }
John McCall90c8c572010-03-18 08:19:33 +00001652 if (FoundDelete.isAmbiguous())
1653 return true; // FIXME: clean up expressions?
Douglas Gregor6d908702010-02-26 05:06:18 +00001654
1655 if (FoundDelete.empty()) {
1656 DeclareGlobalNewDelete();
1657 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1658 }
1659
1660 FoundDelete.suppressDiagnostics();
John McCall9aa472c2010-03-19 07:35:19 +00001661
Chris Lattner5f9e2722011-07-23 10:55:15 +00001662 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCall9aa472c2010-03-19 07:35:19 +00001663
John McCalledeb6c92010-09-14 21:34:24 +00001664 // Whether we're looking for a placement operator delete is dictated
1665 // by whether we selected a placement operator new, not by whether
1666 // we had explicit placement arguments. This matters for things like
1667 // struct A { void *operator new(size_t, int = 0); ... };
1668 // A *a = new A()
Dmitri Gribenkodaaa4682013-05-10 13:22:23 +00001669 bool isPlacementNew = (!PlaceArgs.empty() || OperatorNew->param_size() != 1);
John McCalledeb6c92010-09-14 21:34:24 +00001670
1671 if (isPlacementNew) {
Douglas Gregor6d908702010-02-26 05:06:18 +00001672 // C++ [expr.new]p20:
1673 // A declaration of a placement deallocation function matches the
1674 // declaration of a placement allocation function if it has the
1675 // same number of parameters and, after parameter transformations
1676 // (8.3.5), all parameter types except the first are
1677 // identical. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001678 //
Douglas Gregor6d908702010-02-26 05:06:18 +00001679 // To perform this comparison, we compute the function type that
1680 // the deallocation function should have, and use that type both
1681 // for template argument deduction and for comparison purposes.
John McCalle23cf432010-12-14 08:05:40 +00001682 //
1683 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6d908702010-02-26 05:06:18 +00001684 QualType ExpectedFunctionType;
1685 {
1686 const FunctionProtoType *Proto
1687 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00001688
Chris Lattner5f9e2722011-07-23 10:55:15 +00001689 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001690 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6d908702010-02-26 05:06:18 +00001691 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1692 ArgTypes.push_back(Proto->getArgType(I));
1693
John McCalle23cf432010-12-14 08:05:40 +00001694 FunctionProtoType::ExtProtoInfo EPI;
1695 EPI.Variadic = Proto->isVariadic();
1696
Douglas Gregor6d908702010-02-26 05:06:18 +00001697 ExpectedFunctionType
Jordan Rosebea522f2013-03-08 21:51:21 +00001698 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6d908702010-02-26 05:06:18 +00001699 }
1700
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001701 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001702 DEnd = FoundDelete.end();
1703 D != DEnd; ++D) {
1704 FunctionDecl *Fn = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001705 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6d908702010-02-26 05:06:18 +00001706 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1707 // Perform template argument deduction to try to match the
1708 // expected function type.
Craig Topper93e45992012-09-19 02:26:47 +00001709 TemplateDeductionInfo Info(StartLoc);
Douglas Gregor6d908702010-02-26 05:06:18 +00001710 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1711 continue;
1712 } else
1713 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1714
1715 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCall9aa472c2010-03-19 07:35:19 +00001716 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001717 }
1718 } else {
1719 // C++ [expr.new]p20:
1720 // [...] Any non-placement deallocation function matches a
1721 // non-placement allocation function. [...]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001722 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6d908702010-02-26 05:06:18 +00001723 DEnd = FoundDelete.end();
1724 D != DEnd; ++D) {
1725 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1726 if (isNonPlacementDeallocationFunction(Fn))
John McCall9aa472c2010-03-19 07:35:19 +00001727 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6d908702010-02-26 05:06:18 +00001728 }
1729 }
1730
1731 // C++ [expr.new]p20:
1732 // [...] If the lookup finds a single matching deallocation
1733 // function, that function will be called; otherwise, no
1734 // deallocation function will be called.
1735 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00001736 OperatorDelete = Matches[0].second;
Douglas Gregor6d908702010-02-26 05:06:18 +00001737
1738 // C++0x [expr.new]p20:
1739 // If the lookup finds the two-parameter form of a usual
1740 // deallocation function (3.7.4.2) and that function, considered
1741 // as a placement deallocation function, would have been
1742 // selected as a match for the allocation function, the program
1743 // is ill-formed.
Dmitri Gribenkodaaa4682013-05-10 13:22:23 +00001744 if (!PlaceArgs.empty() && getLangOpts().CPlusPlus11 &&
Douglas Gregor6d908702010-02-26 05:06:18 +00001745 isNonPlacementDeallocationFunction(OperatorDelete)) {
1746 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
Dmitri Gribenkodaaa4682013-05-10 13:22:23 +00001747 << SourceRange(PlaceArgs.front()->getLocStart(),
1748 PlaceArgs.back()->getLocEnd());
Douglas Gregor6d908702010-02-26 05:06:18 +00001749 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1750 << DeleteName;
John McCall90c8c572010-03-18 08:19:33 +00001751 } else {
1752 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCall9aa472c2010-03-19 07:35:19 +00001753 Matches[0].first);
Douglas Gregor6d908702010-02-26 05:06:18 +00001754 }
1755 }
1756
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001757 return false;
1758}
1759
Sebastian Redl7f662392008-12-04 22:20:51 +00001760/// FindAllocationOverload - Find an fitting overload for the allocation
1761/// function in the specified scope.
Sebastian Redl00e68e22009-02-09 18:24:27 +00001762bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
Dmitri Gribenkoa7b7d0e2013-05-10 00:20:06 +00001763 DeclarationName Name, MultiExprArg Args,
1764 DeclContext *Ctx,
Sean Hunt2be7e902011-05-12 22:46:29 +00001765 bool AllowMissing, FunctionDecl *&Operator,
1766 bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00001767 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1768 LookupQualifiedName(R, Ctx);
John McCallf36e02d2009-10-09 21:13:30 +00001769 if (R.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001770 if (AllowMissing || !Diagnose)
Sebastian Redl7f662392008-12-04 22:20:51 +00001771 return false;
Sebastian Redl7f662392008-12-04 22:20:51 +00001772 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner4330d652009-02-17 07:29:20 +00001773 << Name << Range;
Sebastian Redl7f662392008-12-04 22:20:51 +00001774 }
1775
John McCall90c8c572010-03-18 08:19:33 +00001776 if (R.isAmbiguous())
1777 return true;
1778
1779 R.suppressDiagnostics();
John McCallf36e02d2009-10-09 21:13:30 +00001780
John McCall5769d612010-02-08 23:07:23 +00001781 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001782 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor5d64e5b2009-09-30 00:03:47 +00001783 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001784 // Even member operator new/delete are implicitly treated as
1785 // static, so don't use AddMemberCandidate.
John McCall9aa472c2010-03-19 07:35:19 +00001786 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001787
John McCall9aa472c2010-03-19 07:35:19 +00001788 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1789 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00001790 /*ExplicitTemplateArgs=*/0,
Dmitri Gribenkoa7b7d0e2013-05-10 00:20:06 +00001791 Args, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001792 /*SuppressUserConversions=*/false);
Douglas Gregor90916562009-09-29 18:16:17 +00001793 continue;
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001794 }
1795
John McCall9aa472c2010-03-19 07:35:19 +00001796 FunctionDecl *Fn = cast<FunctionDecl>(D);
Dmitri Gribenkoa7b7d0e2013-05-10 00:20:06 +00001797 AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001798 /*SuppressUserConversions=*/false);
Sebastian Redl7f662392008-12-04 22:20:51 +00001799 }
1800
1801 // Do the resolution.
1802 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00001803 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl7f662392008-12-04 22:20:51 +00001804 case OR_Success: {
1805 // Got one!
1806 FunctionDecl *FnDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00001807 MarkFunctionReferenced(StartLoc, FnDecl);
Sebastian Redl7f662392008-12-04 22:20:51 +00001808 // The first argument is size_t, and the first parameter must be size_t,
1809 // too. This is checked on declaration and can be assumed. (It can't be
1810 // asserted on, though, since invalid decls are left in there.)
John McCall90c8c572010-03-18 08:19:33 +00001811 // Watch out for variadic allocator function.
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00001812 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
Dmitri Gribenkoa7b7d0e2013-05-10 00:20:06 +00001813 for (unsigned i = 0; (i < Args.size() && i < NumArgsInFnDecl); ++i) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001814 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1815 FnDecl->getParamDecl(i));
1816
1817 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1818 return true;
1819
John McCall60d7b3a2010-08-24 06:29:42 +00001820 ExprResult Result
Sean Hunt2be7e902011-05-12 22:46:29 +00001821 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001822 if (Result.isInvalid())
Sebastian Redl7f662392008-12-04 22:20:51 +00001823 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001824
Douglas Gregor29ecaba2010-03-26 20:35:59 +00001825 Args[i] = Result.takeAs<Expr>();
Sebastian Redl7f662392008-12-04 22:20:51 +00001826 }
Richard Smith9a561d52012-02-26 09:11:52 +00001827
Sebastian Redl7f662392008-12-04 22:20:51 +00001828 Operator = FnDecl;
Richard Smith9a561d52012-02-26 09:11:52 +00001829
1830 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1831 Best->FoundDecl, Diagnose) == AR_inaccessible)
1832 return true;
1833
Sebastian Redl7f662392008-12-04 22:20:51 +00001834 return false;
1835 }
1836
1837 case OR_No_Viable_Function:
Chandler Carruth361d3802011-06-08 10:26:03 +00001838 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001839 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1840 << Name << Range;
Dmitri Gribenkoa7b7d0e2013-05-10 00:20:06 +00001841 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
Chandler Carruth361d3802011-06-08 10:26:03 +00001842 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001843 return true;
1844
1845 case OR_Ambiguous:
Chandler Carruth361d3802011-06-08 10:26:03 +00001846 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001847 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1848 << Name << Range;
Dmitri Gribenkoa7b7d0e2013-05-10 00:20:06 +00001849 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args);
Chandler Carruth361d3802011-06-08 10:26:03 +00001850 }
Sebastian Redl7f662392008-12-04 22:20:51 +00001851 return true;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001852
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001853 case OR_Deleted: {
Chandler Carruth361d3802011-06-08 10:26:03 +00001854 if (Diagnose) {
Sean Hunt2be7e902011-05-12 22:46:29 +00001855 Diag(StartLoc, diag::err_ovl_deleted_call)
1856 << Best->Function->isDeleted()
1857 << Name
1858 << getDeletedOrUnavailableSuffix(Best->Function)
1859 << Range;
Dmitri Gribenkoa7b7d0e2013-05-10 00:20:06 +00001860 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
Chandler Carruth361d3802011-06-08 10:26:03 +00001861 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001862 return true;
Sebastian Redl7f662392008-12-04 22:20:51 +00001863 }
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001864 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001865 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl7f662392008-12-04 22:20:51 +00001866}
1867
1868
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001869/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1870/// delete. These are:
1871/// @code
Sebastian Redl8999fe12011-03-14 18:08:30 +00001872/// // C++03:
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001873/// void* operator new(std::size_t) throw(std::bad_alloc);
1874/// void* operator new[](std::size_t) throw(std::bad_alloc);
1875/// void operator delete(void *) throw();
1876/// void operator delete[](void *) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001877/// // C++0x:
1878/// void* operator new(std::size_t);
1879/// void* operator new[](std::size_t);
1880/// void operator delete(void *);
1881/// void operator delete[](void *);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001882/// @endcode
Sebastian Redl8999fe12011-03-14 18:08:30 +00001883/// C++0x operator delete is implicitly noexcept.
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001884/// Note that the placement and nothrow forms of new are *not* implicitly
1885/// declared. Their use requires including \<new\>.
Mike Stump1eb44332009-09-09 15:08:12 +00001886void Sema::DeclareGlobalNewDelete() {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001887 if (GlobalNewDeleteDeclared)
1888 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001889
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001890 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001891 // [...] The following allocation and deallocation functions (18.4) are
1892 // implicitly declared in global scope in each translation unit of a
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001893 // program
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001894 //
Sebastian Redl8999fe12011-03-14 18:08:30 +00001895 // C++03:
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001896 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001897 // void* operator new[](std::size_t) throw(std::bad_alloc);
1898 // void operator delete(void*) throw();
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001899 // void operator delete[](void*) throw();
Sebastian Redl8999fe12011-03-14 18:08:30 +00001900 // C++0x:
1901 // void* operator new(std::size_t);
1902 // void* operator new[](std::size_t);
1903 // void operator delete(void*);
1904 // void operator delete[](void*);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001905 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001906 // These implicit declarations introduce only the function names operator
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001907 // new, operator new[], operator delete, operator delete[].
1908 //
1909 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1910 // "std" or "bad_alloc" as necessary to form the exception specification.
1911 // However, we do not make these implicit declarations visible to name
1912 // lookup.
Sebastian Redl8999fe12011-03-14 18:08:30 +00001913 // Note that the C++0x versions of operator delete are deallocation functions,
1914 // and thus are implicitly noexcept.
Richard Smith80ad52f2013-01-02 11:42:31 +00001915 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001916 // The "std::bad_alloc" class has not yet been declared, so build it
1917 // implicitly.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001918 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1919 getOrCreateStdNamespace(),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001920 SourceLocation(), SourceLocation(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001921 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001922 0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001923 getStdBadAlloc()->setImplicit(true);
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001924 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001925
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001926 GlobalNewDeleteDeclared = true;
1927
1928 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1929 QualType SizeT = Context.getSizeType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001930 bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001931
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001932 DeclareGlobalAllocationFunction(
1933 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001934 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001935 DeclareGlobalAllocationFunction(
1936 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopesfc284482009-12-16 16:59:22 +00001937 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001938 DeclareGlobalAllocationFunction(
1939 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1940 Context.VoidTy, VoidPtr);
1941 DeclareGlobalAllocationFunction(
1942 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1943 Context.VoidTy, VoidPtr);
1944}
1945
1946/// DeclareGlobalAllocationFunction - Declares a single implicit global
1947/// allocation function if it doesn't already exist.
1948void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopesfc284482009-12-16 16:59:22 +00001949 QualType Return, QualType Argument,
1950 bool AddMallocAttr) {
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001951 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1952
1953 // Check if this function is already declared.
Serge Pavlov3225b9c2013-09-14 12:00:01 +00001954 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
1955 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
1956 Alloc != AllocEnd; ++Alloc) {
1957 // Only look at non-template functions, as it is the predefined,
1958 // non-templated allocation function we are trying to declare here.
1959 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1960 if (Func->getNumParams() == 1) {
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001961 QualType InitialParamType =
Douglas Gregor6e790ab2009-12-22 23:42:49 +00001962 Context.getCanonicalType(
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001963 Func->getParamDecl(0)->getType().getUnqualifiedType());
1964 // FIXME: Do we need to check for default arguments here?
Serge Pavlov3225b9c2013-09-14 12:00:01 +00001965 if (InitialParamType == Argument) {
Richard Smithace21ba2013-07-14 02:01:48 +00001966 if (AddMallocAttr && !Func->hasAttr<MallocAttr>())
Serge Pavlov3225b9c2013-09-14 12:00:01 +00001967 Func->addAttr(::new (Context) MallocAttr(SourceLocation(),
1968 Context));
1969 // Make the function visible to name lookup, even if we found it in
1970 // an unimported module. It either is an implicitly-declared global
Richard Smithace21ba2013-07-14 02:01:48 +00001971 // allocation function, or is suppressing that function.
1972 Func->setHidden(false);
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001973 return;
Douglas Gregor7b868622010-08-18 15:06:25 +00001974 }
Chandler Carruth4a73ea92010-02-03 11:02:14 +00001975 }
Sebastian Redlb5a57a62008-12-03 20:26:15 +00001976 }
1977 }
1978
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001979 QualType BadAllocType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001980 bool HasBadAllocExceptionSpec
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001981 = (Name.getCXXOverloadedOperator() == OO_New ||
1982 Name.getCXXOverloadedOperator() == OO_Array_New);
Richard Smith80ad52f2013-01-02 11:42:31 +00001983 if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus11) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001984 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00001985 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor7adb10f2009-09-15 22:30:29 +00001986 }
John McCalle23cf432010-12-14 08:05:40 +00001987
1988 FunctionProtoType::ExtProtoInfo EPI;
John McCalle23cf432010-12-14 08:05:40 +00001989 if (HasBadAllocExceptionSpec) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001990 if (!getLangOpts().CPlusPlus11) {
Sebastian Redl8999fe12011-03-14 18:08:30 +00001991 EPI.ExceptionSpecType = EST_Dynamic;
1992 EPI.NumExceptions = 1;
1993 EPI.Exceptions = &BadAllocType;
1994 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00001995 } else {
Richard Smith80ad52f2013-01-02 11:42:31 +00001996 EPI.ExceptionSpecType = getLangOpts().CPlusPlus11 ?
Sebastian Redl8999fe12011-03-14 18:08:30 +00001997 EST_BasicNoexcept : EST_DynamicNone;
John McCalle23cf432010-12-14 08:05:40 +00001998 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001999
Jordan Rosebea522f2013-03-08 21:51:21 +00002000 QualType FnType = Context.getFunctionType(Return, Argument, EPI);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00002001 FunctionDecl *Alloc =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002002 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
2003 SourceLocation(), Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002004 FnType, /*TInfo=*/0, SC_None, false, true);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00002005 Alloc->setImplicit();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002006
Nuno Lopesfc284482009-12-16 16:59:22 +00002007 if (AddMallocAttr)
Sean Huntcf807c42010-08-18 23:23:40 +00002008 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002009
Sebastian Redlb5a57a62008-12-03 20:26:15 +00002010 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002011 SourceLocation(), 0,
2012 Argument, /*TInfo=*/0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002013 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00002014 Alloc->setParams(Param);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00002015
Douglas Gregor6ed40e32008-12-23 21:05:05 +00002016 // FIXME: Also add this declaration to the IdentifierResolver, but
2017 // make sure it is at the end of the chain to coincide with the
2018 // global scope.
John McCall5f1e0942010-08-24 08:50:51 +00002019 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlb5a57a62008-12-03 20:26:15 +00002020}
2021
Anders Carlsson78f74552009-11-15 18:45:20 +00002022bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2023 DeclarationName Name,
Sean Hunt2be7e902011-05-12 22:46:29 +00002024 FunctionDecl* &Operator, bool Diagnose) {
John McCalla24dc2e2009-11-17 02:14:36 +00002025 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlsson78f74552009-11-15 18:45:20 +00002026 // Try to find operator delete/operator delete[] in class scope.
John McCalla24dc2e2009-11-17 02:14:36 +00002027 LookupQualifiedName(Found, RD);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002028
John McCalla24dc2e2009-11-17 02:14:36 +00002029 if (Found.isAmbiguous())
Anders Carlsson78f74552009-11-15 18:45:20 +00002030 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00002031
Chandler Carruth23893242010-06-28 00:30:51 +00002032 Found.suppressDiagnostics();
2033
Chris Lattner5f9e2722011-07-23 10:55:15 +00002034 SmallVector<DeclAccessPair,4> Matches;
Anders Carlsson78f74552009-11-15 18:45:20 +00002035 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2036 F != FEnd; ++F) {
Chandler Carruth09556fd2010-08-08 07:04:00 +00002037 NamedDecl *ND = (*F)->getUnderlyingDecl();
2038
2039 // Ignore template operator delete members from the check for a usual
2040 // deallocation function.
2041 if (isa<FunctionTemplateDecl>(ND))
2042 continue;
2043
2044 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall046a7462010-08-04 00:31:26 +00002045 Matches.push_back(F.getPair());
2046 }
2047
2048 // There's exactly one suitable operator; pick it.
2049 if (Matches.size() == 1) {
2050 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Sean Hunt2be7e902011-05-12 22:46:29 +00002051
2052 if (Operator->isDeleted()) {
2053 if (Diagnose) {
2054 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith6c4c36c2012-03-30 20:53:28 +00002055 NoteDeletedFunction(Operator);
Sean Hunt2be7e902011-05-12 22:46:29 +00002056 }
2057 return true;
2058 }
2059
Richard Smith9a561d52012-02-26 09:11:52 +00002060 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2061 Matches[0], Diagnose) == AR_inaccessible)
2062 return true;
2063
John McCall046a7462010-08-04 00:31:26 +00002064 return false;
2065
2066 // We found multiple suitable operators; complain about the ambiguity.
2067 } else if (!Matches.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00002068 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00002069 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2070 << Name << RD;
John McCall046a7462010-08-04 00:31:26 +00002071
Chris Lattner5f9e2722011-07-23 10:55:15 +00002072 for (SmallVectorImpl<DeclAccessPair>::iterator
Sean Huntcb45a0f2011-05-12 22:46:25 +00002073 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
2074 Diag((*F)->getUnderlyingDecl()->getLocation(),
2075 diag::note_member_declared_here) << Name;
2076 }
John McCall046a7462010-08-04 00:31:26 +00002077 return true;
Anders Carlsson78f74552009-11-15 18:45:20 +00002078 }
2079
2080 // We did find operator delete/operator delete[] declarations, but
2081 // none of them were suitable.
2082 if (!Found.empty()) {
Sean Hunt2be7e902011-05-12 22:46:29 +00002083 if (Diagnose) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00002084 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2085 << Name << RD;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002086
Sean Huntcb45a0f2011-05-12 22:46:25 +00002087 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2088 F != FEnd; ++F)
2089 Diag((*F)->getUnderlyingDecl()->getLocation(),
2090 diag::note_member_declared_here) << Name;
2091 }
Anders Carlsson78f74552009-11-15 18:45:20 +00002092 return true;
2093 }
2094
2095 // Look for a global declaration.
2096 DeclareGlobalNewDelete();
2097 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002098
Anders Carlsson78f74552009-11-15 18:45:20 +00002099 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
Dmitri Gribenkoa7b7d0e2013-05-10 00:20:06 +00002100 Expr *DeallocArgs[1] = { &Null };
Anders Carlsson78f74552009-11-15 18:45:20 +00002101 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Dmitri Gribenkoa7b7d0e2013-05-10 00:20:06 +00002102 DeallocArgs, TUDecl, !Diagnose,
Sean Hunt2be7e902011-05-12 22:46:29 +00002103 Operator, Diagnose))
Anders Carlsson78f74552009-11-15 18:45:20 +00002104 return true;
2105
2106 assert(Operator && "Did not find a deallocation function!");
2107 return false;
2108}
2109
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002110/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2111/// @code ::delete ptr; @endcode
2112/// or
2113/// @code delete [] ptr; @endcode
John McCall60d7b3a2010-08-24 06:29:42 +00002114ExprResult
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002115Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley429bb272011-04-08 18:41:53 +00002116 bool ArrayForm, Expr *ExE) {
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002117 // C++ [expr.delete]p1:
2118 // The operand shall have a pointer type, or a class type having a single
Richard Smith097e0a22013-05-21 19:05:48 +00002119 // non-explicit conversion function to a pointer type. The result has type
2120 // void.
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002121 //
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002122 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2123
John Wiegley429bb272011-04-08 18:41:53 +00002124 ExprResult Ex = Owned(ExE);
Anders Carlssond67c4c32009-08-16 20:29:29 +00002125 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002126 bool ArrayFormAsWritten = ArrayForm;
John McCall6ec278d2011-01-27 09:37:56 +00002127 bool UsualArrayDeleteWantsSize = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002128
John Wiegley429bb272011-04-08 18:41:53 +00002129 if (!Ex.get()->isTypeDependent()) {
John McCall5aba3eb2012-03-09 04:08:29 +00002130 // Perform lvalue-to-rvalue cast, if needed.
2131 Ex = DefaultLvalueConversion(Ex.take());
Eli Friedman206491d2012-12-13 00:37:17 +00002132 if (Ex.isInvalid())
2133 return ExprError();
John McCall5aba3eb2012-03-09 04:08:29 +00002134
John Wiegley429bb272011-04-08 18:41:53 +00002135 QualType Type = Ex.get()->getType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002136
Richard Smith097e0a22013-05-21 19:05:48 +00002137 class DeleteConverter : public ContextualImplicitConverter {
2138 public:
2139 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002140
Richard Smith097e0a22013-05-21 19:05:48 +00002141 bool match(QualType ConvType) {
2142 // FIXME: If we have an operator T* and an operator void*, we must pick
2143 // the operator T*.
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002144 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedman13578692010-08-05 02:49:48 +00002145 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smith097e0a22013-05-21 19:05:48 +00002146 return true;
2147 return false;
Douglas Gregor9cd9f3f2009-09-09 23:39:55 +00002148 }
Sebastian Redl28507842009-02-26 14:39:58 +00002149
Richard Smith097e0a22013-05-21 19:05:48 +00002150 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2151 QualType T) {
2152 return S.Diag(Loc, diag::err_delete_operand) << T;
2153 }
2154
2155 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2156 QualType T) {
2157 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
2158 }
2159
2160 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2161 QualType T, QualType ConvTy) {
2162 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
2163 }
2164
2165 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2166 QualType ConvTy) {
2167 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2168 << ConvTy;
2169 }
2170
2171 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2172 QualType T) {
2173 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
2174 }
2175
2176 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2177 QualType ConvTy) {
2178 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2179 << ConvTy;
2180 }
2181
2182 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2183 QualType T, QualType ConvTy) {
2184 llvm_unreachable("conversion functions are permitted");
2185 }
2186 } Converter;
2187
2188 Ex = PerformContextualImplicitConversion(StartLoc, Ex.take(), Converter);
2189 if (Ex.isInvalid())
2190 return ExprError();
2191 Type = Ex.get()->getType();
2192 if (!Converter.match(Type))
2193 // FIXME: PerformContextualImplicitConversion should return ExprError
2194 // itself in this case.
2195 return ExprError();
Sebastian Redl28507842009-02-26 14:39:58 +00002196
Ted Kremenek6217b802009-07-29 21:53:49 +00002197 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmane52c9142011-07-26 22:25:31 +00002198 QualType PointeeElem = Context.getBaseElementType(Pointee);
2199
2200 if (unsigned AddressSpace = Pointee.getAddressSpace())
2201 return Diag(Ex.get()->getLocStart(),
2202 diag::err_address_space_qualified_delete)
2203 << Pointee.getUnqualifiedType() << AddressSpace;
2204
2205 CXXRecordDecl *PointeeRD = 0;
Douglas Gregor94a61572010-05-24 17:01:56 +00002206 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002207 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregor94a61572010-05-24 17:01:56 +00002208 // effectively bans deletion of "void*". However, most compilers support
2209 // this, so we treat it as a warning unless we're in a SFINAE context.
2210 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002211 << Type << Ex.get()->getSourceRange();
Eli Friedmane52c9142011-07-26 22:25:31 +00002212 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00002213 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley429bb272011-04-08 18:41:53 +00002214 << Type << Ex.get()->getSourceRange());
Eli Friedmane52c9142011-07-26 22:25:31 +00002215 } else if (!Pointee->isDependentType()) {
2216 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregord10099e2012-05-04 16:32:21 +00002217 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmane52c9142011-07-26 22:25:31 +00002218 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2219 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2220 }
2221 }
2222
Douglas Gregor1070c9f2009-09-29 21:38:53 +00002223 // C++ [expr.delete]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002224 // [Note: a pointer to a const type can be the operand of a
2225 // delete-expression; it is not necessary to cast away the constness
2226 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor1070c9f2009-09-29 21:38:53 +00002227 // of the delete-expression. ]
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002228
2229 if (Pointee->isArrayType() && !ArrayForm) {
2230 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley429bb272011-04-08 18:41:53 +00002231 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis4076dac2010-09-13 20:15:54 +00002232 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2233 ArrayForm = true;
2234 }
2235
Anders Carlssond67c4c32009-08-16 20:29:29 +00002236 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2237 ArrayForm ? OO_Array_Delete : OO_Delete);
2238
Eli Friedmane52c9142011-07-26 22:25:31 +00002239 if (PointeeRD) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002240 if (!UseGlobal &&
Eli Friedmane52c9142011-07-26 22:25:31 +00002241 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2242 OperatorDelete))
Anders Carlsson0ba63ea2009-11-14 03:17:38 +00002243 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002244
John McCall6ec278d2011-01-27 09:37:56 +00002245 // If we're allocating an array of records, check whether the
2246 // usual operator delete[] has a size_t parameter.
2247 if (ArrayForm) {
2248 // If the user specifically asked to use the global allocator,
2249 // we'll need to do the lookup into the class.
2250 if (UseGlobal)
2251 UsualArrayDeleteWantsSize =
2252 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2253
2254 // Otherwise, the usual operator delete[] should be the
2255 // function we just found.
2256 else if (isa<CXXMethodDecl>(OperatorDelete))
2257 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2258 }
2259
Richard Smith213d70b2012-02-18 04:13:32 +00002260 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmane52c9142011-07-26 22:25:31 +00002261 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002262 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian34374e62009-09-03 23:18:17 +00002263 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith82f145d2013-05-04 06:44:46 +00002264 if (DiagnoseUseOfDecl(Dtor, StartLoc))
2265 return ExprError();
Douglas Gregor9b623632010-10-12 23:32:35 +00002266 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00002267
2268 // C++ [expr.delete]p3:
2269 // In the first alternative (delete object), if the static type of the
2270 // object to be deleted is different from its dynamic type, the static
2271 // type shall be a base class of the dynamic type of the object to be
2272 // deleted and the static type shall have a virtual destructor or the
2273 // behavior is undefined.
2274 //
2275 // Note: a final class cannot be derived from, no issue there
Eli Friedmanef8c79c2011-07-26 23:27:24 +00002276 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmane52c9142011-07-26 22:25:31 +00002277 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedmanef8c79c2011-07-26 23:27:24 +00002278 if (dtor && !dtor->isVirtual()) {
2279 if (PointeeRD->isAbstract()) {
2280 // If the class is abstract, we warn by default, because we're
2281 // sure the code has undefined behavior.
2282 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2283 << PointeeElem;
2284 } else if (!ArrayForm) {
2285 // Otherwise, if this is not an array delete, it's a bit suspect,
2286 // but not necessarily wrong.
2287 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2288 }
2289 }
Argyrios Kyrtzidis6f0074a2011-05-24 19:53:26 +00002290 }
John McCallf85e1932011-06-15 23:02:42 +00002291
Anders Carlssond67c4c32009-08-16 20:29:29 +00002292 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002293
Anders Carlssond67c4c32009-08-16 20:29:29 +00002294 if (!OperatorDelete) {
Anders Carlsson78f74552009-11-15 18:45:20 +00002295 // Look for a global declaration.
Anders Carlssond67c4c32009-08-16 20:29:29 +00002296 DeclareGlobalNewDelete();
2297 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley429bb272011-04-08 18:41:53 +00002298 Expr *Arg = Ex.get();
Abramo Bagnara34f60a42012-07-09 21:15:43 +00002299 if (!Context.hasSameType(Arg->getType(), Context.VoidPtrTy))
2300 Arg = ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
2301 CK_BitCast, Arg, 0, VK_RValue);
Dmitri Gribenkoa7b7d0e2013-05-10 00:20:06 +00002302 Expr *DeallocArgs[1] = { Arg };
Mike Stump1eb44332009-09-09 15:08:12 +00002303 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
Dmitri Gribenkoa7b7d0e2013-05-10 00:20:06 +00002304 DeallocArgs, TUDecl, /*AllowMissing=*/false,
Anders Carlssond67c4c32009-08-16 20:29:29 +00002305 OperatorDelete))
2306 return ExprError();
2307 }
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Eli Friedman5f2987c2012-02-02 03:46:19 +00002309 MarkFunctionReferenced(StartLoc, OperatorDelete);
John McCall6ec278d2011-01-27 09:37:56 +00002310
Douglas Gregord880f522011-02-01 15:50:11 +00002311 // Check access and ambiguity of operator delete and destructor.
Eli Friedmane52c9142011-07-26 22:25:31 +00002312 if (PointeeRD) {
2313 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley429bb272011-04-08 18:41:53 +00002314 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregord880f522011-02-01 15:50:11 +00002315 PDiag(diag::err_access_dtor) << PointeeElem);
2316 }
2317 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002318 }
2319
Sebastian Redlf53597f2009-03-15 17:47:39 +00002320 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall6ec278d2011-01-27 09:37:56 +00002321 ArrayFormAsWritten,
2322 UsualArrayDeleteWantsSize,
John Wiegley429bb272011-04-08 18:41:53 +00002323 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002324}
2325
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002326/// \brief Check the use of the given variable as a C++ condition in an if,
2327/// while, do-while, or switch statement.
John McCall60d7b3a2010-08-24 06:29:42 +00002328ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCallf89e55a2010-11-18 06:31:45 +00002329 SourceLocation StmtLoc,
2330 bool ConvertToBoolean) {
Richard Smithdc7a4f52013-04-30 13:56:41 +00002331 if (ConditionVar->isInvalidDecl())
2332 return ExprError();
2333
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002334 QualType T = ConditionVar->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002335
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002336 // C++ [stmt.select]p2:
2337 // The declarator shall not specify a function or an array.
2338 if (T->isFunctionType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002339 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002340 diag::err_invalid_use_of_function_type)
2341 << ConditionVar->getSourceRange());
2342 else if (T->isArrayType())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002343 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002344 diag::err_invalid_use_of_array_type)
2345 << ConditionVar->getSourceRange());
Douglas Gregora7605db2009-11-24 16:07:02 +00002346
John Wiegley429bb272011-04-08 18:41:53 +00002347 ExprResult Condition =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002348 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2349 SourceLocation(),
2350 ConditionVar,
John McCallf4b88a42012-03-10 09:33:50 +00002351 /*enclosing*/ false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002352 ConditionVar->getLocation(),
2353 ConditionVar->getType().getNonReferenceType(),
John Wiegley429bb272011-04-08 18:41:53 +00002354 VK_LValue));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002355
Eli Friedman5f2987c2012-02-02 03:46:19 +00002356 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002357
John Wiegley429bb272011-04-08 18:41:53 +00002358 if (ConvertToBoolean) {
2359 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2360 if (Condition.isInvalid())
2361 return ExprError();
2362 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002363
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002364 return Condition;
Douglas Gregor8cfe5a72009-11-23 23:44:04 +00002365}
2366
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002367/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley429bb272011-04-08 18:41:53 +00002368ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002369 // C++ 6.4p4:
2370 // The value of a condition that is an initialized declaration in a statement
2371 // other than a switch statement is the value of the declared variable
2372 // implicitly converted to type bool. If that conversion is ill-formed, the
2373 // program is ill-formed.
2374 // The value of a condition that is an expression is the value of the
2375 // expression, implicitly converted to bool.
2376 //
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002377 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis59210932008-09-10 02:17:11 +00002378}
Douglas Gregor77a52232008-09-12 00:47:35 +00002379
2380/// Helper function to determine whether this is the (deprecated) C++
2381/// conversion from a string literal to a pointer to non-const char or
2382/// non-const wchar_t (for narrow and wide string literals,
2383/// respectively).
Mike Stump1eb44332009-09-09 15:08:12 +00002384bool
Douglas Gregor77a52232008-09-12 00:47:35 +00002385Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2386 // Look inside the implicit cast, if it exists.
2387 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2388 From = Cast->getSubExpr();
2389
2390 // A string literal (2.13.4) that is not a wide string literal can
2391 // be converted to an rvalue of type "pointer to char"; a wide
2392 // string literal can be converted to an rvalue of type "pointer
2393 // to wchar_t" (C++ 4.2p2).
Douglas Gregor1984eb92010-06-22 23:47:37 +00002394 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenek6217b802009-07-29 21:53:49 +00002395 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00002396 if (const BuiltinType *ToPointeeType
John McCall183700f2009-09-21 23:43:11 +00002397 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregor77a52232008-09-12 00:47:35 +00002398 // This conversion is considered only when there is an
2399 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregor5cee1192011-07-27 05:40:30 +00002400 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2401 switch (StrLit->getKind()) {
2402 case StringLiteral::UTF8:
2403 case StringLiteral::UTF16:
2404 case StringLiteral::UTF32:
2405 // We don't allow UTF literals to be implicitly converted
2406 break;
2407 case StringLiteral::Ascii:
2408 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2409 ToPointeeType->getKind() == BuiltinType::Char_S);
2410 case StringLiteral::Wide:
2411 return ToPointeeType->isWideCharType();
2412 }
2413 }
Douglas Gregor77a52232008-09-12 00:47:35 +00002414 }
2415
2416 return false;
2417}
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002418
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002419static ExprResult BuildCXXCastArgument(Sema &S,
John McCall2de56d12010-08-25 11:45:40 +00002420 SourceLocation CastLoc,
2421 QualType Ty,
2422 CastKind Kind,
2423 CXXMethodDecl *Method,
John McCallca82a822011-09-21 08:36:56 +00002424 DeclAccessPair FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002425 bool HadMultipleCandidates,
John McCall2de56d12010-08-25 11:45:40 +00002426 Expr *From) {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002427 switch (Kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002428 default: llvm_unreachable("Unhandled cast kind!");
John McCall2de56d12010-08-25 11:45:40 +00002429 case CK_ConstructorConversion: {
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002430 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002431 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002432
Richard Smithcfc57082013-07-20 19:41:36 +00002433 if (S.RequireNonAbstractType(CastLoc, Ty,
2434 diag::err_allocation_of_abstract_type))
2435 return ExprError();
2436
Benjamin Kramer5354e772012-08-23 23:38:35 +00002437 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00002438 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002439
John McCallb9abd8722012-04-07 03:04:20 +00002440 S.CheckConstructorAccess(CastLoc, Constructor,
2441 InitializedEntity::InitializeTemporary(Ty),
2442 Constructor->getAccess());
Richard Smithc83c2302012-12-19 01:39:02 +00002443
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002444 ExprResult Result
2445 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
Richard Smithc83c2302012-12-19 01:39:02 +00002446 ConstructorArgs, HadMultipleCandidates,
2447 /*ListInit*/ false, /*ZeroInit*/ false,
Douglas Gregor13e1bca2011-10-10 22:41:00 +00002448 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002449 if (Result.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00002450 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002451
Douglas Gregorba70ab62010-04-16 22:17:36 +00002452 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2453 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002454
John McCall2de56d12010-08-25 11:45:40 +00002455 case CK_UserDefinedConversion: {
Douglas Gregorba70ab62010-04-16 22:17:36 +00002456 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002457
Douglas Gregorba70ab62010-04-16 22:17:36 +00002458 // Create an implicit call expr that calls it.
Eli Friedman3f01c8a2012-03-01 01:30:04 +00002459 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2460 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002461 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002462 if (Result.isInvalid())
2463 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00002464 // Record usage of conversion in an implicit cast.
2465 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2466 Result.get()->getType(),
2467 CK_UserDefinedConversion,
2468 Result.get(), 0,
2469 Result.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002470
John McCallca82a822011-09-21 08:36:56 +00002471 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2472
Douglas Gregorf2ae5262011-01-20 00:18:04 +00002473 return S.MaybeBindToTemporary(Result.get());
Douglas Gregorba70ab62010-04-16 22:17:36 +00002474 }
2475 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002476}
Douglas Gregorba70ab62010-04-16 22:17:36 +00002477
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002478/// PerformImplicitConversion - Perform an implicit conversion of the
2479/// expression From to the type ToType using the pre-computed implicit
John Wiegley429bb272011-04-08 18:41:53 +00002480/// conversion sequence ICS. Returns the converted
Douglas Gregor68647482009-12-16 03:45:30 +00002481/// expression. Action is the kind of conversion we're performing,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002482/// used in the error message.
John Wiegley429bb272011-04-08 18:41:53 +00002483ExprResult
2484Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002485 const ImplicitConversionSequence &ICS,
John McCallf85e1932011-06-15 23:02:42 +00002486 AssignmentAction Action,
2487 CheckedConversionKind CCK) {
John McCall1d318332010-01-12 00:44:57 +00002488 switch (ICS.getKind()) {
John Wiegley429bb272011-04-08 18:41:53 +00002489 case ImplicitConversionSequence::StandardConversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002490 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2491 Action, CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002492 if (Res.isInvalid())
2493 return ExprError();
2494 From = Res.take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002495 break;
John Wiegley429bb272011-04-08 18:41:53 +00002496 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002497
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002498 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002499
Fariborz Jahanian7fe5d722009-08-28 22:04:50 +00002500 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCalldaa8e4e2010-11-15 09:13:47 +00002501 CastKind CastKind;
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002502 QualType BeforeToType;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002503 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002504 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCall2de56d12010-08-25 11:45:40 +00002505 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002506
Anders Carlssonf6c213a2009-09-15 06:28:28 +00002507 // If the user-defined conversion is specified by a conversion function,
2508 // the initial standard conversion sequence converts the source type to
2509 // the implicit object parameter of the conversion function.
2510 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCall9ec94452010-12-04 09:57:16 +00002511 } else {
2512 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCall2de56d12010-08-25 11:45:40 +00002513 CastKind = CK_ConstructorConversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002514 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregore44201a2009-11-20 02:31:03 +00002515 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002516 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002517 // initial standard conversion sequence converts the source type to the
2518 // type required by the argument of the constructor
Douglas Gregore44201a2009-11-20 02:31:03 +00002519 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2520 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002521 }
Richard Smithcfc57082013-07-20 19:41:36 +00002522 // Watch out for ellipsis conversion.
Fariborz Jahanian4c0cea22009-11-06 00:55:14 +00002523 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley429bb272011-04-08 18:41:53 +00002524 ExprResult Res =
Richard Smithc8d7f582011-11-29 22:48:16 +00002525 PerformImplicitConversion(From, BeforeToType,
2526 ICS.UserDefined.Before, AA_Converting,
2527 CCK);
John Wiegley429bb272011-04-08 18:41:53 +00002528 if (Res.isInvalid())
2529 return ExprError();
2530 From = Res.take();
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002531 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002532
2533 ExprResult CastArg
Douglas Gregorba70ab62010-04-16 22:17:36 +00002534 = BuildCXXCastArgument(*this,
2535 From->getLocStart(),
Anders Carlsson0aebc812009-09-09 21:33:21 +00002536 ToType.getNonReferenceType(),
Douglas Gregor83eecbe2011-01-20 01:32:05 +00002537 CastKind, cast<CXXMethodDecl>(FD),
2538 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002539 ICS.UserDefined.HadMultipleCandidates,
John McCall9ae2f072010-08-23 23:25:46 +00002540 From);
Anders Carlsson0aebc812009-09-09 21:33:21 +00002541
2542 if (CastArg.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002543 return ExprError();
Eli Friedmand8889622009-11-27 04:41:50 +00002544
John Wiegley429bb272011-04-08 18:41:53 +00002545 From = CastArg.take();
Eli Friedmand8889622009-11-27 04:41:50 +00002546
Richard Smithc8d7f582011-11-29 22:48:16 +00002547 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2548 AA_Converting, CCK);
Fariborz Jahanian93034ca2009-10-16 19:20:59 +00002549 }
John McCall1d318332010-01-12 00:44:57 +00002550
2551 case ImplicitConversionSequence::AmbiguousConversion:
John McCall120d63c2010-08-24 20:38:10 +00002552 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall1d318332010-01-12 00:44:57 +00002553 PDiag(diag::err_typecheck_ambiguous_condition)
2554 << From->getSourceRange());
John Wiegley429bb272011-04-08 18:41:53 +00002555 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002556
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002557 case ImplicitConversionSequence::EllipsisConversion:
David Blaikieb219cfc2011-09-23 05:06:16 +00002558 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002559
2560 case ImplicitConversionSequence::BadConversion:
John Wiegley429bb272011-04-08 18:41:53 +00002561 return ExprError();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002562 }
2563
2564 // Everything went well.
John Wiegley429bb272011-04-08 18:41:53 +00002565 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002566}
2567
Richard Smithc8d7f582011-11-29 22:48:16 +00002568/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002569/// expression From to the type ToType by following the standard
John Wiegley429bb272011-04-08 18:41:53 +00002570/// conversion sequence SCS. Returns the converted
Douglas Gregor45920e82008-12-19 17:40:08 +00002571/// expression. Flavor is the context in which we're performing this
2572/// conversion, for use in error messages.
John Wiegley429bb272011-04-08 18:41:53 +00002573ExprResult
Richard Smithc8d7f582011-11-29 22:48:16 +00002574Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor45920e82008-12-19 17:40:08 +00002575 const StandardConversionSequence& SCS,
John McCallf85e1932011-06-15 23:02:42 +00002576 AssignmentAction Action,
2577 CheckedConversionKind CCK) {
2578 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2579
Mike Stump390b4cc2009-05-16 07:39:55 +00002580 // Overall FIXME: we are recomputing too many types here and doing far too
2581 // much extra work. What this means is that we need to keep track of more
2582 // information that is computed when we try the implicit conversion initially,
2583 // so that we don't need to recompute anything here.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002584 QualType FromType = From->getType();
John McCallf85e1932011-06-15 23:02:42 +00002585
Douglas Gregor225c41e2008-11-03 19:09:14 +00002586 if (SCS.CopyConstructor) {
Anders Carlsson7c3e8a12009-05-19 04:45:15 +00002587 // FIXME: When can ToType be a reference type?
2588 assert(!ToType->isReferenceType());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002589 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002590 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002591 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramer5354e772012-08-23 23:38:35 +00002592 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002593 ConstructorArgs))
John Wiegley429bb272011-04-08 18:41:53 +00002594 return ExprError();
2595 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2596 ToType, SCS.CopyConstructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002597 ConstructorArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002598 /*HadMultipleCandidates*/ false,
Richard Smithc83c2302012-12-19 01:39:02 +00002599 /*ListInit*/ false, /*ZeroInit*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002600 CXXConstructExpr::CK_Complete,
2601 SourceRange());
Fariborz Jahanianb3c47742009-09-25 18:59:21 +00002602 }
John Wiegley429bb272011-04-08 18:41:53 +00002603 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2604 ToType, SCS.CopyConstructor,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002605 From, /*HadMultipleCandidates*/ false,
Richard Smithc83c2302012-12-19 01:39:02 +00002606 /*ListInit*/ false, /*ZeroInit*/ false,
John Wiegley429bb272011-04-08 18:41:53 +00002607 CXXConstructExpr::CK_Complete,
2608 SourceRange());
Douglas Gregor225c41e2008-11-03 19:09:14 +00002609 }
2610
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002611 // Resolve overloaded function references.
2612 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2613 DeclAccessPair Found;
2614 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2615 true, Found);
2616 if (!Fn)
John Wiegley429bb272011-04-08 18:41:53 +00002617 return ExprError();
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002618
Daniel Dunbar96a00142012-03-09 18:35:03 +00002619 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley429bb272011-04-08 18:41:53 +00002620 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002621
Douglas Gregorad4e02f2010-04-29 18:24:40 +00002622 From = FixOverloadedFunctionReference(From, Found, Fn);
2623 FromType = From->getType();
2624 }
2625
Richard Smith5705f212013-05-23 00:30:41 +00002626 // If we're converting to an atomic type, first convert to the corresponding
2627 // non-atomic type.
2628 QualType ToAtomicType;
2629 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
2630 ToAtomicType = ToType;
2631 ToType = ToAtomic->getValueType();
2632 }
2633
Richard Smithc8d7f582011-11-29 22:48:16 +00002634 // Perform the first implicit conversion.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002635 switch (SCS.First) {
2636 case ICK_Identity:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002637 // Nothing to do.
2638 break;
2639
Eli Friedmand814eaf2012-01-24 22:51:26 +00002640 case ICK_Lvalue_To_Rvalue: {
John McCall3c3b7f92011-10-25 17:37:35 +00002641 assert(From->getObjectKind() != OK_ObjCProperty);
John McCallf6a16482010-12-04 03:47:34 +00002642 FromType = FromType.getUnqualifiedType();
Eli Friedmand814eaf2012-01-24 22:51:26 +00002643 ExprResult FromRes = DefaultLvalueConversion(From);
2644 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2645 From = FromRes.take();
John McCallf6a16482010-12-04 03:47:34 +00002646 break;
Eli Friedmand814eaf2012-01-24 22:51:26 +00002647 }
John McCallf6a16482010-12-04 03:47:34 +00002648
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002649 case ICK_Array_To_Pointer:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002650 FromType = Context.getArrayDecayedType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002651 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2652 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002653 break;
2654
2655 case ICK_Function_To_Pointer:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002656 FromType = Context.getPointerType(FromType);
Richard Smithc8d7f582011-11-29 22:48:16 +00002657 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2658 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002659 break;
2660
2661 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002662 llvm_unreachable("Improper first standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002663 }
2664
Richard Smithc8d7f582011-11-29 22:48:16 +00002665 // Perform the second implicit conversion
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002666 switch (SCS.Second) {
2667 case ICK_Identity:
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002668 // If both sides are functions (or pointers/references to them), there could
2669 // be incompatible exception declarations.
2670 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002671 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002672 // Nothing else to do.
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002673 break;
2674
Douglas Gregor43c79c22009-12-09 00:47:37 +00002675 case ICK_NoReturn_Adjustment:
2676 // If both sides are functions (or pointers/references to them), there could
2677 // be incompatible exception declarations.
2678 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002679 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002680
Richard Smithc8d7f582011-11-29 22:48:16 +00002681 From = ImpCastExprToType(From, ToType, CK_NoOp,
2682 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor43c79c22009-12-09 00:47:37 +00002683 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002684
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002685 case ICK_Integral_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002686 case ICK_Integral_Conversion:
Richard Smithe7ff9192012-09-13 21:18:54 +00002687 if (ToType->isBooleanType()) {
2688 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
2689 SCS.Second == ICK_Integral_Promotion &&
2690 "only enums with fixed underlying type can promote to bool");
2691 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
2692 VK_RValue, /*BasePath=*/0, CCK).take();
2693 } else {
2694 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2695 VK_RValue, /*BasePath=*/0, CCK).take();
2696 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002697 break;
2698
2699 case ICK_Floating_Promotion:
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002700 case ICK_Floating_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002701 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2702 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002703 break;
2704
2705 case ICK_Complex_Promotion:
John McCalldaa8e4e2010-11-15 09:13:47 +00002706 case ICK_Complex_Conversion: {
2707 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2708 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2709 CastKind CK;
2710 if (FromEl->isRealFloatingType()) {
2711 if (ToEl->isRealFloatingType())
2712 CK = CK_FloatingComplexCast;
2713 else
2714 CK = CK_FloatingComplexToIntegralComplex;
2715 } else if (ToEl->isRealFloatingType()) {
2716 CK = CK_IntegralComplexToFloatingComplex;
2717 } else {
2718 CK = CK_IntegralComplexCast;
2719 }
Richard Smithc8d7f582011-11-29 22:48:16 +00002720 From = ImpCastExprToType(From, ToType, CK,
2721 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002722 break;
John McCalldaa8e4e2010-11-15 09:13:47 +00002723 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00002724
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002725 case ICK_Floating_Integral:
Douglas Gregor0c293ea2010-06-22 23:07:26 +00002726 if (ToType->isRealFloatingType())
Richard Smithc8d7f582011-11-29 22:48:16 +00002727 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2728 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002729 else
Richard Smithc8d7f582011-11-29 22:48:16 +00002730 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2731 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002732 break;
2733
Douglas Gregorf9201e02009-02-11 23:02:49 +00002734 case ICK_Compatible_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002735 From = ImpCastExprToType(From, ToType, CK_NoOp,
2736 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002737 break;
2738
John McCallf85e1932011-06-15 23:02:42 +00002739 case ICK_Writeback_Conversion:
Anders Carlsson61faec12009-09-12 04:46:44 +00002740 case ICK_Pointer_Conversion: {
Douglas Gregora3998bd2010-12-02 21:47:04 +00002741 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002742 // Diagnose incompatible Objective-C conversions
Douglas Gregor8cf0d222011-06-11 04:42:12 +00002743 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002744 Diag(From->getLocStart(),
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002745 diag::ext_typecheck_convert_incompatible_pointer)
2746 << ToType << From->getType() << Action
Anna Zaks67221552011-07-28 19:51:27 +00002747 << From->getSourceRange() << 0;
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002748 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00002749 Diag(From->getLocStart(),
Fariborz Jahanian84950c72011-03-21 19:08:42 +00002750 diag::ext_typecheck_convert_incompatible_pointer)
2751 << From->getType() << ToType << Action
Anna Zaks67221552011-07-28 19:51:27 +00002752 << From->getSourceRange() << 0;
John McCallf85e1932011-06-15 23:02:42 +00002753
Douglas Gregor926df6c2011-06-11 01:09:30 +00002754 if (From->getType()->isObjCObjectPointerType() &&
2755 ToType->isObjCObjectPointerType())
2756 EmitRelatedResultTypeNote(From);
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002757 }
David Blaikie4e4d0842012-03-11 07:00:24 +00002758 else if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002759 !CheckObjCARCUnavailableWeakConversion(ToType,
2760 From->getType())) {
John McCall7f3a6d32011-09-09 06:12:06 +00002761 if (Action == AA_Initializing)
Daniel Dunbar96a00142012-03-09 18:35:03 +00002762 Diag(From->getLocStart(),
John McCall7f3a6d32011-09-09 06:12:06 +00002763 diag::err_arc_weak_unavailable_assign);
2764 else
Daniel Dunbar96a00142012-03-09 18:35:03 +00002765 Diag(From->getLocStart(),
John McCall7f3a6d32011-09-09 06:12:06 +00002766 diag::err_arc_convesion_of_weak_unavailable)
2767 << (Action == AA_Casting) << From->getType() << ToType
2768 << From->getSourceRange();
2769 }
Fariborz Jahanian82007c32011-07-08 17:41:42 +00002770
John McCalldaa8e4e2010-11-15 09:13:47 +00002771 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002772 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002773 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002774 return ExprError();
John McCalldc05b112011-09-10 01:16:55 +00002775
2776 // Make sure we extend blocks if necessary.
2777 // FIXME: doing this here is really ugly.
2778 if (Kind == CK_BlockPointerToObjCPointerCast) {
2779 ExprResult E = From;
2780 (void) PrepareCastToObjCObjectPointer(E);
2781 From = E.take();
2782 }
Fariborz Jahanianb316dc52013-07-31 17:12:26 +00002783 if (getLangOpts().ObjCAutoRefCount)
2784 CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
Richard Smithc8d7f582011-11-29 22:48:16 +00002785 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2786 .take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002787 break;
Anders Carlsson61faec12009-09-12 04:46:44 +00002788 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002789
Anders Carlsson61faec12009-09-12 04:46:44 +00002790 case ICK_Pointer_Member: {
John McCalldaa8e4e2010-11-15 09:13:47 +00002791 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +00002792 CXXCastPath BasePath;
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002793 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002794 return ExprError();
Sebastian Redl2c7588f2009-10-10 12:04:10 +00002795 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley429bb272011-04-08 18:41:53 +00002796 return ExprError();
Richard Smithc8d7f582011-11-29 22:48:16 +00002797 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2798 .take();
Anders Carlsson61faec12009-09-12 04:46:44 +00002799 break;
2800 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002801
Abramo Bagnara737d5442011-04-07 09:26:19 +00002802 case ICK_Boolean_Conversion:
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00002803 // Perform half-to-boolean conversion via float.
2804 if (From->getType()->isHalfType()) {
2805 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2806 FromType = Context.FloatTy;
2807 }
2808
Richard Smithc8d7f582011-11-29 22:48:16 +00002809 From = ImpCastExprToType(From, Context.BoolTy,
2810 ScalarTypeToBooleanCastKind(FromType),
2811 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002812 break;
2813
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002814 case ICK_Derived_To_Base: {
John McCallf871d0c2010-08-07 06:22:56 +00002815 CXXCastPath BasePath;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002816 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002817 ToType.getNonReferenceType(),
2818 From->getLocStart(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002819 From->getSourceRange(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002820 &BasePath,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002821 CStyle))
John Wiegley429bb272011-04-08 18:41:53 +00002822 return ExprError();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002823
Richard Smithc8d7f582011-11-29 22:48:16 +00002824 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2825 CK_DerivedToBase, From->getValueKind(),
2826 &BasePath, CCK).take();
Douglas Gregorb7a86f52009-11-06 01:02:41 +00002827 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002828 }
2829
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002830 case ICK_Vector_Conversion:
Richard Smithc8d7f582011-11-29 22:48:16 +00002831 From = ImpCastExprToType(From, ToType, CK_BitCast,
2832 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002833 break;
2834
2835 case ICK_Vector_Splat:
Richard Smithc8d7f582011-11-29 22:48:16 +00002836 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2837 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002838 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002839
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002840 case ICK_Complex_Real:
John McCalldaa8e4e2010-11-15 09:13:47 +00002841 // Case 1. x -> _Complex y
2842 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2843 QualType ElType = ToComplex->getElementType();
2844 bool isFloatingComplex = ElType->isRealFloatingType();
2845
2846 // x -> y
2847 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2848 // do nothing
2849 } else if (From->getType()->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002850 From = ImpCastExprToType(From, ElType,
2851 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002852 } else {
2853 assert(From->getType()->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002854 From = ImpCastExprToType(From, ElType,
2855 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002856 }
2857 // y -> _Complex y
Richard Smithc8d7f582011-11-29 22:48:16 +00002858 From = ImpCastExprToType(From, ToType,
2859 isFloatingComplex ? CK_FloatingRealToComplex
2860 : CK_IntegralRealToComplex).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002861
2862 // Case 2. _Complex x -> y
2863 } else {
2864 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2865 assert(FromComplex);
2866
2867 QualType ElType = FromComplex->getElementType();
2868 bool isFloatingComplex = ElType->isRealFloatingType();
2869
2870 // _Complex x -> x
Richard Smithc8d7f582011-11-29 22:48:16 +00002871 From = ImpCastExprToType(From, ElType,
2872 isFloatingComplex ? CK_FloatingComplexToReal
2873 : CK_IntegralComplexToReal,
2874 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002875
2876 // x -> y
2877 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2878 // do nothing
2879 } else if (ToType->isRealFloatingType()) {
Richard Smithc8d7f582011-11-29 22:48:16 +00002880 From = ImpCastExprToType(From, ToType,
2881 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2882 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002883 } else {
2884 assert(ToType->isIntegerType());
Richard Smithc8d7f582011-11-29 22:48:16 +00002885 From = ImpCastExprToType(From, ToType,
2886 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2887 VK_RValue, /*BasePath=*/0, CCK).take();
John McCalldaa8e4e2010-11-15 09:13:47 +00002888 }
2889 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002890 break;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002891
2892 case ICK_Block_Pointer_Conversion: {
Richard Smithc8d7f582011-11-29 22:48:16 +00002893 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2894 VK_RValue, /*BasePath=*/0, CCK).take();
John McCallf85e1932011-06-15 23:02:42 +00002895 break;
2896 }
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002897
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002898 case ICK_TransparentUnionConversion: {
John Wiegley429bb272011-04-08 18:41:53 +00002899 ExprResult FromRes = Owned(From);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002900 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00002901 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2902 if (FromRes.isInvalid())
2903 return ExprError();
2904 From = FromRes.take();
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00002905 assert ((ConvTy == Sema::Compatible) &&
2906 "Improper transparent union conversion");
2907 (void)ConvTy;
2908 break;
2909 }
2910
Guy Benyei6959acd2013-02-07 16:05:33 +00002911 case ICK_Zero_Event_Conversion:
2912 From = ImpCastExprToType(From, ToType,
2913 CK_ZeroToOCLEvent,
2914 From->getValueKind()).take();
2915 break;
2916
Douglas Gregorfb4a5432010-05-18 22:42:18 +00002917 case ICK_Lvalue_To_Rvalue:
2918 case ICK_Array_To_Pointer:
2919 case ICK_Function_To_Pointer:
2920 case ICK_Qualification:
2921 case ICK_Num_Conversion_Kinds:
David Blaikieb219cfc2011-09-23 05:06:16 +00002922 llvm_unreachable("Improper second standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002923 }
2924
2925 switch (SCS.Third) {
2926 case ICK_Identity:
2927 // Nothing to do.
2928 break;
2929
Sebastian Redl906082e2010-07-20 04:20:21 +00002930 case ICK_Qualification: {
2931 // The qualification keeps the category of the inner expression, unless the
2932 // target type isn't a reference.
John McCall5baba9d2010-08-25 10:28:54 +00002933 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00002934 From->getValueKind() : VK_RValue;
Richard Smithc8d7f582011-11-29 22:48:16 +00002935 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2936 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregora9bff302010-02-28 18:30:25 +00002937
Douglas Gregor069a6da2011-03-14 16:13:32 +00002938 if (SCS.DeprecatedStringLiteralToCharPtr &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002939 !getLangOpts().WritableStrings)
Douglas Gregora9bff302010-02-28 18:30:25 +00002940 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2941 << ToType.getNonReferenceType();
2942
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002943 break;
Richard Smith5705f212013-05-23 00:30:41 +00002944 }
Sebastian Redl906082e2010-07-20 04:20:21 +00002945
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002946 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002947 llvm_unreachable("Improper third standard conversion");
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002948 }
2949
Douglas Gregor47bfcca2012-04-12 20:42:30 +00002950 // If this conversion sequence involved a scalar -> atomic conversion, perform
2951 // that conversion now.
Richard Smith5705f212013-05-23 00:30:41 +00002952 if (!ToAtomicType.isNull()) {
2953 assert(Context.hasSameType(
2954 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
2955 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
2956 VK_RValue, 0, CCK).take();
2957 }
2958
John Wiegley429bb272011-04-08 18:41:53 +00002959 return Owned(From);
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002960}
2961
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002962ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002963 SourceLocation KWLoc,
2964 ParsedType Ty,
2965 SourceLocation RParen) {
2966 TypeSourceInfo *TSInfo;
2967 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00002968
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002969 if (!TSInfo)
2970 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002971 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00002972}
2973
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002974/// \brief Check the completeness of a type in a unary type trait.
2975///
2976/// If the particular type trait requires a complete type, tries to complete
2977/// it. If completing the type fails, a diagnostic is emitted and false
2978/// returned. If completing the type succeeds or no completion was required,
2979/// returns true.
2980static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2981 UnaryTypeTrait UTT,
2982 SourceLocation Loc,
2983 QualType ArgTy) {
2984 // C++0x [meta.unary.prop]p3:
2985 // For all of the class templates X declared in this Clause, instantiating
2986 // that template with a template argument that is a class template
2987 // specialization may result in the implicit instantiation of the template
2988 // argument if and only if the semantics of X require that the argument
2989 // must be a complete type.
2990 // We apply this rule to all the type trait expressions used to implement
2991 // these class templates. We also try to follow any GCC documented behavior
2992 // in these expressions to ensure portability of standard libraries.
2993 switch (UTT) {
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002994 // is_complete_type somewhat obviously cannot require a complete type.
2995 case UTT_IsCompleteType:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00002996 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00002997
2998 // These traits are modeled on the type predicates in C++0x
2999 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3000 // requiring a complete type, as whether or not they return true cannot be
3001 // impacted by the completeness of the type.
3002 case UTT_IsVoid:
3003 case UTT_IsIntegral:
3004 case UTT_IsFloatingPoint:
3005 case UTT_IsArray:
3006 case UTT_IsPointer:
3007 case UTT_IsLvalueReference:
3008 case UTT_IsRvalueReference:
3009 case UTT_IsMemberFunctionPointer:
3010 case UTT_IsMemberObjectPointer:
3011 case UTT_IsEnum:
3012 case UTT_IsUnion:
3013 case UTT_IsClass:
3014 case UTT_IsFunction:
3015 case UTT_IsReference:
3016 case UTT_IsArithmetic:
3017 case UTT_IsFundamental:
3018 case UTT_IsObject:
3019 case UTT_IsScalar:
3020 case UTT_IsCompound:
3021 case UTT_IsMemberPointer:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00003022 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003023
3024 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
3025 // which requires some of its traits to have the complete type. However,
3026 // the completeness of the type cannot impact these traits' semantics, and
3027 // so they don't require it. This matches the comments on these traits in
3028 // Table 49.
3029 case UTT_IsConst:
3030 case UTT_IsVolatile:
3031 case UTT_IsSigned:
3032 case UTT_IsUnsigned:
3033 return true;
3034
3035 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00003036 // applied to a complete type.
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003037 case UTT_IsTrivial:
Sean Huntfeb375d2011-05-13 00:31:07 +00003038 case UTT_IsTriviallyCopyable:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003039 case UTT_IsStandardLayout:
3040 case UTT_IsPOD:
3041 case UTT_IsLiteral:
3042 case UTT_IsEmpty:
3043 case UTT_IsPolymorphic:
3044 case UTT_IsAbstract:
John McCallea30e2f2012-09-25 07:32:49 +00003045 case UTT_IsInterfaceClass:
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00003046 // Fall-through
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003047
Douglas Gregor5e9392b2011-12-03 18:14:24 +00003048 // These traits require a complete type.
3049 case UTT_IsFinal:
3050
Chandler Carruthd6efe9b2011-05-01 19:18:02 +00003051 // These trait expressions are designed to help implement predicates in
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003052 // [meta.unary.prop] despite not being named the same. They are specified
3053 // by both GCC and the Embarcadero C++ compiler, and require the complete
3054 // type due to the overarching C++0x type predicates being implemented
3055 // requiring the complete type.
3056 case UTT_HasNothrowAssign:
Joao Matos9ef98752013-03-27 01:34:16 +00003057 case UTT_HasNothrowMoveAssign:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003058 case UTT_HasNothrowConstructor:
3059 case UTT_HasNothrowCopy:
3060 case UTT_HasTrivialAssign:
Joao Matos9ef98752013-03-27 01:34:16 +00003061 case UTT_HasTrivialMoveAssign:
Sean Hunt023df372011-05-09 18:22:59 +00003062 case UTT_HasTrivialDefaultConstructor:
Joao Matos9ef98752013-03-27 01:34:16 +00003063 case UTT_HasTrivialMoveConstructor:
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003064 case UTT_HasTrivialCopy:
3065 case UTT_HasTrivialDestructor:
3066 case UTT_HasVirtualDestructor:
3067 // Arrays of unknown bound are expressly allowed.
3068 QualType ElTy = ArgTy;
3069 if (ArgTy->isIncompleteArrayType())
3070 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
3071
3072 // The void type is expressly allowed.
3073 if (ElTy->isVoidType())
3074 return true;
3075
3076 return !S.RequireCompleteType(
3077 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleycf566412011-04-28 02:06:46 +00003078 }
Chandler Carruth73e0a912011-05-01 07:23:17 +00003079 llvm_unreachable("Type trait not handled by switch");
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003080}
3081
Joao Matos9ef98752013-03-27 01:34:16 +00003082static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
3083 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
3084 bool (CXXRecordDecl::*HasTrivial)() const,
3085 bool (CXXRecordDecl::*HasNonTrivial)() const,
3086 bool (CXXMethodDecl::*IsDesiredOp)() const)
3087{
3088 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3089 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
3090 return true;
3091
3092 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
3093 DeclarationNameInfo NameInfo(Name, KeyLoc);
3094 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
3095 if (Self.LookupQualifiedName(Res, RD)) {
3096 bool FoundOperator = false;
3097 Res.suppressDiagnostics();
3098 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3099 Op != OpEnd; ++Op) {
3100 if (isa<FunctionTemplateDecl>(*Op))
3101 continue;
3102
3103 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3104 if((Operator->*IsDesiredOp)()) {
3105 FoundOperator = true;
3106 const FunctionProtoType *CPT =
3107 Operator->getType()->getAs<FunctionProtoType>();
3108 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3109 if (!CPT || !CPT->isNothrow(Self.Context))
3110 return false;
3111 }
3112 }
3113 return FoundOperator;
3114 }
3115 return false;
3116}
3117
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003118static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
3119 SourceLocation KeyLoc, QualType T) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003120 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleycf566412011-04-28 02:06:46 +00003121
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003122 ASTContext &C = Self.Context;
3123 switch(UTT) {
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003124 // Type trait expressions corresponding to the primary type category
3125 // predicates in C++0x [meta.unary.cat].
3126 case UTT_IsVoid:
3127 return T->isVoidType();
3128 case UTT_IsIntegral:
3129 return T->isIntegralType(C);
3130 case UTT_IsFloatingPoint:
3131 return T->isFloatingType();
3132 case UTT_IsArray:
3133 return T->isArrayType();
3134 case UTT_IsPointer:
3135 return T->isPointerType();
3136 case UTT_IsLvalueReference:
3137 return T->isLValueReferenceType();
3138 case UTT_IsRvalueReference:
3139 return T->isRValueReferenceType();
3140 case UTT_IsMemberFunctionPointer:
3141 return T->isMemberFunctionPointerType();
3142 case UTT_IsMemberObjectPointer:
3143 return T->isMemberDataPointerType();
3144 case UTT_IsEnum:
3145 return T->isEnumeralType();
Chandler Carruth28eeb382011-05-01 06:11:03 +00003146 case UTT_IsUnion:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003147 return T->isUnionType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003148 case UTT_IsClass:
Joao Matos6666ed42012-08-31 18:45:21 +00003149 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003150 case UTT_IsFunction:
3151 return T->isFunctionType();
3152
3153 // Type trait expressions which correspond to the convenient composition
3154 // predicates in C++0x [meta.unary.comp].
3155 case UTT_IsReference:
3156 return T->isReferenceType();
3157 case UTT_IsArithmetic:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003158 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003159 case UTT_IsFundamental:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003160 return T->isFundamentalType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003161 case UTT_IsObject:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003162 return T->isObjectType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003163 case UTT_IsScalar:
John McCallf85e1932011-06-15 23:02:42 +00003164 // Note: semantic analysis depends on Objective-C lifetime types to be
3165 // considered scalar types. However, such types do not actually behave
3166 // like scalar types at run time (since they may require retain/release
3167 // operations), so we report them as non-scalar.
3168 if (T->isObjCLifetimeType()) {
3169 switch (T.getObjCLifetime()) {
3170 case Qualifiers::OCL_None:
3171 case Qualifiers::OCL_ExplicitNone:
3172 return true;
3173
3174 case Qualifiers::OCL_Strong:
3175 case Qualifiers::OCL_Weak:
3176 case Qualifiers::OCL_Autoreleasing:
3177 return false;
3178 }
3179 }
3180
Chandler Carruthcec0ced2011-05-01 09:29:55 +00003181 return T->isScalarType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003182 case UTT_IsCompound:
Chandler Carruthaaf147b2011-05-01 09:29:58 +00003183 return T->isCompoundType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003184 case UTT_IsMemberPointer:
3185 return T->isMemberPointerType();
3186
3187 // Type trait expressions which correspond to the type property predicates
3188 // in C++0x [meta.unary.prop].
3189 case UTT_IsConst:
3190 return T.isConstQualified();
3191 case UTT_IsVolatile:
3192 return T.isVolatileQualified();
3193 case UTT_IsTrivial:
John McCallf85e1932011-06-15 23:02:42 +00003194 return T.isTrivialType(Self.Context);
Sean Huntfeb375d2011-05-13 00:31:07 +00003195 case UTT_IsTriviallyCopyable:
John McCallf85e1932011-06-15 23:02:42 +00003196 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003197 case UTT_IsStandardLayout:
3198 return T->isStandardLayoutType();
3199 case UTT_IsPOD:
Benjamin Kramer470360d2012-04-28 10:00:33 +00003200 return T.isPODType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003201 case UTT_IsLiteral:
Richard Smitha10b9782013-04-22 15:31:51 +00003202 return T->isLiteralType(Self.Context);
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003203 case UTT_IsEmpty:
3204 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3205 return !RD->isUnion() && RD->isEmpty();
3206 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003207 case UTT_IsPolymorphic:
Chandler Carruth28eeb382011-05-01 06:11:03 +00003208 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3209 return RD->isPolymorphic();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003210 return false;
3211 case UTT_IsAbstract:
Chandler Carruth28eeb382011-05-01 06:11:03 +00003212 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3213 return RD->isAbstract();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003214 return false;
John McCallea30e2f2012-09-25 07:32:49 +00003215 case UTT_IsInterfaceClass:
3216 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3217 return RD->isInterface();
3218 return false;
Douglas Gregor5e9392b2011-12-03 18:14:24 +00003219 case UTT_IsFinal:
3220 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3221 return RD->hasAttr<FinalAttr>();
3222 return false;
John Wiegley20c0da72011-04-27 23:09:49 +00003223 case UTT_IsSigned:
3224 return T->isSignedIntegerType();
John Wiegley20c0da72011-04-27 23:09:49 +00003225 case UTT_IsUnsigned:
3226 return T->isUnsignedIntegerType();
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003227
3228 // Type trait expressions which query classes regarding their construction,
3229 // destruction, and copying. Rather than being based directly on the
3230 // related type predicates in the standard, they are specified by both
3231 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3232 // specifications.
3233 //
3234 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3235 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smithac713512012-12-08 02:53:02 +00003236 //
3237 // Note that these builtins do not behave as documented in g++: if a class
3238 // has both a trivial and a non-trivial special member of a particular kind,
3239 // they return false! For now, we emulate this behavior.
3240 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
3241 // does not correctly compute triviality in the presence of multiple special
3242 // members of the same kind. Revisit this once the g++ bug is fixed.
Sean Hunt023df372011-05-09 18:22:59 +00003243 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003244 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3245 // If __is_pod (type) is true then the trait is true, else if type is
3246 // a cv class or union type (or array thereof) with a trivial default
3247 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003248 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003249 return true;
Richard Smithac713512012-12-08 02:53:02 +00003250 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3251 return RD->hasTrivialDefaultConstructor() &&
3252 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003253 return false;
Joao Matos9ef98752013-03-27 01:34:16 +00003254 case UTT_HasTrivialMoveConstructor:
3255 // This trait is implemented by MSVC 2012 and needed to parse the
3256 // standard library headers. Specifically this is used as the logic
3257 // behind std::is_trivially_move_constructible (20.9.4.3).
3258 if (T.isPODType(Self.Context))
3259 return true;
3260 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3261 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
3262 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003263 case UTT_HasTrivialCopy:
3264 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3265 // If __is_pod (type) is true or type is a reference type then
3266 // the trait is true, else if type is a cv class or union type
3267 // with a trivial copy constructor ([class.copy]) then the trait
3268 // is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003269 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003270 return true;
Richard Smithac713512012-12-08 02:53:02 +00003271 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3272 return RD->hasTrivialCopyConstructor() &&
3273 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003274 return false;
Joao Matos9ef98752013-03-27 01:34:16 +00003275 case UTT_HasTrivialMoveAssign:
3276 // This trait is implemented by MSVC 2012 and needed to parse the
3277 // standard library headers. Specifically it is used as the logic
3278 // behind std::is_trivially_move_assignable (20.9.4.3)
3279 if (T.isPODType(Self.Context))
3280 return true;
3281 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3282 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
3283 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003284 case UTT_HasTrivialAssign:
3285 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3286 // If type is const qualified or is a reference type then the
3287 // trait is false. Otherwise if __is_pod (type) is true then the
3288 // trait is true, else if type is a cv class or union type with
3289 // a trivial copy assignment ([class.copy]) then the trait is
3290 // true, else it is false.
3291 // Note: the const and reference restrictions are interesting,
3292 // given that const and reference members don't prevent a class
3293 // from having a trivial copy assignment operator (but do cause
3294 // errors if the copy assignment operator is actually used, q.v.
3295 // [class.copy]p12).
3296
Richard Smithac713512012-12-08 02:53:02 +00003297 if (T.isConstQualified())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003298 return false;
John McCallf85e1932011-06-15 23:02:42 +00003299 if (T.isPODType(Self.Context))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003300 return true;
Richard Smithac713512012-12-08 02:53:02 +00003301 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3302 return RD->hasTrivialCopyAssignment() &&
3303 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003304 return false;
3305 case UTT_HasTrivialDestructor:
3306 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3307 // If __is_pod (type) is true or type is a reference type
3308 // then the trait is true, else if type is a cv class or union
3309 // type (or array thereof) with a trivial destructor
3310 // ([class.dtor]) then the trait is true, else it is
3311 // false.
John McCallf85e1932011-06-15 23:02:42 +00003312 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003313 return true;
John McCallf85e1932011-06-15 23:02:42 +00003314
3315 // Objective-C++ ARC: autorelease types don't require destruction.
3316 if (T->isObjCLifetimeType() &&
3317 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3318 return true;
3319
Richard Smithac713512012-12-08 02:53:02 +00003320 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3321 return RD->hasTrivialDestructor();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003322 return false;
3323 // TODO: Propagate nothrowness for implicitly declared special members.
3324 case UTT_HasNothrowAssign:
3325 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3326 // If type is const qualified or is a reference type then the
3327 // trait is false. Otherwise if __has_trivial_assign (type)
3328 // is true then the trait is true, else if type is a cv class
3329 // or union type with copy assignment operators that are known
3330 // not to throw an exception then the trait is true, else it is
3331 // false.
3332 if (C.getBaseElementType(T).isConstQualified())
3333 return false;
3334 if (T->isReferenceType())
3335 return false;
John McCallf85e1932011-06-15 23:02:42 +00003336 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
Joao Matos9ef98752013-03-27 01:34:16 +00003337 return true;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003338
Joao Matos9ef98752013-03-27 01:34:16 +00003339 if (const RecordType *RT = T->getAs<RecordType>())
3340 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3341 &CXXRecordDecl::hasTrivialCopyAssignment,
3342 &CXXRecordDecl::hasNonTrivialCopyAssignment,
3343 &CXXMethodDecl::isCopyAssignmentOperator);
3344 return false;
3345 case UTT_HasNothrowMoveAssign:
3346 // This trait is implemented by MSVC 2012 and needed to parse the
3347 // standard library headers. Specifically this is used as the logic
3348 // behind std::is_nothrow_move_assignable (20.9.4.3).
3349 if (T.isPODType(Self.Context))
3350 return true;
3351
3352 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
3353 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3354 &CXXRecordDecl::hasTrivialMoveAssignment,
3355 &CXXRecordDecl::hasNonTrivialMoveAssignment,
3356 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003357 return false;
3358 case UTT_HasNothrowCopy:
3359 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3360 // If __has_trivial_copy (type) is true then the trait is true, else
3361 // if type is a cv class or union type with copy constructors that are
3362 // known not to throw an exception then the trait is true, else it is
3363 // false.
John McCallf85e1932011-06-15 23:02:42 +00003364 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003365 return true;
Richard Smithac713512012-12-08 02:53:02 +00003366 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
3367 if (RD->hasTrivialCopyConstructor() &&
3368 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003369 return true;
3370
3371 bool FoundConstructor = false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003372 unsigned FoundTQs;
David Blaikie3bc93e32012-12-19 00:45:41 +00003373 DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3374 for (DeclContext::lookup_const_iterator Con = R.begin(),
3375 ConEnd = R.end(); Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003376 // A template constructor is never a copy constructor.
3377 // FIXME: However, it may actually be selected at the actual overload
3378 // resolution point.
3379 if (isa<FunctionTemplateDecl>(*Con))
3380 continue;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003381 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3382 if (Constructor->isCopyConstructor(FoundTQs)) {
3383 FoundConstructor = true;
3384 const FunctionProtoType *CPT
3385 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +00003386 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3387 if (!CPT)
3388 return false;
Sebastian Redl60618fa2011-03-12 11:50:43 +00003389 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redl751025d2010-09-13 22:02:47 +00003390 // For now, we'll be conservative and assume that they can throw.
Richard Smith7a614d82011-06-11 17:19:42 +00003391 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3392 return false;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003393 }
3394 }
3395
Richard Smith7a614d82011-06-11 17:19:42 +00003396 return FoundConstructor;
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003397 }
3398 return false;
3399 case UTT_HasNothrowConstructor:
3400 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3401 // If __has_trivial_constructor (type) is true then the trait is
3402 // true, else if type is a cv class or union type (or array
3403 // thereof) with a default constructor that is known not to
3404 // throw an exception then the trait is true, else it is false.
John McCallf85e1932011-06-15 23:02:42 +00003405 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003406 return true;
Richard Smithac713512012-12-08 02:53:02 +00003407 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
3408 if (RD->hasTrivialDefaultConstructor() &&
3409 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003410 return true;
3411
David Blaikie3bc93e32012-12-19 00:45:41 +00003412 DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3413 for (DeclContext::lookup_const_iterator Con = R.begin(),
3414 ConEnd = R.end(); Con != ConEnd; ++Con) {
Sebastian Redl08295a52010-09-13 22:18:28 +00003415 // FIXME: In C++0x, a constructor template can be a default constructor.
3416 if (isa<FunctionTemplateDecl>(*Con))
3417 continue;
Sebastian Redl751025d2010-09-13 22:02:47 +00003418 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3419 if (Constructor->isDefaultConstructor()) {
3420 const FunctionProtoType *CPT
3421 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +00003422 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3423 if (!CPT)
3424 return false;
Sebastian Redl751025d2010-09-13 22:02:47 +00003425 // TODO: check whether evaluating default arguments can throw.
3426 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl8026f6d2011-03-13 17:09:40 +00003427 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redl751025d2010-09-13 22:02:47 +00003428 }
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003429 }
3430 }
3431 return false;
3432 case UTT_HasVirtualDestructor:
3433 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3434 // If type is a class type with a virtual destructor ([class.dtor])
3435 // then the trait is true, else it is false.
Richard Smithac713512012-12-08 02:53:02 +00003436 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redlf8aca862010-09-14 23:40:14 +00003437 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003438 return Destructor->isVirtual();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003439 return false;
Chandler Carruthc41d6b52011-05-01 06:11:07 +00003440
3441 // These type trait expressions are modeled on the specifications for the
3442 // Embarcadero C++0x type trait functions:
3443 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3444 case UTT_IsCompleteType:
3445 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3446 // Returns True if and only if T is a complete type at the point of the
3447 // function call.
3448 return !T->isIncompleteType();
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003449 }
Chandler Carruth83f563c2011-05-01 07:44:17 +00003450 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003451}
3452
3453ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00003454 SourceLocation KWLoc,
3455 TypeSourceInfo *TSInfo,
3456 SourceLocation RParen) {
3457 QualType T = TSInfo->getType();
Chandler Carrutheb65a102011-04-30 10:07:32 +00003458 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3459 return ExprError();
Sebastian Redl64b45f72009-01-05 20:52:13 +00003460
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003461 bool Value = false;
3462 if (!T->isDependentType())
Chandler Carruthccb4ecf2011-05-01 06:51:22 +00003463 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003464
3465 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson3292d5c2009-07-07 19:06:02 +00003466 RParen, Context.BoolTy));
Sebastian Redl64b45f72009-01-05 20:52:13 +00003467}
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003468
Francois Pichet6ad6f282010-12-07 00:08:36 +00003469ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3470 SourceLocation KWLoc,
3471 ParsedType LhsTy,
3472 ParsedType RhsTy,
3473 SourceLocation RParen) {
3474 TypeSourceInfo *LhsTSInfo;
3475 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3476 if (!LhsTSInfo)
3477 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3478
3479 TypeSourceInfo *RhsTSInfo;
3480 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3481 if (!RhsTSInfo)
3482 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3483
3484 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3485}
3486
Douglas Gregor14b23272012-06-29 00:49:17 +00003487/// \brief Determine whether T has a non-trivial Objective-C lifetime in
3488/// ARC mode.
3489static bool hasNontrivialObjCLifetime(QualType T) {
3490 switch (T.getObjCLifetime()) {
3491 case Qualifiers::OCL_ExplicitNone:
3492 return false;
3493
3494 case Qualifiers::OCL_Strong:
3495 case Qualifiers::OCL_Weak:
3496 case Qualifiers::OCL_Autoreleasing:
3497 return true;
3498
3499 case Qualifiers::OCL_None:
3500 return T->isObjCLifetimeType();
3501 }
3502
3503 llvm_unreachable("Unknown ObjC lifetime qualifier");
3504}
3505
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003506static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3507 ArrayRef<TypeSourceInfo *> Args,
3508 SourceLocation RParenLoc) {
3509 switch (Kind) {
3510 case clang::TT_IsTriviallyConstructible: {
3511 // C++11 [meta.unary.prop]:
Dmitri Gribenko62348f02012-02-24 20:03:35 +00003512 // is_trivially_constructible is defined as:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003513 //
Dmitri Gribenko62348f02012-02-24 20:03:35 +00003514 // is_constructible<T, Args...>::value is true and the variable
3515 // definition for is_constructible, as defined below, is known to call no
3516 // operation that is not trivial.
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003517 //
3518 // The predicate condition for a template specialization
3519 // is_constructible<T, Args...> shall be satisfied if and only if the
3520 // following variable definition would be well-formed for some invented
3521 // variable t:
3522 //
3523 // T t(create<Args>()...);
3524 if (Args.empty()) {
3525 S.Diag(KWLoc, diag::err_type_trait_arity)
3526 << 1 << 1 << 1 << (int)Args.size();
3527 return false;
3528 }
Eli Friedmanba081612013-09-11 02:53:02 +00003529
3530 // Precondition: T and all types in the parameter pack Args shall be
3531 // complete types, (possibly cv-qualified) void, or arrays of
3532 // unknown bound.
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003533 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
Eli Friedmanba081612013-09-11 02:53:02 +00003534 QualType ArgTy = Args[I]->getType();
3535 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003536 continue;
Eli Friedmanba081612013-09-11 02:53:02 +00003537
3538 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003539 diag::err_incomplete_type_used_in_type_trait_expr))
3540 return false;
3541 }
Eli Friedmanba081612013-09-11 02:53:02 +00003542
3543 // Make sure the first argument is a complete type.
3544 if (Args[0]->getType()->isIncompleteType())
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003545 return false;
Eli Friedmanba081612013-09-11 02:53:02 +00003546
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003547 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3548 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003549 ArgExprs.reserve(Args.size() - 1);
3550 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3551 QualType T = Args[I]->getType();
3552 if (T->isObjectType() || T->isFunctionType())
3553 T = S.Context.getRValueReferenceType(T);
3554 OpaqueArgExprs.push_back(
Daniel Dunbar96a00142012-03-09 18:35:03 +00003555 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003556 T.getNonLValueExprType(S.Context),
3557 Expr::getValueKindForType(T)));
3558 ArgExprs.push_back(&OpaqueArgExprs.back());
3559 }
3560
3561 // Perform the initialization in an unevaluated context within a SFINAE
3562 // trap at translation unit scope.
3563 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3564 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3565 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3566 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3567 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3568 RParenLoc));
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003569 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003570 if (Init.Failed())
3571 return false;
3572
Benjamin Kramer5354e772012-08-23 23:38:35 +00003573 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003574 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3575 return false;
Douglas Gregor14b23272012-06-29 00:49:17 +00003576
3577 // Under Objective-C ARC, if the destination has non-trivial Objective-C
3578 // lifetime, this is a non-trivial construction.
3579 if (S.getLangOpts().ObjCAutoRefCount &&
3580 hasNontrivialObjCLifetime(Args[0]->getType().getNonReferenceType()))
3581 return false;
3582
3583 // The initialization succeeded; now make sure there are no non-trivial
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003584 // calls.
3585 return !Result.get()->hasNonTrivialCall(S.Context);
3586 }
3587 }
3588
3589 return false;
3590}
3591
3592ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3593 ArrayRef<TypeSourceInfo *> Args,
3594 SourceLocation RParenLoc) {
3595 bool Dependent = false;
3596 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3597 if (Args[I]->getType()->isDependentType()) {
3598 Dependent = true;
3599 break;
3600 }
3601 }
3602
3603 bool Value = false;
3604 if (!Dependent)
3605 Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3606
3607 return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind,
3608 Args, RParenLoc, Value);
3609}
3610
3611ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3612 ArrayRef<ParsedType> Args,
3613 SourceLocation RParenLoc) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003614 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00003615 ConvertedArgs.reserve(Args.size());
3616
3617 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3618 TypeSourceInfo *TInfo;
3619 QualType T = GetTypeFromParser(Args[I], &TInfo);
3620 if (!TInfo)
3621 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3622
3623 ConvertedArgs.push_back(TInfo);
3624 }
3625
3626 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3627}
3628
Francois Pichet6ad6f282010-12-07 00:08:36 +00003629static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3630 QualType LhsT, QualType RhsT,
3631 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003632 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3633 "Cannot evaluate traits of dependent types");
Francois Pichet6ad6f282010-12-07 00:08:36 +00003634
3635 switch(BTT) {
John McCalld89d30f2011-01-28 22:02:36 +00003636 case BTT_IsBaseOf: {
Francois Pichet6ad6f282010-12-07 00:08:36 +00003637 // C++0x [meta.rel]p2
John McCalld89d30f2011-01-28 22:02:36 +00003638 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet6ad6f282010-12-07 00:08:36 +00003639 // Base and Derived are not unions and name the same class type without
3640 // regard to cv-qualifiers.
Francois Pichet6ad6f282010-12-07 00:08:36 +00003641
John McCalld89d30f2011-01-28 22:02:36 +00003642 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3643 if (!lhsRecord) return false;
3644
3645 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3646 if (!rhsRecord) return false;
3647
3648 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3649 == (lhsRecord == rhsRecord));
3650
3651 if (lhsRecord == rhsRecord)
3652 return !lhsRecord->getDecl()->isUnion();
3653
3654 // C++0x [meta.rel]p2:
3655 // If Base and Derived are class types and are different types
3656 // (ignoring possible cv-qualifiers) then Derived shall be a
3657 // complete type.
3658 if (Self.RequireCompleteType(KeyLoc, RhsT,
3659 diag::err_incomplete_type_used_in_type_trait_expr))
3660 return false;
3661
3662 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3663 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3664 }
John Wiegley20c0da72011-04-27 23:09:49 +00003665 case BTT_IsSame:
3666 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichetf1872372010-12-08 22:35:30 +00003667 case BTT_TypeCompatible:
3668 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3669 RhsT.getUnqualifiedType());
John Wiegley20c0da72011-04-27 23:09:49 +00003670 case BTT_IsConvertible:
Douglas Gregor9f361132011-01-27 20:28:01 +00003671 case BTT_IsConvertibleTo: {
3672 // C++0x [meta.rel]p4:
3673 // Given the following function prototype:
3674 //
3675 // template <class T>
3676 // typename add_rvalue_reference<T>::type create();
3677 //
3678 // the predicate condition for a template specialization
3679 // is_convertible<From, To> shall be satisfied if and only if
3680 // the return expression in the following code would be
3681 // well-formed, including any implicit conversions to the return
3682 // type of the function:
3683 //
3684 // To test() {
3685 // return create<From>();
3686 // }
3687 //
3688 // Access checking is performed as if in a context unrelated to To and
3689 // From. Only the validity of the immediate context of the expression
3690 // of the return-statement (including conversions to the return type)
3691 // is considered.
3692 //
3693 // We model the initialization as a copy-initialization of a temporary
3694 // of the appropriate type, which for this expression is identical to the
3695 // return statement (since NRVO doesn't apply).
Eli Friedman2217f852012-08-14 02:06:07 +00003696
3697 // Functions aren't allowed to return function or array types.
3698 if (RhsT->isFunctionType() || RhsT->isArrayType())
3699 return false;
3700
3701 // A return statement in a void function must have void type.
3702 if (RhsT->isVoidType())
3703 return LhsT->isVoidType();
3704
3705 // A function definition requires a complete, non-abstract return type.
3706 if (Self.RequireCompleteType(KeyLoc, RhsT, 0) ||
3707 Self.RequireNonAbstractType(KeyLoc, RhsT, 0))
3708 return false;
3709
3710 // Compute the result of add_rvalue_reference.
Douglas Gregor9f361132011-01-27 20:28:01 +00003711 if (LhsT->isObjectType() || LhsT->isFunctionType())
3712 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman2217f852012-08-14 02:06:07 +00003713
3714 // Build a fake source and destination for initialization.
Douglas Gregor9f361132011-01-27 20:28:01 +00003715 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorb608b982011-01-28 02:26:04 +00003716 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor9f361132011-01-27 20:28:01 +00003717 Expr::getValueKindForType(LhsT));
3718 Expr *FromPtr = &From;
3719 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3720 SourceLocation()));
3721
Eli Friedman3add9f02012-01-25 01:05:57 +00003722 // Perform the initialization in an unevaluated context within a SFINAE
3723 // trap at translation unit scope.
3724 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003725 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3726 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003727 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redl383616c2011-06-05 12:23:28 +00003728 if (Init.Failed())
Douglas Gregor9f361132011-01-27 20:28:01 +00003729 return false;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +00003730
Benjamin Kramer5354e772012-08-23 23:38:35 +00003731 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor9f361132011-01-27 20:28:01 +00003732 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3733 }
Douglas Gregor25d0a0f2012-02-23 07:33:15 +00003734
3735 case BTT_IsTriviallyAssignable: {
3736 // C++11 [meta.unary.prop]p3:
3737 // is_trivially_assignable is defined as:
3738 // is_assignable<T, U>::value is true and the assignment, as defined by
3739 // is_assignable, is known to call no operation that is not trivial
3740 //
3741 // is_assignable is defined as:
3742 // The expression declval<T>() = declval<U>() is well-formed when
3743 // treated as an unevaluated operand (Clause 5).
3744 //
3745 // For both, T and U shall be complete types, (possibly cv-qualified)
3746 // void, or arrays of unknown bound.
3747 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3748 Self.RequireCompleteType(KeyLoc, LhsT,
3749 diag::err_incomplete_type_used_in_type_trait_expr))
3750 return false;
3751 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3752 Self.RequireCompleteType(KeyLoc, RhsT,
3753 diag::err_incomplete_type_used_in_type_trait_expr))
3754 return false;
3755
3756 // cv void is never assignable.
3757 if (LhsT->isVoidType() || RhsT->isVoidType())
3758 return false;
3759
3760 // Build expressions that emulate the effect of declval<T>() and
3761 // declval<U>().
3762 if (LhsT->isObjectType() || LhsT->isFunctionType())
3763 LhsT = Self.Context.getRValueReferenceType(LhsT);
3764 if (RhsT->isObjectType() || RhsT->isFunctionType())
3765 RhsT = Self.Context.getRValueReferenceType(RhsT);
3766 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3767 Expr::getValueKindForType(LhsT));
3768 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3769 Expr::getValueKindForType(RhsT));
3770
3771 // Attempt the assignment in an unevaluated context within a SFINAE
3772 // trap at translation unit scope.
3773 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3774 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3775 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3776 ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs);
3777 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3778 return false;
3779
Douglas Gregor14b23272012-06-29 00:49:17 +00003780 // Under Objective-C ARC, if the destination has non-trivial Objective-C
3781 // lifetime, this is a non-trivial assignment.
3782 if (Self.getLangOpts().ObjCAutoRefCount &&
3783 hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
3784 return false;
3785
Douglas Gregor25d0a0f2012-02-23 07:33:15 +00003786 return !Result.get()->hasNonTrivialCall(Self.Context);
3787 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003788 }
3789 llvm_unreachable("Unknown type trait or not implemented");
3790}
3791
3792ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3793 SourceLocation KWLoc,
3794 TypeSourceInfo *LhsTSInfo,
3795 TypeSourceInfo *RhsTSInfo,
3796 SourceLocation RParen) {
3797 QualType LhsT = LhsTSInfo->getType();
3798 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003799
John McCalld89d30f2011-01-28 22:02:36 +00003800 if (BTT == BTT_TypeCompatible) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003801 if (getLangOpts().CPlusPlus) {
Francois Pichetf1872372010-12-08 22:35:30 +00003802 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3803 << SourceRange(KWLoc, RParen);
3804 return ExprError();
3805 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00003806 }
3807
3808 bool Value = false;
3809 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3810 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3811
Francois Pichetf1872372010-12-08 22:35:30 +00003812 // Select trait result type.
3813 QualType ResultType;
3814 switch (BTT) {
Francois Pichetf1872372010-12-08 22:35:30 +00003815 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley20c0da72011-04-27 23:09:49 +00003816 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3817 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichetf1872372010-12-08 22:35:30 +00003818 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor9f361132011-01-27 20:28:01 +00003819 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Douglas Gregor25d0a0f2012-02-23 07:33:15 +00003820 case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy;
Francois Pichetf1872372010-12-08 22:35:30 +00003821 }
3822
Francois Pichet6ad6f282010-12-07 00:08:36 +00003823 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3824 RhsTSInfo, Value, RParen,
Francois Pichetf1872372010-12-08 22:35:30 +00003825 ResultType));
Francois Pichet6ad6f282010-12-07 00:08:36 +00003826}
3827
John Wiegley21ff2e52011-04-28 00:16:57 +00003828ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3829 SourceLocation KWLoc,
3830 ParsedType Ty,
3831 Expr* DimExpr,
3832 SourceLocation RParen) {
3833 TypeSourceInfo *TSInfo;
3834 QualType T = GetTypeFromParser(Ty, &TSInfo);
3835 if (!TSInfo)
3836 TSInfo = Context.getTrivialTypeSourceInfo(T);
3837
3838 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3839}
3840
3841static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3842 QualType T, Expr *DimExpr,
3843 SourceLocation KeyLoc) {
Chandler Carruthd064c702011-05-01 08:41:10 +00003844 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley21ff2e52011-04-28 00:16:57 +00003845
3846 switch(ATT) {
3847 case ATT_ArrayRank:
3848 if (T->isArrayType()) {
3849 unsigned Dim = 0;
3850 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3851 ++Dim;
3852 T = AT->getElementType();
3853 }
3854 return Dim;
John Wiegley21ff2e52011-04-28 00:16:57 +00003855 }
John Wiegleycf566412011-04-28 02:06:46 +00003856 return 0;
3857
John Wiegley21ff2e52011-04-28 00:16:57 +00003858 case ATT_ArrayExtent: {
3859 llvm::APSInt Value;
3860 uint64_t Dim;
Richard Smith282e7e62012-02-04 09:53:13 +00003861 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregorab41fe92012-05-04 22:38:52 +00003862 diag::err_dimension_expr_not_constant_integer,
Richard Smith282e7e62012-02-04 09:53:13 +00003863 false).isInvalid())
3864 return 0;
3865 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbare7d6ca02012-03-09 21:38:22 +00003866 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3867 << DimExpr->getSourceRange();
Richard Smith282e7e62012-02-04 09:53:13 +00003868 return 0;
John Wiegleycf566412011-04-28 02:06:46 +00003869 }
Richard Smith282e7e62012-02-04 09:53:13 +00003870 Dim = Value.getLimitedValue();
John Wiegley21ff2e52011-04-28 00:16:57 +00003871
3872 if (T->isArrayType()) {
3873 unsigned D = 0;
3874 bool Matched = false;
3875 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3876 if (Dim == D) {
3877 Matched = true;
3878 break;
3879 }
3880 ++D;
3881 T = AT->getElementType();
3882 }
3883
John Wiegleycf566412011-04-28 02:06:46 +00003884 if (Matched && T->isArrayType()) {
3885 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3886 return CAT->getSize().getLimitedValue();
3887 }
John Wiegley21ff2e52011-04-28 00:16:57 +00003888 }
John Wiegleycf566412011-04-28 02:06:46 +00003889 return 0;
John Wiegley21ff2e52011-04-28 00:16:57 +00003890 }
3891 }
3892 llvm_unreachable("Unknown type trait or not implemented");
3893}
3894
3895ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3896 SourceLocation KWLoc,
3897 TypeSourceInfo *TSInfo,
3898 Expr* DimExpr,
3899 SourceLocation RParen) {
3900 QualType T = TSInfo->getType();
John Wiegley21ff2e52011-04-28 00:16:57 +00003901
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003902 // FIXME: This should likely be tracked as an APInt to remove any host
3903 // assumptions about the width of size_t on the target.
Chandler Carruthd064c702011-05-01 08:41:10 +00003904 uint64_t Value = 0;
3905 if (!T->isDependentType())
3906 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3907
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003908 // While the specification for these traits from the Embarcadero C++
3909 // compiler's documentation says the return type is 'unsigned int', Clang
3910 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3911 // compiler, there is no difference. On several other platforms this is an
3912 // important distinction.
John Wiegley21ff2e52011-04-28 00:16:57 +00003913 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth06207f62011-05-01 07:49:26 +00003914 DimExpr, RParen,
Chandler Carruthaf5a3c62011-05-01 08:48:21 +00003915 Context.getSizeType()));
John Wiegley21ff2e52011-04-28 00:16:57 +00003916}
3917
John Wiegley55262202011-04-25 06:54:41 +00003918ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003919 SourceLocation KWLoc,
3920 Expr *Queried,
3921 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003922 // If error parsing the expression, ignore.
3923 if (!Queried)
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003924 return ExprError();
John Wiegley55262202011-04-25 06:54:41 +00003925
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003926 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegley55262202011-04-25 06:54:41 +00003927
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003928 return Result;
John Wiegley55262202011-04-25 06:54:41 +00003929}
3930
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003931static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3932 switch (ET) {
3933 case ET_IsLValueExpr: return E->isLValue();
3934 case ET_IsRValueExpr: return E->isRValue();
3935 }
3936 llvm_unreachable("Expression trait not covered by switch");
3937}
3938
John Wiegley55262202011-04-25 06:54:41 +00003939ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003940 SourceLocation KWLoc,
3941 Expr *Queried,
3942 SourceLocation RParen) {
John Wiegley55262202011-04-25 06:54:41 +00003943 if (Queried->isTypeDependent()) {
3944 // Delay type-checking for type-dependent expressions.
3945 } else if (Queried->getType()->isPlaceholderType()) {
3946 ExprResult PE = CheckPlaceholderExpr(Queried);
3947 if (PE.isInvalid()) return ExprError();
3948 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3949 }
3950
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003951 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf7ef0002011-05-01 08:48:19 +00003952
Chandler Carruth4aa0af32011-05-01 07:44:20 +00003953 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3954 RParen, Context.BoolTy));
John Wiegley55262202011-04-25 06:54:41 +00003955}
3956
Richard Trieudd225092011-09-15 21:56:47 +00003957QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCallf89e55a2010-11-18 06:31:45 +00003958 ExprValueKind &VK,
3959 SourceLocation Loc,
3960 bool isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003961 assert(!LHS.get()->getType()->isPlaceholderType() &&
3962 !RHS.get()->getType()->isPlaceholderType() &&
John McCallea4aba02011-06-30 17:15:34 +00003963 "placeholders should have been weeded out by now");
3964
3965 // The LHS undergoes lvalue conversions if this is ->*.
3966 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00003967 LHS = DefaultLvalueConversion(LHS.take());
3968 if (LHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003969 }
3970
3971 // The RHS always undergoes lvalue conversions.
Richard Trieudd225092011-09-15 21:56:47 +00003972 RHS = DefaultLvalueConversion(RHS.take());
3973 if (RHS.isInvalid()) return QualType();
John McCallea4aba02011-06-30 17:15:34 +00003974
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003975 const char *OpSpelling = isIndirect ? "->*" : ".*";
3976 // C++ 5.5p2
3977 // The binary operator .* [p3: ->*] binds its second operand, which shall
3978 // be of type "pointer to member of T" (where T is a completely-defined
3979 // class type) [...]
Richard Trieudd225092011-09-15 21:56:47 +00003980 QualType RHSType = RHS.get()->getType();
3981 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregore7450f52009-03-24 19:52:54 +00003982 if (!MemPtr) {
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003983 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieudd225092011-09-15 21:56:47 +00003984 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003985 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00003986 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003987
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003988 QualType Class(MemPtr->getClass(), 0);
3989
Douglas Gregor7d520ba2010-10-13 20:41:14 +00003990 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3991 // member pointer points must be completely-defined. However, there is no
3992 // reason for this semantic distinction, and the rule is not enforced by
3993 // other compilers. Therefore, we do not check this property, as it is
3994 // likely to be considered a defect.
Sebastian Redl59fc2692010-04-10 10:14:54 +00003995
Sebastian Redl7c8bd602009-02-07 20:10:22 +00003996 // C++ 5.5p2
3997 // [...] to its first operand, which shall be of class T or of a class of
3998 // which T is an unambiguous and accessible base class. [p3: a pointer to
3999 // such a class]
Richard Trieudd225092011-09-15 21:56:47 +00004000 QualType LHSType = LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00004001 if (isIndirect) {
Richard Trieudd225092011-09-15 21:56:47 +00004002 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
4003 LHSType = Ptr->getPointeeType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00004004 else {
4005 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieudd225092011-09-15 21:56:47 +00004006 << OpSpelling << 1 << LHSType
Douglas Gregor849b2432010-03-31 17:46:05 +00004007 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl7c8bd602009-02-07 20:10:22 +00004008 return QualType();
4009 }
4010 }
4011
Richard Trieudd225092011-09-15 21:56:47 +00004012 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00004013 // If we want to check the hierarchy, we need a complete type.
Douglas Gregord10099e2012-05-04 16:32:21 +00004014 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
4015 OpSpelling, (int)isIndirect)) {
Sebastian Redl17e1d352010-04-23 17:18:26 +00004016 return QualType();
4017 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004018 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00004019 /*DetectVirtual=*/false);
Mike Stump390b4cc2009-05-16 07:39:55 +00004020 // FIXME: Would it be useful to print full ambiguity paths, or is that
4021 // overkill?
Richard Trieudd225092011-09-15 21:56:47 +00004022 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl7c8bd602009-02-07 20:10:22 +00004023 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
4024 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieudd225092011-09-15 21:56:47 +00004025 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl7c8bd602009-02-07 20:10:22 +00004026 return QualType();
4027 }
Eli Friedman3005efe2010-01-16 00:00:48 +00004028 // Cast LHS to type of use.
4029 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00004030 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redl906082e2010-07-20 04:20:21 +00004031
John McCallf871d0c2010-08-07 06:22:56 +00004032 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004033 BuildBasePathArray(Paths, BasePath);
Richard Trieudd225092011-09-15 21:56:47 +00004034 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
4035 &BasePath);
Sebastian Redl7c8bd602009-02-07 20:10:22 +00004036 }
4037
Richard Trieudd225092011-09-15 21:56:47 +00004038 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian05ebda92009-11-18 21:54:48 +00004039 // Diagnose use of pointer-to-member type which when used as
4040 // the functional cast in a pointer-to-member expression.
4041 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
4042 return QualType();
4043 }
John McCallf89e55a2010-11-18 06:31:45 +00004044
Sebastian Redl7c8bd602009-02-07 20:10:22 +00004045 // C++ 5.5p2
4046 // The result is an object or a function of the type specified by the
4047 // second operand.
4048 // The cv qualifiers are the union of those in the pointer and the left side,
4049 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl7c8bd602009-02-07 20:10:22 +00004050 QualType Result = MemPtr->getPointeeType();
Richard Trieudd225092011-09-15 21:56:47 +00004051 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCallf89e55a2010-11-18 06:31:45 +00004052
Douglas Gregor6b4df912011-01-26 16:40:18 +00004053 // C++0x [expr.mptr.oper]p6:
4054 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004055 // ill-formed if the second operand is a pointer to member function with
4056 // ref-qualifier &. In a ->* expression or in a .* expression whose object
4057 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor6b4df912011-01-26 16:40:18 +00004058 // is a pointer to member function with ref-qualifier &&.
4059 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
4060 switch (Proto->getRefQualifier()) {
4061 case RQ_None:
4062 // Do nothing
4063 break;
4064
4065 case RQ_LValue:
Richard Trieudd225092011-09-15 21:56:47 +00004066 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00004067 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00004068 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00004069 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004070
Douglas Gregor6b4df912011-01-26 16:40:18 +00004071 case RQ_RValue:
Richard Trieudd225092011-09-15 21:56:47 +00004072 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor6b4df912011-01-26 16:40:18 +00004073 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieudd225092011-09-15 21:56:47 +00004074 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor6b4df912011-01-26 16:40:18 +00004075 break;
4076 }
4077 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004078
John McCallf89e55a2010-11-18 06:31:45 +00004079 // C++ [expr.mptr.oper]p6:
4080 // The result of a .* expression whose second operand is a pointer
4081 // to a data member is of the same value category as its
4082 // first operand. The result of a .* expression whose second
4083 // operand is a pointer to a member function is a prvalue. The
4084 // result of an ->* expression is an lvalue if its second operand
4085 // is a pointer to data member and a prvalue otherwise.
John McCall864c0412011-04-26 20:42:42 +00004086 if (Result->isFunctionType()) {
John McCallf89e55a2010-11-18 06:31:45 +00004087 VK = VK_RValue;
John McCall864c0412011-04-26 20:42:42 +00004088 return Context.BoundMemberTy;
4089 } else if (isIndirect) {
John McCallf89e55a2010-11-18 06:31:45 +00004090 VK = VK_LValue;
John McCall864c0412011-04-26 20:42:42 +00004091 } else {
Richard Trieudd225092011-09-15 21:56:47 +00004092 VK = LHS.get()->getValueKind();
John McCall864c0412011-04-26 20:42:42 +00004093 }
John McCallf89e55a2010-11-18 06:31:45 +00004094
Sebastian Redl7c8bd602009-02-07 20:10:22 +00004095 return Result;
4096}
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004097
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004098/// \brief Try to convert a type to another according to C++0x 5.16p3.
4099///
4100/// This is part of the parameter validation for the ? operator. If either
4101/// value operand is a class type, the two operands are attempted to be
4102/// converted to each other. This function does the conversion in one direction.
Douglas Gregorb70cf442010-03-26 20:14:36 +00004103/// It returns true if the program is ill-formed and has already been diagnosed
4104/// as such.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004105static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
4106 SourceLocation QuestionLoc,
Douglas Gregorb70cf442010-03-26 20:14:36 +00004107 bool &HaveConversion,
4108 QualType &ToType) {
4109 HaveConversion = false;
4110 ToType = To->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004111
4112 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00004113 SourceLocation());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004114 // C++0x 5.16p3
4115 // The process for determining whether an operand expression E1 of type T1
4116 // can be converted to match an operand expression E2 of type T2 is defined
4117 // as follows:
4118 // -- If E2 is an lvalue:
John McCall7eb0a9e2010-11-24 05:12:34 +00004119 bool ToIsLvalue = To->isLValue();
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00004120 if (ToIsLvalue) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004121 // E1 can be converted to match E2 if E1 can be implicitly converted to
4122 // type "lvalue reference to T2", subject to the constraint that in the
4123 // conversion the reference must bind directly to E1.
Douglas Gregorb70cf442010-03-26 20:14:36 +00004124 QualType T = Self.Context.getLValueReferenceType(ToType);
4125 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004126
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004127 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregorb70cf442010-03-26 20:14:36 +00004128 if (InitSeq.isDirectReferenceBinding()) {
4129 ToType = T;
4130 HaveConversion = true;
4131 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004132 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004133
Douglas Gregorb70cf442010-03-26 20:14:36 +00004134 if (InitSeq.isAmbiguous())
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004135 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004136 }
John McCallb1bdc622010-02-25 01:37:24 +00004137
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004138 // -- If E2 is an rvalue, or if the conversion above cannot be done:
4139 // -- if E1 and E2 have class type, and the underlying class types are
4140 // the same or one is a base class of the other:
4141 QualType FTy = From->getType();
4142 QualType TTy = To->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00004143 const RecordType *FRec = FTy->getAs<RecordType>();
4144 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004145 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00004146 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004147 if (FRec && TRec &&
Douglas Gregorb70cf442010-03-26 20:14:36 +00004148 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004149 // E1 can be converted to match E2 if the class of T2 is the
4150 // same type as, or a base class of, the class of T1, and
4151 // [cv2 > cv1].
John McCallb1bdc622010-02-25 01:37:24 +00004152 if (FRec == TRec || FDerivedFromT) {
4153 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00004154 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004155 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redl383616c2011-06-05 12:23:28 +00004156 if (InitSeq) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00004157 HaveConversion = true;
4158 return false;
4159 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004160
Douglas Gregorb70cf442010-03-26 20:14:36 +00004161 if (InitSeq.isAmbiguous())
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004162 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004163 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004164 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004165
Douglas Gregorb70cf442010-03-26 20:14:36 +00004166 return false;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004167 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004168
Douglas Gregorb70cf442010-03-26 20:14:36 +00004169 // -- Otherwise: E1 can be converted to match E2 if E1 can be
4170 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004171 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregor0fd8ff72010-03-26 20:59:55 +00004172 // an rvalue).
4173 //
4174 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
4175 // to the array-to-pointer or function-to-pointer conversions.
4176 if (!TTy->getAs<TagType>())
4177 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004178
Douglas Gregorb70cf442010-03-26 20:14:36 +00004179 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004180 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redl383616c2011-06-05 12:23:28 +00004181 HaveConversion = !InitSeq.Failed();
Douglas Gregorb70cf442010-03-26 20:14:36 +00004182 ToType = TTy;
4183 if (InitSeq.isAmbiguous())
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004184 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregorb70cf442010-03-26 20:14:36 +00004185
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004186 return false;
4187}
4188
4189/// \brief Try to find a common type for two according to C++0x 5.16p5.
4190///
4191/// This is part of the parameter validation for the ? operator. If either
4192/// value operand is a class type, overload resolution is used to find a
4193/// conversion to a common type.
John Wiegley429bb272011-04-08 18:41:53 +00004194static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth82214a82011-02-18 23:54:50 +00004195 SourceLocation QuestionLoc) {
John Wiegley429bb272011-04-08 18:41:53 +00004196 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carruth82214a82011-02-18 23:54:50 +00004197 OverloadCandidateSet CandidateSet(QuestionLoc);
Richard Smith958ba642013-05-05 15:51:06 +00004198 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carruth82214a82011-02-18 23:54:50 +00004199 CandidateSet);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004200
4201 OverloadCandidateSet::iterator Best;
Chandler Carruth82214a82011-02-18 23:54:50 +00004202 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley429bb272011-04-08 18:41:53 +00004203 case OR_Success: {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004204 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley429bb272011-04-08 18:41:53 +00004205 ExprResult LHSRes =
4206 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
4207 Best->Conversions[0], Sema::AA_Converting);
4208 if (LHSRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004209 break;
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004210 LHS = LHSRes;
John Wiegley429bb272011-04-08 18:41:53 +00004211
4212 ExprResult RHSRes =
4213 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
4214 Best->Conversions[1], Sema::AA_Converting);
4215 if (RHSRes.isInvalid())
4216 break;
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004217 RHS = RHSRes;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004218 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00004219 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004220 return false;
John Wiegley429bb272011-04-08 18:41:53 +00004221 }
4222
Douglas Gregor20093b42009-12-09 23:02:17 +00004223 case OR_No_Viable_Function:
Chandler Carruth82214a82011-02-18 23:54:50 +00004224
4225 // Emit a better diagnostic if one of the expressions is a null pointer
4226 // constant and the other is a pointer type. In this case, the user most
4227 // likely forgot to take the address of the other expression.
John Wiegley429bb272011-04-08 18:41:53 +00004228 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth82214a82011-02-18 23:54:50 +00004229 return true;
4230
4231 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00004232 << LHS.get()->getType() << RHS.get()->getType()
4233 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004234 return true;
4235
Douglas Gregor20093b42009-12-09 23:02:17 +00004236 case OR_Ambiguous:
Chandler Carruth82214a82011-02-18 23:54:50 +00004237 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley429bb272011-04-08 18:41:53 +00004238 << LHS.get()->getType() << RHS.get()->getType()
4239 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump390b4cc2009-05-16 07:39:55 +00004240 // FIXME: Print the possible common types by printing the return types of
4241 // the viable candidates.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004242 break;
4243
Douglas Gregor20093b42009-12-09 23:02:17 +00004244 case OR_Deleted:
David Blaikieb219cfc2011-09-23 05:06:16 +00004245 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004246 }
4247 return true;
4248}
4249
Sebastian Redl76458502009-04-17 16:30:52 +00004250/// \brief Perform an "extended" implicit conversion as returned by
4251/// TryClassUnification.
John Wiegley429bb272011-04-08 18:41:53 +00004252static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregorb70cf442010-03-26 20:14:36 +00004253 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley429bb272011-04-08 18:41:53 +00004254 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregorb70cf442010-03-26 20:14:36 +00004255 SourceLocation());
John Wiegley429bb272011-04-08 18:41:53 +00004256 Expr *Arg = E.take();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004257 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +00004258 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregorb70cf442010-03-26 20:14:36 +00004259 if (Result.isInvalid())
Sebastian Redl76458502009-04-17 16:30:52 +00004260 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004261
John Wiegley429bb272011-04-08 18:41:53 +00004262 E = Result;
Sebastian Redl76458502009-04-17 16:30:52 +00004263 return false;
4264}
4265
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004266/// \brief Check the operands of ?: under C++ semantics.
4267///
4268/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4269/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smith50d61c82012-08-08 06:13:49 +00004270QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4271 ExprResult &RHS, ExprValueKind &VK,
4272 ExprObjectKind &OK,
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004273 SourceLocation QuestionLoc) {
Mike Stump390b4cc2009-05-16 07:39:55 +00004274 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4275 // interface pointers.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004276
Richard Smith604fb382012-08-07 22:06:48 +00004277 // C++11 [expr.cond]p1
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004278 // The first expression is contextually converted to bool.
John Wiegley429bb272011-04-08 18:41:53 +00004279 if (!Cond.get()->isTypeDependent()) {
4280 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
4281 if (CondRes.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004282 return QualType();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00004283 Cond = CondRes;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004284 }
4285
John McCallf89e55a2010-11-18 06:31:45 +00004286 // Assume r-value.
4287 VK = VK_RValue;
John McCall09431682010-11-18 19:01:18 +00004288 OK = OK_Ordinary;
John McCallf89e55a2010-11-18 06:31:45 +00004289
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004290 // Either of the arguments dependent?
John Wiegley429bb272011-04-08 18:41:53 +00004291 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004292 return Context.DependentTy;
4293
Richard Smith604fb382012-08-07 22:06:48 +00004294 // C++11 [expr.cond]p2
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004295 // If either the second or the third operand has type (cv) void, ...
John Wiegley429bb272011-04-08 18:41:53 +00004296 QualType LTy = LHS.get()->getType();
4297 QualType RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004298 bool LVoid = LTy->isVoidType();
4299 bool RVoid = RTy->isVoidType();
4300 if (LVoid || RVoid) {
4301 // ... then the [l2r] conversions are performed on the second and third
4302 // operands ...
John Wiegley429bb272011-04-08 18:41:53 +00004303 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4304 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4305 if (LHS.isInvalid() || RHS.isInvalid())
4306 return QualType();
Richard Smith604fb382012-08-07 22:06:48 +00004307
4308 // Finish off the lvalue-to-rvalue conversion by copy-initializing a
4309 // temporary if necessary. DefaultFunctionArrayLvalueConversion doesn't
4310 // do this part for us.
4311 ExprResult &NonVoid = LVoid ? RHS : LHS;
4312 if (NonVoid.get()->getType()->isRecordType() &&
4313 NonVoid.get()->isGLValue()) {
David Blaikie654f1d52012-09-10 22:05:41 +00004314 if (RequireNonAbstractType(QuestionLoc, NonVoid.get()->getType(),
4315 diag::err_allocation_of_abstract_type))
4316 return QualType();
Richard Smith604fb382012-08-07 22:06:48 +00004317 InitializedEntity Entity =
4318 InitializedEntity::InitializeTemporary(NonVoid.get()->getType());
4319 NonVoid = PerformCopyInitialization(Entity, SourceLocation(), NonVoid);
4320 if (NonVoid.isInvalid())
4321 return QualType();
4322 }
4323
John Wiegley429bb272011-04-08 18:41:53 +00004324 LTy = LHS.get()->getType();
4325 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004326
4327 // ... and one of the following shall hold:
4328 // -- The second or the third operand (but not both) is a throw-
Richard Smith604fb382012-08-07 22:06:48 +00004329 // expression; the result is of the type of the other and is a prvalue.
David Majnemerc063cb12013-06-02 08:40:42 +00004330 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenCasts());
4331 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenCasts());
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004332 if (LThrow && !RThrow)
4333 return RTy;
4334 if (RThrow && !LThrow)
4335 return LTy;
4336
4337 // -- Both the second and third operands have type void; the result is of
Richard Smith604fb382012-08-07 22:06:48 +00004338 // type void and is a prvalue.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004339 if (LVoid && RVoid)
4340 return Context.VoidTy;
4341
4342 // Neither holds, error.
4343 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4344 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley429bb272011-04-08 18:41:53 +00004345 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004346 return QualType();
4347 }
4348
4349 // Neither is void.
4350
Richard Smith50d61c82012-08-08 06:13:49 +00004351 // C++11 [expr.cond]p3
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004352 // Otherwise, if the second and third operand have different types, and
Richard Smith50d61c82012-08-08 06:13:49 +00004353 // either has (cv) class type [...] an attempt is made to convert each of
4354 // those operands to the type of the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004355 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004356 (LTy->isRecordType() || RTy->isRecordType())) {
4357 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
4358 // These return true if a single direction is already ambiguous.
Douglas Gregorb70cf442010-03-26 20:14:36 +00004359 QualType L2RType, R2LType;
4360 bool HaveL2R, HaveR2L;
John Wiegley429bb272011-04-08 18:41:53 +00004361 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004362 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004363 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004364 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004365
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004366 // If both can be converted, [...] the program is ill-formed.
4367 if (HaveL2R && HaveR2L) {
4368 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley429bb272011-04-08 18:41:53 +00004369 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004370 return QualType();
4371 }
4372
4373 // If exactly one conversion is possible, that conversion is applied to
4374 // the chosen operand and the converted operands are used in place of the
4375 // original operands for the remainder of this section.
4376 if (HaveL2R) {
John Wiegley429bb272011-04-08 18:41:53 +00004377 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004378 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004379 LTy = LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004380 } else if (HaveR2L) {
John Wiegley429bb272011-04-08 18:41:53 +00004381 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004382 return QualType();
John Wiegley429bb272011-04-08 18:41:53 +00004383 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004384 }
4385 }
4386
Richard Smith50d61c82012-08-08 06:13:49 +00004387 // C++11 [expr.cond]p3
4388 // if both are glvalues of the same value category and the same type except
4389 // for cv-qualification, an attempt is made to convert each of those
4390 // operands to the type of the other.
4391 ExprValueKind LVK = LHS.get()->getValueKind();
4392 ExprValueKind RVK = RHS.get()->getValueKind();
4393 if (!Context.hasSameType(LTy, RTy) &&
4394 Context.hasSameUnqualifiedType(LTy, RTy) &&
4395 LVK == RVK && LVK != VK_RValue) {
4396 // Since the unqualified types are reference-related and we require the
4397 // result to be as if a reference bound directly, the only conversion
4398 // we can perform is to add cv-qualifiers.
4399 Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
4400 Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
4401 if (RCVR.isStrictSupersetOf(LCVR)) {
4402 LHS = ImpCastExprToType(LHS.take(), RTy, CK_NoOp, LVK);
4403 LTy = LHS.get()->getType();
4404 }
4405 else if (LCVR.isStrictSupersetOf(RCVR)) {
4406 RHS = ImpCastExprToType(RHS.take(), LTy, CK_NoOp, RVK);
4407 RTy = RHS.get()->getType();
4408 }
4409 }
4410
4411 // C++11 [expr.cond]p4
John McCallf89e55a2010-11-18 06:31:45 +00004412 // If the second and third operands are glvalues of the same value
4413 // category and have the same type, the result is of that type and
4414 // value category and it is a bit-field if the second or the third
4415 // operand is a bit-field, or if both are bit-fields.
John McCall09431682010-11-18 19:01:18 +00004416 // We only extend this to bitfields, not to the crazy other kinds of
4417 // l-values.
Douglas Gregor1927b1f2010-04-01 22:47:07 +00004418 bool Same = Context.hasSameType(LTy, RTy);
Richard Smith50d61c82012-08-08 06:13:49 +00004419 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley429bb272011-04-08 18:41:53 +00004420 LHS.get()->isOrdinaryOrBitFieldObject() &&
4421 RHS.get()->isOrdinaryOrBitFieldObject()) {
4422 VK = LHS.get()->getValueKind();
4423 if (LHS.get()->getObjectKind() == OK_BitField ||
4424 RHS.get()->getObjectKind() == OK_BitField)
John McCall09431682010-11-18 19:01:18 +00004425 OK = OK_BitField;
John McCallf89e55a2010-11-18 06:31:45 +00004426 return LTy;
Fariborz Jahanian3911a1a2010-09-25 01:08:05 +00004427 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004428
Richard Smith50d61c82012-08-08 06:13:49 +00004429 // C++11 [expr.cond]p5
4430 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004431 // do not have the same type, and either has (cv) class type, ...
4432 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4433 // ... overload resolution is used to determine the conversions (if any)
4434 // to be applied to the operands. If the overload resolution fails, the
4435 // program is ill-formed.
4436 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4437 return QualType();
4438 }
4439
Richard Smith50d61c82012-08-08 06:13:49 +00004440 // C++11 [expr.cond]p6
4441 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004442 // conversions are performed on the second and third operands.
John Wiegley429bb272011-04-08 18:41:53 +00004443 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4444 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4445 if (LHS.isInvalid() || RHS.isInvalid())
4446 return QualType();
4447 LTy = LHS.get()->getType();
4448 RTy = RHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004449
4450 // After those conversions, one of the following shall hold:
4451 // -- The second and third operands have the same type; the result
Douglas Gregorb65a4582010-05-19 23:40:50 +00004452 // is of that type. If the operands have class type, the result
4453 // is a prvalue temporary of the result type, which is
4454 // copy-initialized from either the second operand or the third
4455 // operand depending on the value of the first operand.
4456 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4457 if (LTy->isRecordType()) {
4458 // The operands have class type. Make a temporary copy.
David Blaikie654f1d52012-09-10 22:05:41 +00004459 if (RequireNonAbstractType(QuestionLoc, LTy,
4460 diag::err_allocation_of_abstract_type))
4461 return QualType();
Douglas Gregorb65a4582010-05-19 23:40:50 +00004462 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie654f1d52012-09-10 22:05:41 +00004463
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004464 ExprResult LHSCopy = PerformCopyInitialization(Entity,
4465 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00004466 LHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00004467 if (LHSCopy.isInvalid())
4468 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004469
4470 ExprResult RHSCopy = PerformCopyInitialization(Entity,
4471 SourceLocation(),
John Wiegley429bb272011-04-08 18:41:53 +00004472 RHS);
Douglas Gregorb65a4582010-05-19 23:40:50 +00004473 if (RHSCopy.isInvalid())
4474 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004475
John Wiegley429bb272011-04-08 18:41:53 +00004476 LHS = LHSCopy;
4477 RHS = RHSCopy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00004478 }
4479
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004480 return LTy;
Douglas Gregorb65a4582010-05-19 23:40:50 +00004481 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004482
Douglas Gregorfb4a5432010-05-18 22:42:18 +00004483 // Extension: conditional operator involving vector types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004484 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedmanb9b4b782011-06-23 18:10:35 +00004485 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregorfb4a5432010-05-18 22:42:18 +00004486
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004487 // -- The second and third operands have arithmetic or enumeration type;
4488 // the usual arithmetic conversions are performed to bring them to a
4489 // common type, and the result is of that type.
4490 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4491 UsualArithmeticConversions(LHS, RHS);
John Wiegley429bb272011-04-08 18:41:53 +00004492 if (LHS.isInvalid() || RHS.isInvalid())
4493 return QualType();
4494 return LHS.get()->getType();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004495 }
4496
4497 // -- The second and third operands have pointer type, or one has pointer
Richard Smith50d61c82012-08-08 06:13:49 +00004498 // type and the other is a null pointer constant, or both are null
4499 // pointer constants, at least one of which is non-integral; pointer
4500 // conversions and qualification conversions are performed to bring them
4501 // to their composite pointer type. The result is of the composite
4502 // pointer type.
Eli Friedmande8ac492010-01-02 22:56:07 +00004503 // -- The second and third operands have pointer to member type, or one has
4504 // pointer to member type and the other is a null pointer constant;
4505 // pointer to member conversions and qualification conversions are
4506 // performed to bring them to a common type, whose cv-qualification
4507 // shall match the cv-qualification of either the second or the third
4508 // operand. The result is of the common type.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004509 bool NonStandardCompositeType = false;
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004510 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004511 isSFINAEContext()? 0 : &NonStandardCompositeType);
4512 if (!Composite.isNull()) {
4513 if (NonStandardCompositeType)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004514 Diag(QuestionLoc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004515 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4516 << LTy << RTy << Composite
John Wiegley429bb272011-04-08 18:41:53 +00004517 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004518
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004519 return Composite;
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004520 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004521
Douglas Gregor1927b1f2010-04-01 22:47:07 +00004522 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian55016362009-12-10 20:46:08 +00004523 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4524 if (!Composite.isNull())
4525 return Composite;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004526
Chandler Carruth7ef93242011-02-19 00:13:59 +00004527 // Check if we are using a null with a non-pointer type.
John Wiegley429bb272011-04-08 18:41:53 +00004528 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth7ef93242011-02-19 00:13:59 +00004529 return QualType();
4530
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004531 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley429bb272011-04-08 18:41:53 +00004532 << LHS.get()->getType() << RHS.get()->getType()
4533 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004534 return QualType();
4535}
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004536
4537/// \brief Find a merged pointer type and convert the two expressions to it.
4538///
Douglas Gregor20b3e992009-08-24 17:42:35 +00004539/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith50d61c82012-08-08 06:13:49 +00004540/// and @p E2 according to C++11 5.9p2. It converts both expressions to this
Douglas Gregor20b3e992009-08-24 17:42:35 +00004541/// type and returns it.
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004542/// It does not emit diagnostics.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004543///
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004544/// \param Loc The location of the operator requiring these two expressions to
4545/// be converted to the composite pointer type.
4546///
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004547/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4548/// a non-standard (but still sane) composite type to which both expressions
4549/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4550/// will be set true.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004551QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004552 Expr *&E1, Expr *&E2,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004553 bool *NonStandardCompositeType) {
4554 if (NonStandardCompositeType)
4555 *NonStandardCompositeType = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004556
David Blaikie4e4d0842012-03-11 07:00:24 +00004557 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004558 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004559
Richard Smith50d61c82012-08-08 06:13:49 +00004560 // C++11 5.9p2
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004561 // Pointer conversions and qualification conversions are performed on
4562 // pointer operands to bring them to their composite pointer type. If
4563 // one operand is a null pointer constant, the composite pointer type is
Richard Smith50d61c82012-08-08 06:13:49 +00004564 // std::nullptr_t if the other operand is also a null pointer constant or,
4565 // if the other operand is a pointer, the type of the other operand.
4566 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4567 !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
4568 if (T1->isNullPtrType() &&
4569 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4570 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
4571 return T1;
4572 }
4573 if (T2->isNullPtrType() &&
4574 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4575 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
4576 return T2;
4577 }
4578 return QualType();
4579 }
4580
Douglas Gregorce940492009-09-25 04:25:58 +00004581 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004582 if (T2->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00004583 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004584 else
John Wiegley429bb272011-04-08 18:41:53 +00004585 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004586 return T2;
4587 }
Douglas Gregorce940492009-09-25 04:25:58 +00004588 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004589 if (T1->isMemberPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00004590 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004591 else
John Wiegley429bb272011-04-08 18:41:53 +00004592 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004593 return T1;
4594 }
Mike Stump1eb44332009-09-09 15:08:12 +00004595
Douglas Gregor20b3e992009-08-24 17:42:35 +00004596 // Now both have to be pointers or member pointers.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004597 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4598 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004599 return QualType();
4600
4601 // Otherwise, of one of the operands has type "pointer to cv1 void," then
4602 // the other has type "pointer to cv2 T" and the composite pointer type is
4603 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4604 // Otherwise, the composite pointer type is a pointer type similar to the
4605 // type of one of the operands, with a cv-qualification signature that is
4606 // the union of the cv-qualification signatures of the operand types.
4607 // In practice, the first part here is redundant; it's subsumed by the second.
4608 // What we do here is, we build the two possible composite types, and try the
4609 // conversions in both directions. If only one works, or if the two composite
4610 // types are the same, we have succeeded.
John McCall0953e762009-09-24 19:53:00 +00004611 // FIXME: extended qualifiers?
Chris Lattner5f9e2722011-07-23 10:55:15 +00004612 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redla439e6f2009-11-16 21:03:45 +00004613 QualifierVector QualifierUnion;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004614 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redla439e6f2009-11-16 21:03:45 +00004615 ContainingClassVector;
4616 ContainingClassVector MemberOfClass;
4617 QualType Composite1 = Context.getCanonicalType(T1),
4618 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004619 unsigned NeedConstBefore = 0;
Douglas Gregor20b3e992009-08-24 17:42:35 +00004620 do {
4621 const PointerType *Ptr1, *Ptr2;
4622 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4623 (Ptr2 = Composite2->getAs<PointerType>())) {
4624 Composite1 = Ptr1->getPointeeType();
4625 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004626
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004627 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004628 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004629 if (NonStandardCompositeType &&
4630 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4631 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004632
Douglas Gregor20b3e992009-08-24 17:42:35 +00004633 QualifierUnion.push_back(
4634 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4635 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
4636 continue;
4637 }
Mike Stump1eb44332009-09-09 15:08:12 +00004638
Douglas Gregor20b3e992009-08-24 17:42:35 +00004639 const MemberPointerType *MemPtr1, *MemPtr2;
4640 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4641 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4642 Composite1 = MemPtr1->getPointeeType();
4643 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004644
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004645 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004646 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004647 if (NonStandardCompositeType &&
4648 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4649 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004650
Douglas Gregor20b3e992009-08-24 17:42:35 +00004651 QualifierUnion.push_back(
4652 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4653 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4654 MemPtr2->getClass()));
4655 continue;
4656 }
Mike Stump1eb44332009-09-09 15:08:12 +00004657
Douglas Gregor20b3e992009-08-24 17:42:35 +00004658 // FIXME: block pointer types?
Mike Stump1eb44332009-09-09 15:08:12 +00004659
Douglas Gregor20b3e992009-08-24 17:42:35 +00004660 // Cannot unwrap any more types.
4661 break;
4662 } while (true);
Mike Stump1eb44332009-09-09 15:08:12 +00004663
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004664 if (NeedConstBefore && NonStandardCompositeType) {
4665 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004666 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00004667 // requirements of C++ [conv.qual]p4 bullet 3.
4668 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4669 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4670 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4671 *NonStandardCompositeType = true;
4672 }
4673 }
4674 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004675
Douglas Gregor20b3e992009-08-24 17:42:35 +00004676 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redla439e6f2009-11-16 21:03:45 +00004677 ContainingClassVector::reverse_iterator MOC
4678 = MemberOfClass.rbegin();
4679 for (QualifierVector::reverse_iterator
4680 I = QualifierUnion.rbegin(),
4681 E = QualifierUnion.rend();
Douglas Gregor20b3e992009-08-24 17:42:35 +00004682 I != E; (void)++I, ++MOC) {
John McCall0953e762009-09-24 19:53:00 +00004683 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004684 if (MOC->first && MOC->second) {
4685 // Rebuild member pointer type
John McCall0953e762009-09-24 19:53:00 +00004686 Composite1 = Context.getMemberPointerType(
4687 Context.getQualifiedType(Composite1, Quals),
4688 MOC->first);
4689 Composite2 = Context.getMemberPointerType(
4690 Context.getQualifiedType(Composite2, Quals),
4691 MOC->second);
Douglas Gregor20b3e992009-08-24 17:42:35 +00004692 } else {
4693 // Rebuild pointer type
John McCall0953e762009-09-24 19:53:00 +00004694 Composite1
4695 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4696 Composite2
4697 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregor20b3e992009-08-24 17:42:35 +00004698 }
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004699 }
4700
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004701 // Try to convert to the first composite pointer type.
4702 InitializedEntity Entity1
4703 = InitializedEntity::InitializeTemporary(Composite1);
4704 InitializationKind Kind
4705 = InitializationKind::CreateCopy(Loc, SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004706 InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
4707 InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
Mike Stump1eb44332009-09-09 15:08:12 +00004708
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004709 if (E1ToC1 && E2ToC1) {
4710 // Conversion to Composite1 is viable.
4711 if (!Context.hasSameType(Composite1, Composite2)) {
4712 // Composite2 is a different type from Composite1. Check whether
4713 // Composite2 is also viable.
4714 InitializedEntity Entity2
4715 = InitializedEntity::InitializeTemporary(Composite2);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004716 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4717 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004718 if (E1ToC2 && E2ToC2) {
4719 // Both Composite1 and Composite2 are viable and are different;
4720 // this is an ambiguity.
4721 return QualType();
4722 }
4723 }
4724
4725 // Convert E1 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004726 ExprResult E1Result
Benjamin Kramer5354e772012-08-23 23:38:35 +00004727 = E1ToC1.Perform(*this, Entity1, Kind, E1);
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004728 if (E1Result.isInvalid())
4729 return QualType();
4730 E1 = E1Result.takeAs<Expr>();
4731
4732 // Convert E2 to Composite1
John McCall60d7b3a2010-08-24 06:29:42 +00004733 ExprResult E2Result
Benjamin Kramer5354e772012-08-23 23:38:35 +00004734 = E2ToC1.Perform(*this, Entity1, Kind, E2);
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004735 if (E2Result.isInvalid())
4736 return QualType();
4737 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004738
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004739 return Composite1;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004740 }
4741
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004742 // Check whether Composite2 is viable.
4743 InitializedEntity Entity2
4744 = InitializedEntity::InitializeTemporary(Composite2);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00004745 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4746 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004747 if (!E1ToC2 || !E2ToC2)
4748 return QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004749
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004750 // Convert E1 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004751 ExprResult E1Result
Benjamin Kramer5354e772012-08-23 23:38:35 +00004752 = E1ToC2.Perform(*this, Entity2, Kind, E1);
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004753 if (E1Result.isInvalid())
4754 return QualType();
4755 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004756
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004757 // Convert E2 to Composite2
John McCall60d7b3a2010-08-24 06:29:42 +00004758 ExprResult E2Result
Benjamin Kramer5354e772012-08-23 23:38:35 +00004759 = E2ToC2.Perform(*this, Entity2, Kind, E2);
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004760 if (E2Result.isInvalid())
4761 return QualType();
4762 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004763
Douglas Gregor8f00dcf2010-04-16 23:20:25 +00004764 return Composite2;
Sebastian Redld1bd7fc2009-04-19 19:26:31 +00004765}
Anders Carlsson165a0a02009-05-17 18:41:29 +00004766
John McCall60d7b3a2010-08-24 06:29:42 +00004767ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor19cc1c72010-11-01 21:10:29 +00004768 if (!E)
4769 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004770
John McCallf85e1932011-06-15 23:02:42 +00004771 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4772
4773 // If the result is a glvalue, we shouldn't bind it.
4774 if (!E->isRValue())
Anders Carlsson089c2602009-08-15 23:41:35 +00004775 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004776
John McCallf85e1932011-06-15 23:02:42 +00004777 // In ARC, calls that return a retainable type can return retained,
4778 // in which case we have to insert a consuming cast.
David Blaikie4e4d0842012-03-11 07:00:24 +00004779 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00004780 E->getType()->isObjCRetainableType()) {
4781
4782 bool ReturnsRetained;
4783
4784 // For actual calls, we compute this by examining the type of the
4785 // called value.
4786 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4787 Expr *Callee = Call->getCallee()->IgnoreParens();
4788 QualType T = Callee->getType();
4789
4790 if (T == Context.BoundMemberTy) {
4791 // Handle pointer-to-members.
4792 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4793 T = BinOp->getRHS()->getType();
4794 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4795 T = Mem->getMemberDecl()->getType();
4796 }
4797
4798 if (const PointerType *Ptr = T->getAs<PointerType>())
4799 T = Ptr->getPointeeType();
4800 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4801 T = Ptr->getPointeeType();
4802 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4803 T = MemPtr->getPointeeType();
4804
4805 const FunctionType *FTy = T->getAs<FunctionType>();
4806 assert(FTy && "call to value not of function type?");
4807 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4808
4809 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4810 // type always produce a +1 object.
4811 } else if (isa<StmtExpr>(E)) {
4812 ReturnsRetained = true;
4813
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004814 // We hit this case with the lambda conversion-to-block optimization;
4815 // we don't want any extra casts here.
4816 } else if (isa<CastExpr>(E) &&
4817 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
4818 return Owned(E);
4819
John McCallf85e1932011-06-15 23:02:42 +00004820 // For message sends and property references, we try to find an
4821 // actual method. FIXME: we should infer retention by selector in
4822 // cases where we don't have an actual method.
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004823 } else {
4824 ObjCMethodDecl *D = 0;
4825 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4826 D = Send->getMethodDecl();
Patrick Beardeb382ec2012-04-19 00:25:12 +00004827 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4828 D = BoxedExpr->getBoxingMethod();
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004829 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4830 D = ArrayLit->getArrayWithObjectsMethod();
4831 } else if (ObjCDictionaryLiteral *DictLit
4832 = dyn_cast<ObjCDictionaryLiteral>(E)) {
4833 D = DictLit->getDictWithObjectsMethod();
4834 }
John McCallf85e1932011-06-15 23:02:42 +00004835
4836 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCallfc4b1912011-08-03 07:02:44 +00004837
4838 // Don't do reclaims on performSelector calls; despite their
4839 // return type, the invoked method doesn't necessarily actually
4840 // return an object.
4841 if (!ReturnsRetained &&
4842 D && D->getMethodFamily() == OMF_performSelector)
4843 return Owned(E);
John McCallf85e1932011-06-15 23:02:42 +00004844 }
4845
John McCall567c5862011-11-14 19:53:16 +00004846 // Don't reclaim an object of Class type.
4847 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4848 return Owned(E);
4849
John McCall7e5e5f42011-07-07 06:58:02 +00004850 ExprNeedsCleanups = true;
4851
John McCall33e56f32011-09-10 06:18:15 +00004852 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4853 : CK_ARCReclaimReturnedObject);
John McCall7e5e5f42011-07-07 06:58:02 +00004854 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4855 VK_RValue));
John McCallf85e1932011-06-15 23:02:42 +00004856 }
4857
David Blaikie4e4d0842012-03-11 07:00:24 +00004858 if (!getLangOpts().CPlusPlus)
John McCallf85e1932011-06-15 23:02:42 +00004859 return Owned(E);
Douglas Gregor51326552009-12-24 18:51:59 +00004860
Peter Collingbourneb4ab8432012-01-26 03:33:51 +00004861 // Search for the base element type (cf. ASTContext::getBaseElementType) with
4862 // a fast path for the common case that the type is directly a RecordType.
4863 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4864 const RecordType *RT = 0;
4865 while (!RT) {
4866 switch (T->getTypeClass()) {
4867 case Type::Record:
4868 RT = cast<RecordType>(T);
4869 break;
4870 case Type::ConstantArray:
4871 case Type::IncompleteArray:
4872 case Type::VariableArray:
4873 case Type::DependentSizedArray:
4874 T = cast<ArrayType>(T)->getElementType().getTypePtr();
4875 break;
4876 default:
4877 return Owned(E);
4878 }
4879 }
Mike Stump1eb44332009-09-09 15:08:12 +00004880
Richard Smith76f3f692012-02-22 02:04:18 +00004881 // That should be enough to guarantee that this type is complete, if we're
4882 // not processing a decltype expression.
Jeffrey Yasskinb7ee2e52011-01-27 19:17:54 +00004883 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith213d70b2012-02-18 04:13:32 +00004884 if (RD->isInvalidDecl() || RD->isDependentContext())
John McCall86ff3082010-02-04 22:26:26 +00004885 return Owned(E);
Richard Smith76f3f692012-02-22 02:04:18 +00004886
4887 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
4888 CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD);
John McCallf85e1932011-06-15 23:02:42 +00004889
John McCallf85e1932011-06-15 23:02:42 +00004890 if (Destructor) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00004891 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCallc91cc662010-04-07 00:41:46 +00004892 CheckDestructorAccess(E->getExprLoc(), Destructor,
4893 PDiag(diag::err_access_dtor_temp)
4894 << E->getType());
Richard Smith82f145d2013-05-04 06:44:46 +00004895 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
4896 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00004897
Richard Smith76f3f692012-02-22 02:04:18 +00004898 // If destructor is trivial, we can avoid the extra copy.
4899 if (Destructor->isTrivial())
4900 return Owned(E);
Richard Smith213d70b2012-02-18 04:13:32 +00004901
John McCall80ee6e82011-11-10 05:35:25 +00004902 // We need a cleanup, but we don't need to remember the temporary.
John McCallf85e1932011-06-15 23:02:42 +00004903 ExprNeedsCleanups = true;
Richard Smith76f3f692012-02-22 02:04:18 +00004904 }
Richard Smith213d70b2012-02-18 04:13:32 +00004905
4906 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smith76f3f692012-02-22 02:04:18 +00004907 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
4908
4909 if (IsDecltype)
4910 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
4911
4912 return Owned(Bind);
Anders Carlssondef11992009-05-30 20:36:53 +00004913}
4914
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004915ExprResult
John McCall4765fa02010-12-06 08:20:24 +00004916Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregor90f93822009-12-22 22:17:25 +00004917 if (SubExpr.isInvalid())
4918 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004919
John McCall4765fa02010-12-06 08:20:24 +00004920 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregor90f93822009-12-22 22:17:25 +00004921}
4922
John McCall80ee6e82011-11-10 05:35:25 +00004923Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4924 assert(SubExpr && "sub expression can't be null!");
4925
Eli Friedmand2cce132012-02-02 23:15:15 +00004926 CleanupVarDeclMarking();
4927
John McCall80ee6e82011-11-10 05:35:25 +00004928 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4929 assert(ExprCleanupObjects.size() >= FirstCleanup);
4930 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4931 if (!ExprNeedsCleanups)
4932 return SubExpr;
4933
4934 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4935 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4936 ExprCleanupObjects.size() - FirstCleanup);
4937
4938 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4939 DiscardCleanupsInEvaluationContext();
4940
4941 return E;
4942}
4943
John McCall4765fa02010-12-06 08:20:24 +00004944Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004945 assert(SubStmt && "sub statement can't be null!");
4946
Eli Friedmand2cce132012-02-02 23:15:15 +00004947 CleanupVarDeclMarking();
4948
John McCallf85e1932011-06-15 23:02:42 +00004949 if (!ExprNeedsCleanups)
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004950 return SubStmt;
4951
4952 // FIXME: In order to attach the temporaries, wrap the statement into
4953 // a StmtExpr; currently this is only used for asm statements.
4954 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4955 // a new AsmStmtWithTemporaries.
Nico Weberd36aa352012-12-29 20:03:39 +00004956 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004957 SourceLocation(),
4958 SourceLocation());
4959 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4960 SourceLocation());
John McCall4765fa02010-12-06 08:20:24 +00004961 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00004962}
4963
Richard Smith76f3f692012-02-22 02:04:18 +00004964/// Process the expression contained within a decltype. For such expressions,
4965/// certain semantic checks on temporaries are delayed until this point, and
4966/// are omitted for the 'topmost' call in the decltype expression. If the
4967/// topmost call bound a temporary, strip that temporary off the expression.
4968ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer1b486332012-11-15 15:18:42 +00004969 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smith76f3f692012-02-22 02:04:18 +00004970
4971 // C++11 [expr.call]p11:
4972 // If a function call is a prvalue of object type,
4973 // -- if the function call is either
4974 // -- the operand of a decltype-specifier, or
4975 // -- the right operand of a comma operator that is the operand of a
4976 // decltype-specifier,
4977 // a temporary object is not introduced for the prvalue.
4978
4979 // Recursively rebuild ParenExprs and comma expressions to strip out the
4980 // outermost CXXBindTemporaryExpr, if any.
4981 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4982 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
4983 if (SubExpr.isInvalid())
4984 return ExprError();
4985 if (SubExpr.get() == PE->getSubExpr())
4986 return Owned(E);
4987 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take());
4988 }
4989 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4990 if (BO->getOpcode() == BO_Comma) {
4991 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
4992 if (RHS.isInvalid())
4993 return ExprError();
4994 if (RHS.get() == BO->getRHS())
4995 return Owned(E);
4996 return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(),
4997 BO_Comma, BO->getType(),
4998 BO->getValueKind(),
4999 BO->getObjectKind(),
Lang Hamesbe9af122012-10-02 04:45:10 +00005000 BO->getOperatorLoc(),
5001 BO->isFPContractable()));
Richard Smith76f3f692012-02-22 02:04:18 +00005002 }
5003 }
5004
5005 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
5006 if (TopBind)
5007 E = TopBind->getSubExpr();
5008
5009 // Disable the special decltype handling now.
Benjamin Kramer1b486332012-11-15 15:18:42 +00005010 ExprEvalContexts.back().IsDecltype = false;
Richard Smith76f3f692012-02-22 02:04:18 +00005011
Richard Smithd22f0842012-07-28 19:54:11 +00005012 // In MS mode, don't perform any extra checking of call return types within a
5013 // decltype expression.
5014 if (getLangOpts().MicrosoftMode)
5015 return Owned(E);
5016
Richard Smith76f3f692012-02-22 02:04:18 +00005017 // Perform the semantic checks we delayed until this point.
5018 CallExpr *TopCall = dyn_cast<CallExpr>(E);
Benjamin Kramer1b486332012-11-15 15:18:42 +00005019 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
5020 I != N; ++I) {
5021 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smith76f3f692012-02-22 02:04:18 +00005022 if (Call == TopCall)
5023 continue;
5024
5025 if (CheckCallReturnType(Call->getCallReturnType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +00005026 Call->getLocStart(),
Richard Smith76f3f692012-02-22 02:04:18 +00005027 Call, Call->getDirectCallee()))
5028 return ExprError();
5029 }
5030
5031 // Now all relevant types are complete, check the destructors are accessible
5032 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer1b486332012-11-15 15:18:42 +00005033 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
5034 I != N; ++I) {
5035 CXXBindTemporaryExpr *Bind =
5036 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smith76f3f692012-02-22 02:04:18 +00005037 if (Bind == TopBind)
5038 continue;
5039
5040 CXXTemporary *Temp = Bind->getTemporary();
5041
5042 CXXRecordDecl *RD =
5043 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5044 CXXDestructorDecl *Destructor = LookupDestructor(RD);
5045 Temp->setDestructor(Destructor);
5046
Richard Smith2f68ca02012-05-11 22:20:10 +00005047 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
5048 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smith76f3f692012-02-22 02:04:18 +00005049 PDiag(diag::err_access_dtor_temp)
Richard Smith2f68ca02012-05-11 22:20:10 +00005050 << Bind->getType());
Richard Smith82f145d2013-05-04 06:44:46 +00005051 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
5052 return ExprError();
Richard Smith76f3f692012-02-22 02:04:18 +00005053
5054 // We need a cleanup, but we don't need to remember the temporary.
5055 ExprNeedsCleanups = true;
5056 }
5057
5058 // Possibly strip off the top CXXBindTemporaryExpr.
5059 return Owned(E);
5060}
5061
John McCall60d7b3a2010-08-24 06:29:42 +00005062ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005063Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallb3d87482010-08-24 05:47:05 +00005064 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00005065 bool &MayBePseudoDestructor) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +00005066 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCall60d7b3a2010-08-24 06:29:42 +00005067 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCall9ae2f072010-08-23 23:25:46 +00005068 if (Result.isInvalid()) return ExprError();
5069 Base = Result.get();
Mike Stump1eb44332009-09-09 15:08:12 +00005070
John McCall3c3b7f92011-10-25 17:37:35 +00005071 Result = CheckPlaceholderExpr(Base);
5072 if (Result.isInvalid()) return ExprError();
5073 Base = Result.take();
5074
John McCall9ae2f072010-08-23 23:25:46 +00005075 QualType BaseType = Base->getType();
Douglas Gregord4dca082010-02-24 18:44:31 +00005076 MayBePseudoDestructor = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00005077 if (BaseType->isDependentType()) {
Douglas Gregor43d88632009-11-04 22:49:18 +00005078 // If we have a pointer to a dependent type and are using the -> operator,
5079 // the object type is the type that the pointer points to. We might still
5080 // have enough information about that type to do something useful.
5081 if (OpKind == tok::arrow)
5082 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
5083 BaseType = Ptr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005084
John McCallb3d87482010-08-24 05:47:05 +00005085 ObjectType = ParsedType::make(BaseType);
Douglas Gregord4dca082010-02-24 18:44:31 +00005086 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00005087 return Owned(Base);
Douglas Gregor2dd078a2009-09-02 22:59:36 +00005088 }
Mike Stump1eb44332009-09-09 15:08:12 +00005089
Douglas Gregor2dd078a2009-09-02 22:59:36 +00005090 // C++ [over.match.oper]p8:
Mike Stump1eb44332009-09-09 15:08:12 +00005091 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregor2dd078a2009-09-02 22:59:36 +00005092 // returned, with the original second operand.
5093 if (OpKind == tok::arrow) {
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +00005094 bool NoArrowOperatorFound = false;
5095 bool FirstIteration = true;
5096 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc4e83212009-09-30 01:01:30 +00005097 // The set of types we've considered so far.
John McCall432887f2009-09-30 01:30:54 +00005098 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005099 SmallVector<SourceLocation, 8> Locations;
John McCall432887f2009-09-30 01:30:54 +00005100 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005101
Douglas Gregor2dd078a2009-09-02 22:59:36 +00005102 while (BaseType->isRecordType()) {
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +00005103 Result = BuildOverloadedArrowExpr(
5104 S, Base, OpLoc,
5105 // When in a template specialization and on the first loop iteration,
5106 // potentially give the default diagnostic (with the fixit in a
5107 // separate note) instead of having the error reported back to here
5108 // and giving a diagnostic with a fixit attached to the error itself.
5109 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
5110 ? 0
5111 : &NoArrowOperatorFound);
5112 if (Result.isInvalid()) {
5113 if (NoArrowOperatorFound) {
5114 if (FirstIteration) {
5115 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5116 << BaseType << 1 << Base->getSourceRange()
5117 << FixItHint::CreateReplacement(OpLoc, ".");
5118 OpKind = tok::period;
5119 break;
Kaelyn Uhrainc14e6dd2013-07-31 20:16:17 +00005120 }
5121 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5122 << BaseType << Base->getSourceRange();
5123 CallExpr *CE = dyn_cast<CallExpr>(Base);
5124 if (Decl *CD = (CE ? CE->getCalleeDecl() : 0)) {
5125 Diag(CD->getLocStart(),
5126 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +00005127 }
5128 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +00005129 return ExprError();
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +00005130 }
John McCall9ae2f072010-08-23 23:25:46 +00005131 Base = Result.get();
5132 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonde699e52009-10-13 22:55:59 +00005133 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCall9ae2f072010-08-23 23:25:46 +00005134 BaseType = Base->getType();
John McCallc4e83212009-09-30 01:01:30 +00005135 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCall432887f2009-09-30 01:30:54 +00005136 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00005137 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanian7a8233a2009-09-30 17:46:20 +00005138 for (unsigned i = 0; i < Locations.size(); i++)
5139 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian4a4e3452009-09-30 00:19:41 +00005140 return ExprError();
5141 }
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +00005142 FirstIteration = false;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00005143 }
Mike Stump1eb44332009-09-09 15:08:12 +00005144
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +00005145 if (OpKind == tok::arrow &&
5146 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregor31658df2009-11-20 19:58:21 +00005147 BaseType = BaseType->getPointeeType();
5148 }
Mike Stump1eb44332009-09-09 15:08:12 +00005149
Douglas Gregor1d7049a2012-01-12 16:11:24 +00005150 // Objective-C properties allow "." access on Objective-C pointer types,
5151 // so adjust the base type to the object type itself.
5152 if (BaseType->isObjCObjectPointerType())
5153 BaseType = BaseType->getPointeeType();
5154
5155 // C++ [basic.lookup.classref]p2:
5156 // [...] If the type of the object expression is of pointer to scalar
5157 // type, the unqualified-id is looked up in the context of the complete
5158 // postfix-expression.
5159 //
5160 // This also indicates that we could be parsing a pseudo-destructor-name.
5161 // Note that Objective-C class and object types can be pseudo-destructor
5162 // expressions or normal member (ivar or property) access expressions.
5163 if (BaseType->isObjCObjectOrInterfaceType()) {
5164 MayBePseudoDestructor = true;
5165 } else if (!BaseType->isRecordType()) {
John McCallb3d87482010-08-24 05:47:05 +00005166 ObjectType = ParsedType();
Douglas Gregord4dca082010-02-24 18:44:31 +00005167 MayBePseudoDestructor = true;
John McCall9ae2f072010-08-23 23:25:46 +00005168 return Owned(Base);
Douglas Gregorc68afe22009-09-03 21:38:09 +00005169 }
Mike Stump1eb44332009-09-09 15:08:12 +00005170
Douglas Gregorcefc3af2012-04-16 07:05:22 +00005171 // The object type must be complete (or dependent), or
5172 // C++11 [expr.prim.general]p3:
5173 // Unlike the object expression in other contexts, *this is not required to
5174 // be of complete type for purposes of class member access (5.2.5) outside
5175 // the member function body.
Douglas Gregor03c57052009-11-17 05:17:33 +00005176 if (!BaseType->isDependentType() &&
Douglas Gregorcefc3af2012-04-16 07:05:22 +00005177 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00005178 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor03c57052009-11-17 05:17:33 +00005179 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005180
Douglas Gregorc68afe22009-09-03 21:38:09 +00005181 // C++ [basic.lookup.classref]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005182 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor03c57052009-11-17 05:17:33 +00005183 // unqualified-id, and the type of the object expression is of a class
Douglas Gregorc68afe22009-09-03 21:38:09 +00005184 // type C (or of pointer to a class type C), the unqualified-id is looked
5185 // up in the scope of class C. [...]
John McCallb3d87482010-08-24 05:47:05 +00005186 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00005187 return Base;
Douglas Gregor2dd078a2009-09-02 22:59:36 +00005188}
5189
John McCall60d7b3a2010-08-24 06:29:42 +00005190ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCall9ae2f072010-08-23 23:25:46 +00005191 Expr *MemExpr) {
Douglas Gregor77549082010-02-24 21:29:12 +00005192 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCall9ae2f072010-08-23 23:25:46 +00005193 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
5194 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregor849b2432010-03-31 17:46:05 +00005195 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005196
Douglas Gregor77549082010-02-24 21:29:12 +00005197 return ActOnCallExpr(/*Scope*/ 0,
John McCall9ae2f072010-08-23 23:25:46 +00005198 MemExpr,
Douglas Gregor77549082010-02-24 21:29:12 +00005199 /*LPLoc*/ ExpectedLParenLoc,
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00005200 None,
Douglas Gregor77549082010-02-24 21:29:12 +00005201 /*RPLoc*/ ExpectedLParenLoc);
5202}
Douglas Gregord4dca082010-02-24 18:44:31 +00005203
Eli Friedmane0dbedf2012-01-25 04:29:24 +00005204static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie91ec7892011-12-16 16:03:09 +00005205 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedmane0dbedf2012-01-25 04:29:24 +00005206 if (Base->hasPlaceholderType()) {
5207 ExprResult result = S.CheckPlaceholderExpr(Base);
5208 if (result.isInvalid()) return true;
5209 Base = result.take();
5210 }
5211 ObjectType = Base->getType();
5212
David Blaikie91ec7892011-12-16 16:03:09 +00005213 // C++ [expr.pseudo]p2:
5214 // The left-hand side of the dot operator shall be of scalar type. The
5215 // left-hand side of the arrow operator shall be of pointer to scalar type.
5216 // This scalar type is the object type.
Eli Friedmane0dbedf2012-01-25 04:29:24 +00005217 // Note that this is rather different from the normal handling for the
5218 // arrow operator.
David Blaikie91ec7892011-12-16 16:03:09 +00005219 if (OpKind == tok::arrow) {
5220 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
5221 ObjectType = Ptr->getPointeeType();
5222 } else if (!Base->isTypeDependent()) {
5223 // The user wrote "p->" when she probably meant "p."; fix it.
5224 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5225 << ObjectType << true
5226 << FixItHint::CreateReplacement(OpLoc, ".");
5227 if (S.isSFINAEContext())
5228 return true;
5229
5230 OpKind = tok::period;
5231 }
5232 }
5233
5234 return false;
5235}
5236
John McCall60d7b3a2010-08-24 06:29:42 +00005237ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00005238 SourceLocation OpLoc,
5239 tok::TokenKind OpKind,
5240 const CXXScopeSpec &SS,
5241 TypeSourceInfo *ScopeTypeInfo,
5242 SourceLocation CCLoc,
5243 SourceLocation TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005244 PseudoDestructorTypeStorage Destructed,
John McCall2d9f5fa2011-02-25 05:21:17 +00005245 bool HasTrailingLParen) {
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005246 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005247
Eli Friedman8c9fe202012-01-25 04:35:06 +00005248 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00005249 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5250 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005251
Douglas Gregor0cb89392012-09-10 14:57:06 +00005252 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
5253 !ObjectType->isVectorType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005254 if (getLangOpts().MicrosoftMode && ObjectType->isVoidType())
Nico Weber2d757ec2012-01-23 06:08:16 +00005255 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Nico Weberdf1be862012-01-23 05:50:57 +00005256 else
5257 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
5258 << ObjectType << Base->getSourceRange();
Douglas Gregorb57fb492010-02-24 22:38:50 +00005259 return ExprError();
5260 }
5261
5262 // C++ [expr.pseudo]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005263 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb57fb492010-02-24 22:38:50 +00005264 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005265 if (DestructedTypeInfo) {
5266 QualType DestructedType = DestructedTypeInfo->getType();
5267 SourceLocation DestructedTypeStart
Abramo Bagnarabd054db2010-05-20 10:00:11 +00005268 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCallf85e1932011-06-15 23:02:42 +00005269 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
5270 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
5271 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
5272 << ObjectType << DestructedType << Base->getSourceRange()
5273 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005274
John McCallf85e1932011-06-15 23:02:42 +00005275 // Recover by setting the destructed type to the object type.
5276 DestructedType = ObjectType;
5277 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005278 DestructedTypeStart);
John McCallf85e1932011-06-15 23:02:42 +00005279 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5280 } else if (DestructedType.getObjCLifetime() !=
5281 ObjectType.getObjCLifetime()) {
5282
5283 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
5284 // Okay: just pretend that the user provided the correctly-qualified
5285 // type.
5286 } else {
5287 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
5288 << ObjectType << DestructedType << Base->getSourceRange()
5289 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5290 }
5291
5292 // Recover by setting the destructed type to the object type.
5293 DestructedType = ObjectType;
5294 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5295 DestructedTypeStart);
5296 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5297 }
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005298 }
Douglas Gregorb57fb492010-02-24 22:38:50 +00005299 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005300
Douglas Gregorb57fb492010-02-24 22:38:50 +00005301 // C++ [expr.pseudo]p2:
5302 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
5303 // form
5304 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005305 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb57fb492010-02-24 22:38:50 +00005306 //
5307 // shall designate the same scalar type.
5308 if (ScopeTypeInfo) {
5309 QualType ScopeType = ScopeTypeInfo->getType();
5310 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCall81e317a2010-06-11 17:36:40 +00005311 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005312
Abramo Bagnarabd054db2010-05-20 10:00:11 +00005313 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00005314 diag::err_pseudo_dtor_type_mismatch)
John McCall9ae2f072010-08-23 23:25:46 +00005315 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00005316 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005317
Douglas Gregorb57fb492010-02-24 22:38:50 +00005318 ScopeType = QualType();
5319 ScopeTypeInfo = 0;
5320 }
5321 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005322
John McCall9ae2f072010-08-23 23:25:46 +00005323 Expr *Result
5324 = new (Context) CXXPseudoDestructorExpr(Context, Base,
5325 OpKind == tok::arrow, OpLoc,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00005326 SS.getWithLocInContext(Context),
John McCall9ae2f072010-08-23 23:25:46 +00005327 ScopeTypeInfo,
5328 CCLoc,
5329 TildeLoc,
5330 Destructed);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005331
Douglas Gregorb57fb492010-02-24 22:38:50 +00005332 if (HasTrailingLParen)
John McCall9ae2f072010-08-23 23:25:46 +00005333 return Owned(Result);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005334
John McCall9ae2f072010-08-23 23:25:46 +00005335 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor77549082010-02-24 21:29:12 +00005336}
5337
John McCall60d7b3a2010-08-24 06:29:42 +00005338ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCall2d9f5fa2011-02-25 05:21:17 +00005339 SourceLocation OpLoc,
5340 tok::TokenKind OpKind,
5341 CXXScopeSpec &SS,
5342 UnqualifiedId &FirstTypeName,
5343 SourceLocation CCLoc,
5344 SourceLocation TildeLoc,
5345 UnqualifiedId &SecondTypeName,
5346 bool HasTrailingLParen) {
Douglas Gregor77549082010-02-24 21:29:12 +00005347 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5348 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5349 "Invalid first type name in pseudo-destructor");
5350 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5351 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5352 "Invalid second type name in pseudo-destructor");
5353
Eli Friedman8c9fe202012-01-25 04:35:06 +00005354 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00005355 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5356 return ExprError();
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005357
5358 // Compute the object type that we should use for name lookup purposes. Only
5359 // record types and dependent types matter.
John McCallb3d87482010-08-24 05:47:05 +00005360 ParsedType ObjectTypePtrForLookup;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005361 if (!SS.isSet()) {
John McCall2d9f5fa2011-02-25 05:21:17 +00005362 if (ObjectType->isRecordType())
5363 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallb3d87482010-08-24 05:47:05 +00005364 else if (ObjectType->isDependentType())
5365 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005366 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005367
5368 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb57fb492010-02-24 22:38:50 +00005369 // type (with source-location information).
Douglas Gregor77549082010-02-24 21:29:12 +00005370 QualType DestructedType;
5371 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005372 PseudoDestructorTypeStorage Destructed;
Douglas Gregor77549082010-02-24 21:29:12 +00005373 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005374 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00005375 SecondTypeName.StartLocation,
Fariborz Jahanian1e52dfc2011-02-08 18:05:59 +00005376 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005377 if (!T &&
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005378 ((SS.isSet() && !computeDeclContext(SS, false)) ||
5379 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005380 // The name of the type being destroyed is a dependent name, and we
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005381 // couldn't find anything useful in scope. Just store the identifier and
5382 // it's location, and we'll perform (qualified) name lookup again at
5383 // template instantiation time.
5384 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5385 SecondTypeName.StartLocation);
5386 } else if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005387 Diag(SecondTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00005388 diag::err_pseudo_dtor_destructor_non_type)
5389 << SecondTypeName.Identifier << ObjectType;
5390 if (isSFINAEContext())
5391 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005392
Douglas Gregor77549082010-02-24 21:29:12 +00005393 // Recover by assuming we had the right type all along.
5394 DestructedType = ObjectType;
Douglas Gregorb57fb492010-02-24 22:38:50 +00005395 } else
Douglas Gregor77549082010-02-24 21:29:12 +00005396 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005397 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00005398 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00005399 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramer5354e772012-08-23 23:38:35 +00005400 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00005401 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00005402 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005403 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00005404 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00005405 TemplateId->TemplateNameLoc,
5406 TemplateId->LAngleLoc,
5407 TemplateArgsPtr,
5408 TemplateId->RAngleLoc);
5409 if (T.isInvalid() || !T.get()) {
5410 // Recover by assuming we had the right type all along.
5411 DestructedType = ObjectType;
5412 } else
5413 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005414 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005415
5416 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb57fb492010-02-24 22:38:50 +00005417 // information.
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005418 if (!DestructedType.isNull()) {
5419 if (!DestructedTypeInfo)
5420 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb57fb492010-02-24 22:38:50 +00005421 SecondTypeName.StartLocation);
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005422 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5423 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005424
Douglas Gregorb57fb492010-02-24 22:38:50 +00005425 // Convert the name of the scope type (the type prior to '::') into a type.
5426 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor77549082010-02-24 21:29:12 +00005427 QualType ScopeType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005428 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor77549082010-02-24 21:29:12 +00005429 FirstTypeName.Identifier) {
5430 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005431 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallb3d87482010-08-24 05:47:05 +00005432 FirstTypeName.StartLocation,
Douglas Gregorf3db29f2011-02-25 18:19:59 +00005433 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor77549082010-02-24 21:29:12 +00005434 if (!T) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005435 Diag(FirstTypeName.StartLocation,
Douglas Gregor77549082010-02-24 21:29:12 +00005436 diag::err_pseudo_dtor_destructor_non_type)
5437 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005438
Douglas Gregorb57fb492010-02-24 22:38:50 +00005439 if (isSFINAEContext())
5440 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005441
Douglas Gregorb57fb492010-02-24 22:38:50 +00005442 // Just drop this type. It's unnecessary anyway.
5443 ScopeType = QualType();
5444 } else
5445 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005446 } else {
Douglas Gregorb57fb492010-02-24 22:38:50 +00005447 // Resolve the template-id to a type.
Douglas Gregor77549082010-02-24 21:29:12 +00005448 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramer5354e772012-08-23 23:38:35 +00005449 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb57fb492010-02-24 22:38:50 +00005450 TemplateId->NumArgs);
Douglas Gregor059101f2011-03-02 00:47:37 +00005451 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara55d23c92012-02-06 14:41:24 +00005452 TemplateId->TemplateKWLoc,
Douglas Gregor059101f2011-03-02 00:47:37 +00005453 TemplateId->Template,
Douglas Gregorb57fb492010-02-24 22:38:50 +00005454 TemplateId->TemplateNameLoc,
5455 TemplateId->LAngleLoc,
5456 TemplateArgsPtr,
5457 TemplateId->RAngleLoc);
5458 if (T.isInvalid() || !T.get()) {
5459 // Recover by dropping this type.
5460 ScopeType = QualType();
5461 } else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005462 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor77549082010-02-24 21:29:12 +00005463 }
5464 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005465
Douglas Gregorb4a418f2010-02-24 23:02:30 +00005466 if (!ScopeType.isNull() && !ScopeTypeInfo)
5467 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5468 FirstTypeName.StartLocation);
5469
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005470
John McCall9ae2f072010-08-23 23:25:46 +00005471 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorfce46ee2010-02-24 23:50:37 +00005472 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregora2e7dd22010-02-25 01:56:36 +00005473 Destructed, HasTrailingLParen);
Douglas Gregord4dca082010-02-24 18:44:31 +00005474}
5475
David Blaikie91ec7892011-12-16 16:03:09 +00005476ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5477 SourceLocation OpLoc,
5478 tok::TokenKind OpKind,
5479 SourceLocation TildeLoc,
5480 const DeclSpec& DS,
5481 bool HasTrailingLParen) {
Eli Friedman8c9fe202012-01-25 04:35:06 +00005482 QualType ObjectType;
David Blaikie91ec7892011-12-16 16:03:09 +00005483 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5484 return ExprError();
5485
5486 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5487
5488 TypeLocBuilder TLB;
5489 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5490 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5491 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5492 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5493
5494 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5495 0, SourceLocation(), TildeLoc,
5496 Destructed, HasTrailingLParen);
5497}
5498
John Wiegley429bb272011-04-08 18:41:53 +00005499ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman3f01c8a2012-03-01 01:30:04 +00005500 CXXConversionDecl *Method,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005501 bool HadMultipleCandidates) {
Eli Friedman23f02672012-03-01 04:01:32 +00005502 if (Method->getParent()->isLambda() &&
5503 Method->getConversionType()->isBlockPointerType()) {
5504 // This is a lambda coversion to block pointer; check if the argument
5505 // is a LambdaExpr.
5506 Expr *SubE = E;
5507 CastExpr *CE = dyn_cast<CastExpr>(SubE);
5508 if (CE && CE->getCastKind() == CK_NoOp)
5509 SubE = CE->getSubExpr();
5510 SubE = SubE->IgnoreParens();
5511 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5512 SubE = BE->getSubExpr();
5513 if (isa<LambdaExpr>(SubE)) {
5514 // For the conversion to block pointer on a lambda expression, we
5515 // construct a special BlockLiteral instead; this doesn't really make
5516 // a difference in ARC, but outside of ARC the resulting block literal
5517 // follows the normal lifetime rules for block literals instead of being
5518 // autoreleased.
5519 DiagnosticErrorTrap Trap(Diags);
5520 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5521 E->getExprLoc(),
5522 Method, E);
5523 if (Exp.isInvalid())
5524 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5525 return Exp;
5526 }
5527 }
5528
5529
John Wiegley429bb272011-04-08 18:41:53 +00005530 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
5531 FoundDecl, Method);
5532 if (Exp.isInvalid())
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005533 return true;
Eli Friedman772fffa2009-12-09 04:53:56 +00005534
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005535 MemberExpr *ME =
John Wiegley429bb272011-04-08 18:41:53 +00005536 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnara960809e2011-11-16 22:46:05 +00005537 SourceLocation(), Context.BoundMemberTy,
John McCallf89e55a2010-11-18 06:31:45 +00005538 VK_RValue, OK_Ordinary);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005539 if (HadMultipleCandidates)
5540 ME->setHadMultipleCandidates(true);
Nick Lewycky3c86a5c2013-02-12 08:08:54 +00005541 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005542
John McCallf89e55a2010-11-18 06:31:45 +00005543 QualType ResultType = Method->getResultType();
5544 ExprValueKind VK = Expr::getValueKindForType(ResultType);
5545 ResultType = ResultType.getNonLValueExprType(Context);
5546
Douglas Gregor7edfb692009-11-23 12:27:39 +00005547 CXXMemberCallExpr *CE =
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00005548 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley429bb272011-04-08 18:41:53 +00005549 Exp.get()->getLocEnd());
Fariborz Jahanianb7400232009-09-28 23:23:40 +00005550 return CE;
5551}
5552
Sebastian Redl2e156222010-09-10 20:55:43 +00005553ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5554 SourceLocation RParen) {
Richard Smithe6975e92012-04-17 00:58:00 +00005555 CanThrowResult CanThrow = canThrow(Operand);
Sebastian Redl2e156222010-09-10 20:55:43 +00005556 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
Richard Smithe6975e92012-04-17 00:58:00 +00005557 CanThrow, KeyLoc, RParen));
Sebastian Redl2e156222010-09-10 20:55:43 +00005558}
5559
5560ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5561 Expr *Operand, SourceLocation RParen) {
5562 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl02bc21a2010-09-10 20:55:37 +00005563}
5564
Eli Friedmane26073c2012-05-24 22:04:19 +00005565static bool IsSpecialDiscardedValue(Expr *E) {
5566 // In C++11, discarded-value expressions of a certain form are special,
5567 // according to [expr]p10:
5568 // The lvalue-to-rvalue conversion (4.1) is applied only if the
5569 // expression is an lvalue of volatile-qualified type and it has
5570 // one of the following forms:
5571 E = E->IgnoreParens();
5572
Eli Friedman02180682012-05-24 22:36:31 +00005573 // - id-expression (5.1.1),
Eli Friedmane26073c2012-05-24 22:04:19 +00005574 if (isa<DeclRefExpr>(E))
5575 return true;
5576
Eli Friedman02180682012-05-24 22:36:31 +00005577 // - subscripting (5.2.1),
Eli Friedmane26073c2012-05-24 22:04:19 +00005578 if (isa<ArraySubscriptExpr>(E))
5579 return true;
5580
Eli Friedman02180682012-05-24 22:36:31 +00005581 // - class member access (5.2.5),
Eli Friedmane26073c2012-05-24 22:04:19 +00005582 if (isa<MemberExpr>(E))
5583 return true;
5584
Eli Friedman02180682012-05-24 22:36:31 +00005585 // - indirection (5.3.1),
Eli Friedmane26073c2012-05-24 22:04:19 +00005586 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
5587 if (UO->getOpcode() == UO_Deref)
5588 return true;
5589
5590 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedman02180682012-05-24 22:36:31 +00005591 // - pointer-to-member operation (5.5),
Eli Friedmane26073c2012-05-24 22:04:19 +00005592 if (BO->isPtrMemOp())
5593 return true;
5594
Eli Friedman02180682012-05-24 22:36:31 +00005595 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmane26073c2012-05-24 22:04:19 +00005596 if (BO->getOpcode() == BO_Comma)
5597 return IsSpecialDiscardedValue(BO->getRHS());
5598 }
5599
Eli Friedman02180682012-05-24 22:36:31 +00005600 // - conditional expression (5.16) where both the second and the third
Eli Friedmane26073c2012-05-24 22:04:19 +00005601 // operands are one of the above, or
5602 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
5603 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
5604 IsSpecialDiscardedValue(CO->getFalseExpr());
5605 // The related edge case of "*x ?: *x".
5606 if (BinaryConditionalOperator *BCO =
5607 dyn_cast<BinaryConditionalOperator>(E)) {
5608 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
5609 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
5610 IsSpecialDiscardedValue(BCO->getFalseExpr());
5611 }
5612
5613 // Objective-C++ extensions to the rule.
5614 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
5615 return true;
5616
5617 return false;
5618}
5619
John McCallf6a16482010-12-04 03:47:34 +00005620/// Perform the conversions required for an expression used in a
5621/// context that ignores the result.
John Wiegley429bb272011-04-08 18:41:53 +00005622ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall3c3b7f92011-10-25 17:37:35 +00005623 if (E->hasPlaceholderType()) {
5624 ExprResult result = CheckPlaceholderExpr(E);
5625 if (result.isInvalid()) return Owned(E);
5626 E = result.take();
5627 }
5628
John McCalla878cda2010-12-02 02:07:15 +00005629 // C99 6.3.2.1:
5630 // [Except in specific positions,] an lvalue that does not have
5631 // array type is converted to the value stored in the
5632 // designated object (and is no longer an lvalue).
John McCalle6d134b2011-06-27 21:24:11 +00005633 if (E->isRValue()) {
5634 // In C, function designators (i.e. expressions of function type)
5635 // are r-values, but we still want to do function-to-pointer decay
5636 // on them. This is both technically correct and convenient for
5637 // some clients.
David Blaikie4e4d0842012-03-11 07:00:24 +00005638 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalle6d134b2011-06-27 21:24:11 +00005639 return DefaultFunctionArrayConversion(E);
5640
5641 return Owned(E);
5642 }
John McCalla878cda2010-12-02 02:07:15 +00005643
Eli Friedmane26073c2012-05-24 22:04:19 +00005644 if (getLangOpts().CPlusPlus) {
5645 // The C++11 standard defines the notion of a discarded-value expression;
5646 // normally, we don't need to do anything to handle it, but if it is a
5647 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
5648 // conversion.
Richard Smith80ad52f2013-01-02 11:42:31 +00005649 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmane26073c2012-05-24 22:04:19 +00005650 E->getType().isVolatileQualified() &&
5651 IsSpecialDiscardedValue(E)) {
5652 ExprResult Res = DefaultLvalueConversion(E);
5653 if (Res.isInvalid())
5654 return Owned(E);
5655 E = Res.take();
5656 }
5657 return Owned(E);
5658 }
John McCallf6a16482010-12-04 03:47:34 +00005659
5660 // GCC seems to also exclude expressions of incomplete enum type.
5661 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5662 if (!T->getDecl()->isComplete()) {
5663 // FIXME: stupid workaround for a codegen bug!
John Wiegley429bb272011-04-08 18:41:53 +00005664 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
5665 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00005666 }
5667 }
5668
John Wiegley429bb272011-04-08 18:41:53 +00005669 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5670 if (Res.isInvalid())
5671 return Owned(E);
5672 E = Res.take();
5673
John McCall85515d62010-12-04 12:29:11 +00005674 if (!E->getType()->isVoidType())
5675 RequireCompleteType(E->getExprLoc(), E->getType(),
5676 diag::err_incomplete_type);
John Wiegley429bb272011-04-08 18:41:53 +00005677 return Owned(E);
John McCallf6a16482010-12-04 03:47:34 +00005678}
5679
Richard Smith41956372013-01-14 22:39:08 +00005680ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005681 bool DiscardedValue,
5682 bool IsConstexpr) {
John Wiegley429bb272011-04-08 18:41:53 +00005683 ExprResult FullExpr = Owned(FE);
5684
5685 if (!FullExpr.get())
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00005686 return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00005687
John Wiegley429bb272011-04-08 18:41:53 +00005688 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregord0937222010-12-13 22:49:22 +00005689 return ExprError();
5690
Douglas Gregor1344e942013-03-07 22:57:58 +00005691 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith41956372013-01-14 22:39:08 +00005692 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregor1344e942013-03-07 22:57:58 +00005693 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Douglas Gregor5e3a8be2011-12-15 00:53:32 +00005694 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
5695 if (FullExpr.isInvalid())
5696 return ExprError();
5697 }
Douglas Gregor353ee242011-03-07 02:05:23 +00005698
Richard Smith41956372013-01-14 22:39:08 +00005699 if (DiscardedValue) {
5700 FullExpr = CheckPlaceholderExpr(FullExpr.take());
5701 if (FullExpr.isInvalid())
5702 return ExprError();
5703
5704 FullExpr = IgnoredValueConversions(FullExpr.take());
5705 if (FullExpr.isInvalid())
5706 return ExprError();
5707 }
John Wiegley429bb272011-04-08 18:41:53 +00005708
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005709 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
John McCall4765fa02010-12-06 08:20:24 +00005710 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson165a0a02009-05-17 18:41:29 +00005711}
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00005712
5713StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
5714 if (!FullStmt) return StmtError();
5715
John McCall4765fa02010-12-06 08:20:24 +00005716 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidisbf8cafa2010-11-02 02:33:08 +00005717}
Francois Pichet1e862692011-05-06 20:48:22 +00005718
Douglas Gregorba0513d2011-10-25 01:33:02 +00005719Sema::IfExistsResult
5720Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
5721 CXXScopeSpec &SS,
5722 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet1e862692011-05-06 20:48:22 +00005723 DeclarationName TargetName = TargetNameInfo.getName();
5724 if (!TargetName)
Douglas Gregor3896fc52011-10-24 22:31:10 +00005725 return IER_DoesNotExist;
Douglas Gregorba0513d2011-10-25 01:33:02 +00005726
Douglas Gregor3896fc52011-10-24 22:31:10 +00005727 // If the name itself is dependent, then the result is dependent.
5728 if (TargetName.isDependentName())
5729 return IER_Dependent;
Douglas Gregorba0513d2011-10-25 01:33:02 +00005730
Francois Pichet1e862692011-05-06 20:48:22 +00005731 // Do the redeclaration lookup in the current scope.
5732 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
5733 Sema::NotForRedeclaration);
Douglas Gregor3896fc52011-10-24 22:31:10 +00005734 LookupParsedName(R, S, &SS);
Francois Pichet1e862692011-05-06 20:48:22 +00005735 R.suppressDiagnostics();
Douglas Gregor3896fc52011-10-24 22:31:10 +00005736
5737 switch (R.getResultKind()) {
5738 case LookupResult::Found:
5739 case LookupResult::FoundOverloaded:
5740 case LookupResult::FoundUnresolvedValue:
5741 case LookupResult::Ambiguous:
5742 return IER_Exists;
5743
5744 case LookupResult::NotFound:
5745 return IER_DoesNotExist;
5746
5747 case LookupResult::NotFoundInCurrentInstantiation:
5748 return IER_Dependent;
5749 }
David Blaikie7530c032012-01-17 06:56:22 +00005750
5751 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet1e862692011-05-06 20:48:22 +00005752}
Douglas Gregorba0513d2011-10-25 01:33:02 +00005753
Douglas Gregor65019ac2011-10-25 03:44:56 +00005754Sema::IfExistsResult
5755Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5756 bool IsIfExists, CXXScopeSpec &SS,
5757 UnqualifiedId &Name) {
Douglas Gregorba0513d2011-10-25 01:33:02 +00005758 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor65019ac2011-10-25 03:44:56 +00005759
5760 // Check for unexpanded parameter packs.
5761 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5762 collectUnexpandedParameterPacks(SS, Unexpanded);
5763 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
5764 if (!Unexpanded.empty()) {
5765 DiagnoseUnexpandedParameterPacks(KeywordLoc,
5766 IsIfExists? UPPC_IfExists
5767 : UPPC_IfNotExists,
5768 Unexpanded);
5769 return IER_Error;
5770 }
5771
Douglas Gregorba0513d2011-10-25 01:33:02 +00005772 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
5773}