blob: 59a167a62c58fcee9a3fca8520902e0367f68605 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
James Dennett84053fb2012-06-22 05:14:59 +00009///
10/// \file
11/// \brief Implements semantic analysis for C++ expressions.
12///
13//===----------------------------------------------------------------------===//
Chris Lattner29375652006-12-04 18:06:35 +000014
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "TypeLocBuilder.h"
Steve Naroffaac94152007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
John McCallde6836a2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Richard Smithc406cb72013-01-17 01:17:56 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000023#include "clang/AST/ExprObjC.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000025#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000026#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000027#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/ParsedTemplate.h"
33#include "clang/Sema/Scope.h"
34#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000035#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000037#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000039#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000040using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000041using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000042
Richard Smith7447af42013-03-26 01:15:19 +000043/// \brief Handle the result of the special case name lookup for inheriting
44/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
45/// constructor names in member using declarations, even if 'X' is not the
46/// name of the corresponding type.
47ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
48 SourceLocation NameLoc,
49 IdentifierInfo &Name) {
50 NestedNameSpecifier *NNS = SS.getScopeRep();
51
52 // Convert the nested-name-specifier into a type.
53 QualType Type;
54 switch (NNS->getKind()) {
55 case NestedNameSpecifier::TypeSpec:
56 case NestedNameSpecifier::TypeSpecWithTemplate:
57 Type = QualType(NNS->getAsType(), 0);
58 break;
59
60 case NestedNameSpecifier::Identifier:
61 // Strip off the last layer of the nested-name-specifier and build a
62 // typename type for it.
63 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
64 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
65 NNS->getAsIdentifier());
66 break;
67
68 case NestedNameSpecifier::Global:
69 case NestedNameSpecifier::Namespace:
70 case NestedNameSpecifier::NamespaceAlias:
71 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
72 }
73
74 // This reference to the type is located entirely at the location of the
75 // final identifier in the qualified-id.
76 return CreateParsedType(Type,
77 Context.getTrivialTypeSourceInfo(Type, NameLoc));
78}
79
John McCallba7bf592010-08-24 05:47:05 +000080ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000081 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000082 SourceLocation NameLoc,
83 Scope *S, CXXScopeSpec &SS,
84 ParsedType ObjectTypePtr,
85 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000086 // Determine where to perform name lookup.
87
88 // FIXME: This area of the standard is very messy, and the current
89 // wording is rather unclear about which scopes we search for the
90 // destructor name; see core issues 399 and 555. Issue 399 in
91 // particular shows where the current description of destructor name
92 // lookup is completely out of line with existing practice, e.g.,
93 // this appears to be ill-formed:
94 //
95 // namespace N {
96 // template <typename T> struct S {
97 // ~S();
98 // };
99 // }
100 //
101 // void f(N::S<int>* s) {
102 // s->N::S<int>::~S();
103 // }
104 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000105 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000106 // For this reason, we're currently only doing the C++03 version of this
107 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000108 QualType SearchType;
109 DeclContext *LookupCtx = 0;
110 bool isDependent = false;
111 bool LookInScope = false;
112
113 // If we have an object type, it's because we are in a
114 // pseudo-destructor-expression or a member access expression, and
115 // we know what type we're looking for.
116 if (ObjectTypePtr)
117 SearchType = GetTypeFromParser(ObjectTypePtr);
118
119 if (SS.isSet()) {
Douglas Gregor46841e12010-02-23 00:15:22 +0000120 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000121
Douglas Gregor46841e12010-02-23 00:15:22 +0000122 bool AlreadySearched = false;
123 bool LookAtPrefix = true;
Sebastian Redla771d222010-07-07 23:17:38 +0000124 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000125 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000126 // the type-names are looked up as types in the scope designated by the
127 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000128 //
129 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000130 //
131 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth8f254812010-02-21 10:19:54 +0000132 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +0000133 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000134 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregorfe17d252010-02-16 19:09:40 +0000135 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000136 // the class-names are looked up as types in the scope designated by
Sebastian Redla771d222010-07-07 23:17:38 +0000137 // the nested-name-specifier.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000138 //
Sebastian Redla771d222010-07-07 23:17:38 +0000139 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000140 // code below is permitted to look at the prefix of the
Sebastian Redla771d222010-07-07 23:17:38 +0000141 // nested-name-specifier.
142 DeclContext *DC = computeDeclContext(SS, EnteringContext);
143 if (DC && DC->isFileContext()) {
144 AlreadySearched = true;
145 LookupCtx = DC;
146 isDependent = false;
147 } else if (DC && isa<CXXRecordDecl>(DC))
148 LookAtPrefix = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000149
Sebastian Redla771d222010-07-07 23:17:38 +0000150 // The second case from the C++03 rules quoted further above.
Douglas Gregor46841e12010-02-23 00:15:22 +0000151 NestedNameSpecifier *Prefix = 0;
152 if (AlreadySearched) {
153 // Nothing left to do.
154 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
155 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000156 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000157 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
158 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000159 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000160 LookupCtx = computeDeclContext(SearchType);
161 isDependent = SearchType->isDependentType();
162 } else {
163 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000164 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000165 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000166
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000167 LookInScope = false;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000168 } else if (ObjectTypePtr) {
169 // C++ [basic.lookup.classref]p3:
170 // If the unqualified-id is ~type-name, the type-name is looked up
171 // in the context of the entire postfix-expression. If the type T
172 // of the object expression is of a class type C, the type-name is
173 // also looked up in the scope of class C. At least one of the
174 // lookups shall find a name that refers to (possibly
175 // cv-qualified) T.
176 LookupCtx = computeDeclContext(SearchType);
177 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000178 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000179 "Caller should have completed object type");
180
181 LookInScope = true;
182 } else {
183 // Perform lookup into the current scope (only).
184 LookInScope = true;
185 }
186
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000187 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000188 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
189 for (unsigned Step = 0; Step != 2; ++Step) {
190 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000191 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000192 // we're allowed to look there).
193 Found.clear();
194 if (Step == 0 && LookupCtx)
195 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000196 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000197 LookupName(Found, S);
198 else
199 continue;
200
201 // FIXME: Should we be suppressing ambiguities here?
202 if (Found.isAmbiguous())
John McCallba7bf592010-08-24 05:47:05 +0000203 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000204
205 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
206 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000207
208 if (SearchType.isNull() || SearchType->isDependentType() ||
209 Context.hasSameUnqualifiedType(T, SearchType)) {
210 // We found our type!
211
John McCallba7bf592010-08-24 05:47:05 +0000212 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000213 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000214
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000215 if (!SearchType.isNull())
216 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000217 }
218
219 // If the name that we found is a class template name, and it is
220 // the same name as the template name in the last part of the
221 // nested-name-specifier (if present) or the object type, then
222 // this is the destructor for that class.
223 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000225 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
226 QualType MemberOfType;
227 if (SS.isSet()) {
228 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
229 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000230 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
231 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000232 }
233 }
234 if (MemberOfType.isNull())
235 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000236
Douglas Gregorfe17d252010-02-16 19:09:40 +0000237 if (MemberOfType.isNull())
238 continue;
239
240 // We're referring into a class template specialization. If the
241 // class template we found is the same as the template being
242 // specialized, we found what we are looking for.
243 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
244 if (ClassTemplateSpecializationDecl *Spec
245 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
246 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
247 Template->getCanonicalDecl())
John McCallba7bf592010-08-24 05:47:05 +0000248 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000249 }
250
251 continue;
252 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000253
Douglas Gregorfe17d252010-02-16 19:09:40 +0000254 // We're referring to an unresolved class template
255 // specialization. Determine whether we class template we found
256 // is the same as the template being specialized or, if we don't
257 // know which template is being specialized, that it at least
258 // has the same name.
259 if (const TemplateSpecializationType *SpecType
260 = MemberOfType->getAs<TemplateSpecializationType>()) {
261 TemplateName SpecName = SpecType->getTemplateName();
262
263 // The class template we found is the same template being
264 // specialized.
265 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
266 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallba7bf592010-08-24 05:47:05 +0000267 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000268
269 continue;
270 }
271
272 // The class template we found has the same name as the
273 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000274 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000275 = SpecName.getAsDependentTemplateName()) {
276 if (DepTemplate->isIdentifier() &&
277 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallba7bf592010-08-24 05:47:05 +0000278 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000279
280 continue;
281 }
282 }
283 }
284 }
285
286 if (isDependent) {
287 // We didn't find our type, but that's okay: it's dependent
288 // anyway.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000289
290 // FIXME: What if we have no nested-name-specifier?
291 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
292 SS.getWithLocInContext(Context),
293 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000294 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000295 }
296
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000297 if (NonMatchingTypeDecl) {
298 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
299 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
300 << T << SearchType;
301 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
302 << T;
303 } else if (ObjectTypePtr)
304 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000305 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000306 else {
307 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
308 diag::err_destructor_class_name);
309 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000310 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000311 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
312 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
313 Class->getNameAsString());
314 }
315 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000316
John McCallba7bf592010-08-24 05:47:05 +0000317 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000318}
319
David Blaikieecd8a942011-12-08 16:13:53 +0000320ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie08608f62011-12-12 04:13:55 +0000321 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikieecd8a942011-12-08 16:13:53 +0000322 return ParsedType();
323 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
324 && "only get destructor types from declspecs");
325 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
326 QualType SearchType = GetTypeFromParser(ObjectType);
327 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
328 return ParsedType::make(T);
329 }
330
331 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
332 << T << SearchType;
333 return ParsedType();
334}
335
Douglas Gregor9da64192010-04-26 22:37:10 +0000336/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000337ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000338 SourceLocation TypeidLoc,
339 TypeSourceInfo *Operand,
340 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000341 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000342 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000343 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000344 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000345 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000346 Qualifiers Quals;
347 QualType T
348 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
349 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000350 if (T->getAs<RecordType>() &&
351 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
352 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000353
Douglas Gregor9da64192010-04-26 22:37:10 +0000354 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
355 Operand,
356 SourceRange(TypeidLoc, RParenLoc)));
357}
358
359/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000360ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000361 SourceLocation TypeidLoc,
362 Expr *E,
363 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000364 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000365 if (E->getType()->isPlaceholderType()) {
366 ExprResult result = CheckPlaceholderExpr(E);
367 if (result.isInvalid()) return ExprError();
368 E = result.take();
369 }
370
Douglas Gregor9da64192010-04-26 22:37:10 +0000371 QualType T = E->getType();
372 if (const RecordType *RecordT = T->getAs<RecordType>()) {
373 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
374 // C++ [expr.typeid]p3:
375 // [...] If the type of the expression is a class type, the class
376 // shall be completely-defined.
377 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
378 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000379
Douglas Gregor9da64192010-04-26 22:37:10 +0000380 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000381 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000382 // polymorphic class type [...] [the] expression is an unevaluated
383 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000384 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000385 // The subexpression is potentially evaluated; switch the context
386 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000387 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000388 if (Result.isInvalid()) return ExprError();
389 E = Result.take();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000390
391 // We require a vtable to query the type at run time.
392 MarkVTableUsed(TypeidLoc, RecordD);
393 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000394 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000395
Douglas Gregor9da64192010-04-26 22:37:10 +0000396 // C++ [expr.typeid]p4:
397 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000398 // cv-qualified type, the result of the typeid expression refers to a
399 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000400 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000401 Qualifiers Quals;
402 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
403 if (!Context.hasSameType(T, UnqualT)) {
404 T = UnqualT;
Eli Friedmanbe4b3632011-09-27 21:58:52 +0000405 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor9da64192010-04-26 22:37:10 +0000406 }
407 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000408
Douglas Gregor9da64192010-04-26 22:37:10 +0000409 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCallb268a282010-08-23 23:25:46 +0000410 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000411 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor9da64192010-04-26 22:37:10 +0000412}
413
414/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000415ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000416Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
417 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000418 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000419 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000420 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000421
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000422 if (!CXXTypeInfoDecl) {
423 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
424 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
425 LookupQualifiedName(R, getStdNamespace());
426 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000427 // Microsoft's typeinfo doesn't have type_info in std but in the global
428 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
429 if (!CXXTypeInfoDecl && LangOpts.MicrosoftMode) {
430 LookupQualifiedName(R, Context.getTranslationUnitDecl());
431 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
432 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000433 if (!CXXTypeInfoDecl)
434 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
435 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000436
Nico Weber1b7f39d2012-05-20 01:27:21 +0000437 if (!getLangOpts().RTTI) {
438 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
439 }
440
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000441 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000442
Douglas Gregor9da64192010-04-26 22:37:10 +0000443 if (isType) {
444 // The operand is a type; handle it as such.
445 TypeSourceInfo *TInfo = 0;
John McCallba7bf592010-08-24 05:47:05 +0000446 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
447 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000448 if (T.isNull())
449 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000450
Douglas Gregor9da64192010-04-26 22:37:10 +0000451 if (!TInfo)
452 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000453
Douglas Gregor9da64192010-04-26 22:37:10 +0000454 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000455 }
Mike Stump11289f42009-09-09 15:08:12 +0000456
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000457 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000458 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000459}
460
Francois Pichet9f4f2072010-09-08 12:20:18 +0000461/// \brief Build a Microsoft __uuidof expression with a type operand.
462ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
463 SourceLocation TypeidLoc,
464 TypeSourceInfo *Operand,
465 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000466 if (!Operand->getType()->isDependentType()) {
David Majnemer59c0ec22013-09-07 06:59:46 +0000467 bool HasMultipleGUIDs = false;
468 if (!CXXUuidofExpr::GetUuidAttrOfType(Operand->getType(),
469 &HasMultipleGUIDs)) {
470 if (HasMultipleGUIDs)
471 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
472 else
473 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
474 }
Francois Pichetb7577652010-12-27 01:32:00 +0000475 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000476
Francois Pichet9f4f2072010-09-08 12:20:18 +0000477 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
478 Operand,
479 SourceRange(TypeidLoc, RParenLoc)));
480}
481
482/// \brief Build a Microsoft __uuidof expression with an expression operand.
483ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
484 SourceLocation TypeidLoc,
485 Expr *E,
486 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000487 if (!E->getType()->isDependentType()) {
David Majnemer59c0ec22013-09-07 06:59:46 +0000488 bool HasMultipleGUIDs = false;
489 if (!CXXUuidofExpr::GetUuidAttrOfType(E->getType(), &HasMultipleGUIDs) &&
490 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
491 if (HasMultipleGUIDs)
492 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
493 else
494 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
495 }
Francois Pichetb7577652010-12-27 01:32:00 +0000496 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000497
Francois Pichet9f4f2072010-09-08 12:20:18 +0000498 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
499 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000501}
502
503/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
504ExprResult
505Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
506 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000508 if (!MSVCGuidDecl) {
509 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
510 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
511 LookupQualifiedName(R, Context.getTranslationUnitDecl());
512 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
513 if (!MSVCGuidDecl)
514 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000515 }
516
Francois Pichet9f4f2072010-09-08 12:20:18 +0000517 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000518
Francois Pichet9f4f2072010-09-08 12:20:18 +0000519 if (isType) {
520 // The operand is a type; handle it as such.
521 TypeSourceInfo *TInfo = 0;
522 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
523 &TInfo);
524 if (T.isNull())
525 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000526
Francois Pichet9f4f2072010-09-08 12:20:18 +0000527 if (!TInfo)
528 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
529
530 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
531 }
532
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000534 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
535}
536
Steve Naroff66356bd2007-09-16 14:56:35 +0000537/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000538ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000539Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000540 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000541 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000542 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
543 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000544}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000545
Sebastian Redl576fd422009-05-10 18:38:11 +0000546/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000547ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000548Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
549 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
550}
551
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000552/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000553ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000554Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
555 bool IsThrownVarInScope = false;
556 if (Ex) {
557 // C++0x [class.copymove]p31:
558 // When certain criteria are met, an implementation is allowed to omit the
559 // copy/move construction of a class object [...]
560 //
561 // - in a throw-expression, when the operand is the name of a
562 // non-volatile automatic object (other than a function or catch-
563 // clause parameter) whose scope does not extend beyond the end of the
564 // innermost enclosing try-block (if there is one), the copy/move
565 // operation from the operand to the exception object (15.1) can be
566 // omitted by constructing the automatic object directly into the
567 // exception object
568 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
569 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
570 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
571 for( ; S; S = S->getParent()) {
572 if (S->isDeclScope(Var)) {
573 IsThrownVarInScope = true;
574 break;
575 }
576
577 if (S->getFlags() &
578 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
579 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
580 Scope::TryScope))
581 break;
582 }
583 }
584 }
585 }
586
587 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
588}
589
590ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
591 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000592 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000593 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000594 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000595 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000596
John Wiegley01296292011-04-08 18:41:53 +0000597 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000598 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley01296292011-04-08 18:41:53 +0000599 if (ExRes.isInvalid())
600 return ExprError();
601 Ex = ExRes.take();
602 }
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000603
604 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
605 IsThrownVarInScope));
Sebastian Redl4de47b42009-04-27 20:27:31 +0000606}
607
608/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000609ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
610 bool IsThrownVarInScope) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000611 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000612 // A throw-expression initializes a temporary object, called the exception
613 // object, the type of which is determined by removing any top-level
614 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000615 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor247894b2009-12-23 22:04:40 +0000616 // or "pointer to function returning T", [...]
617 if (E->getType().hasQualifiers())
John Wiegley01296292011-04-08 18:41:53 +0000618 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanbe4b3632011-09-27 21:58:52 +0000619 E->getValueKind()).take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000620
John Wiegley01296292011-04-08 18:41:53 +0000621 ExprResult Res = DefaultFunctionArrayConversion(E);
622 if (Res.isInvalid())
623 return ExprError();
624 E = Res.take();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000625
626 // If the type of the exception would be an incomplete type or a pointer
627 // to an incomplete type other than (cv) void the program is ill-formed.
628 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000629 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000630 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000631 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000632 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000633 }
634 if (!isPointer || !Ty->isVoidType()) {
635 if (RequireCompleteType(ThrowLoc, Ty,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000636 isPointer? diag::err_throw_incomplete_ptr
637 : diag::err_throw_incomplete,
638 E->getSourceRange()))
John Wiegley01296292011-04-08 18:41:53 +0000639 return ExprError();
Rafael Espindola70e040d2010-03-02 21:28:26 +0000640
Douglas Gregore8154332010-04-15 18:05:39 +0000641 if (RequireNonAbstractType(ThrowLoc, E->getType(),
Douglas Gregorae298422012-05-04 17:09:59 +0000642 diag::err_throw_abstract_type, E))
John Wiegley01296292011-04-08 18:41:53 +0000643 return ExprError();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000644 }
645
John McCall2e6567a2010-04-22 01:10:34 +0000646 // Initialize the exception result. This implicitly weeds out
647 // abstract types or types with inaccessible copy constructors.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000648
649 // C++0x [class.copymove]p31:
650 // When certain criteria are met, an implementation is allowed to omit the
651 // copy/move construction of a class object [...]
652 //
653 // - in a throw-expression, when the operand is the name of a
654 // non-volatile automatic object (other than a function or catch-clause
655 // parameter) whose scope does not extend beyond the end of the
656 // innermost enclosing try-block (if there is one), the copy/move
657 // operation from the operand to the exception object (15.1) can be
658 // omitted by constructing the automatic object directly into the
659 // exception object
660 const VarDecl *NRVOVariable = 0;
661 if (IsThrownVarInScope)
662 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
663
John McCall2e6567a2010-04-22 01:10:34 +0000664 InitializedEntity Entity =
Douglas Gregorc74edc22011-01-21 22:46:35 +0000665 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000666 /*NRVO=*/NRVOVariable != 0);
John Wiegley01296292011-04-08 18:41:53 +0000667 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000668 QualType(), E,
669 IsThrownVarInScope);
John McCall2e6567a2010-04-22 01:10:34 +0000670 if (Res.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000671 return ExprError();
672 E = Res.take();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000673
Eli Friedman91a3d272010-06-03 20:39:03 +0000674 // If the exception has class type, we need additional handling.
675 const RecordType *RecordTy = Ty->getAs<RecordType>();
676 if (!RecordTy)
John Wiegley01296292011-04-08 18:41:53 +0000677 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000678 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
679
Douglas Gregor88d292c2010-05-13 16:44:06 +0000680 // If we are throwing a polymorphic class type or pointer thereof,
681 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000682 MarkVTableUsed(ThrowLoc, RD);
683
Eli Friedman36ebbec2010-10-12 20:32:36 +0000684 // If a pointer is thrown, the referenced object will not be destroyed.
685 if (isPointer)
John Wiegley01296292011-04-08 18:41:53 +0000686 return Owned(E);
Eli Friedman36ebbec2010-10-12 20:32:36 +0000687
Richard Smitheec915d62012-02-18 04:13:32 +0000688 // If the class has a destructor, we must be able to call it.
689 if (RD->hasIrrelevantDestructor())
John Wiegley01296292011-04-08 18:41:53 +0000690 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000691
Sebastian Redl249dee52012-03-05 19:35:43 +0000692 CXXDestructorDecl *Destructor = LookupDestructor(RD);
Eli Friedman91a3d272010-06-03 20:39:03 +0000693 if (!Destructor)
John Wiegley01296292011-04-08 18:41:53 +0000694 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000695
Eli Friedmanfa0df832012-02-02 03:46:19 +0000696 MarkFunctionReferenced(E->getExprLoc(), Destructor);
Eli Friedman91a3d272010-06-03 20:39:03 +0000697 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregor747eb782010-07-08 06:14:04 +0000698 PDiag(diag::err_access_dtor_exception) << Ty);
Richard Smith22262ab2013-05-04 06:44:46 +0000699 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
700 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +0000701 return Owned(E);
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000702}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000703
Eli Friedman73a04092012-01-07 04:59:52 +0000704QualType Sema::getCurrentThisType() {
705 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +0000706 QualType ThisTy = CXXThisTypeOverride;
Richard Smith938f40b2011-06-11 17:19:42 +0000707 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
708 if (method && method->isInstance())
709 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000710 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000711
Richard Smith938f40b2011-06-11 17:19:42 +0000712 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +0000713}
714
Douglas Gregor3024f072012-04-16 07:05:22 +0000715Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
716 Decl *ContextDecl,
717 unsigned CXXThisTypeQuals,
718 bool Enabled)
719 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
720{
721 if (!Enabled || !ContextDecl)
722 return;
723
724 CXXRecordDecl *Record = 0;
725 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
726 Record = Template->getTemplatedDecl();
727 else
728 Record = cast<CXXRecordDecl>(ContextDecl);
729
730 S.CXXThisTypeOverride
731 = S.Context.getPointerType(
732 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
733
734 this->Enabled = true;
735}
736
737
738Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
739 if (Enabled) {
740 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
741 }
742}
743
Ben Langmuire7d7c4c2013-04-29 13:32:41 +0000744static Expr *captureThis(ASTContext &Context, RecordDecl *RD,
745 QualType ThisTy, SourceLocation Loc) {
746 FieldDecl *Field
747 = FieldDecl::Create(Context, RD, Loc, Loc, 0, ThisTy,
748 Context.getTrivialTypeSourceInfo(ThisTy, Loc),
749 0, false, ICIS_NoInit);
750 Field->setImplicit(true);
751 Field->setAccess(AS_private);
752 RD->addDecl(Field);
753 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/true);
754}
755
Faisal Valia17d19f2013-11-07 05:17:06 +0000756bool Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit,
757 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt) {
Eli Friedman73a04092012-01-07 04:59:52 +0000758 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +0000759 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +0000760 return true;
Eli Friedman73a04092012-01-07 04:59:52 +0000761
Faisal Valia17d19f2013-11-07 05:17:06 +0000762 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
763 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
764 // Otherwise, check that we can capture 'this'.
Eli Friedman73a04092012-01-07 04:59:52 +0000765 unsigned NumClosures = 0;
Faisal Valia17d19f2013-11-07 05:17:06 +0000766 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +0000767 if (CapturingScopeInfo *CSI =
768 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
769 if (CSI->CXXThisCaptureIndex != 0) {
770 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman73a04092012-01-07 04:59:52 +0000771 break;
772 }
Faisal Valia17d19f2013-11-07 05:17:06 +0000773 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
774 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
775 // This context can't implicitly capture 'this'; fail out.
776 if (BuildAndDiagnose)
777 Diag(Loc, diag::err_this_capture) << Explicit;
778 return true;
779 }
Eli Friedman20139d32012-01-11 02:36:31 +0000780 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +0000781 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000782 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000783 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000784 Explicit) {
785 // This closure can capture 'this'; continue looking upwards.
Eli Friedman73a04092012-01-07 04:59:52 +0000786 NumClosures++;
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000787 Explicit = false;
Eli Friedman73a04092012-01-07 04:59:52 +0000788 continue;
789 }
Eli Friedman20139d32012-01-11 02:36:31 +0000790 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +0000791 if (BuildAndDiagnose)
792 Diag(Loc, diag::err_this_capture) << Explicit;
793 return true;
Eli Friedman73a04092012-01-07 04:59:52 +0000794 }
Eli Friedman73a04092012-01-07 04:59:52 +0000795 break;
796 }
Faisal Valia17d19f2013-11-07 05:17:06 +0000797 if (!BuildAndDiagnose) return false;
Eli Friedman73a04092012-01-07 04:59:52 +0000798 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
799 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
800 // contexts.
Faisal Valia17d19f2013-11-07 05:17:06 +0000801 for (unsigned idx = MaxFunctionScopesIndex; NumClosures;
802 --idx, --NumClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +0000803 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Eli Friedmanc9751062012-02-11 02:51:16 +0000804 Expr *ThisExpr = 0;
Douglas Gregorfdf598e2012-02-18 09:37:24 +0000805 QualType ThisTy = getCurrentThisType();
Ben Langmuire7d7c4c2013-04-29 13:32:41 +0000806 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI))
Eli Friedmanc9751062012-02-11 02:51:16 +0000807 // For lambda expressions, build a field and an initializing expression.
Ben Langmuire7d7c4c2013-04-29 13:32:41 +0000808 ThisExpr = captureThis(Context, LSI->Lambda, ThisTy, Loc);
809 else if (CapturedRegionScopeInfo *RSI
810 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
811 ThisExpr = captureThis(Context, RSI->TheRecordDecl, ThisTy, Loc);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000812
Eli Friedman20139d32012-01-11 02:36:31 +0000813 bool isNested = NumClosures > 1;
Douglas Gregorfdf598e2012-02-18 09:37:24 +0000814 CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
Eli Friedman73a04092012-01-07 04:59:52 +0000815 }
Faisal Valia17d19f2013-11-07 05:17:06 +0000816 return false;
Eli Friedman73a04092012-01-07 04:59:52 +0000817}
818
Richard Smith938f40b2011-06-11 17:19:42 +0000819ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +0000820 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
821 /// is a non-lvalue expression whose value is the address of the object for
822 /// which the function is called.
823
Douglas Gregor09deffa2011-10-18 16:47:30 +0000824 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +0000825 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +0000826
Eli Friedman73a04092012-01-07 04:59:52 +0000827 CheckCXXThisCapture(Loc);
Richard Smith938f40b2011-06-11 17:19:42 +0000828 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000829}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000830
Douglas Gregor3024f072012-04-16 07:05:22 +0000831bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
832 // If we're outside the body of a member function, then we'll have a specified
833 // type for 'this'.
834 if (CXXThisTypeOverride.isNull())
835 return false;
836
837 // Determine whether we're looking into a class that's currently being
838 // defined.
839 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
840 return Class && Class->isBeingDefined();
841}
842
John McCalldadc5752010-08-24 06:29:42 +0000843ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +0000844Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000845 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000846 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000847 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000848 if (!TypeRep)
849 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000850
John McCall97513962010-01-15 18:39:57 +0000851 TypeSourceInfo *TInfo;
852 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
853 if (!TInfo)
854 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +0000855
856 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
857}
858
859/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
860/// Can be interpreted either as function-style casting ("int(x)")
861/// or class type construction ("ClassType(x,y,z)")
862/// or creation of a value-initialized type ("int()").
863ExprResult
864Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
865 SourceLocation LParenLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000866 MultiExprArg Exprs,
Douglas Gregor2b88c112010-09-08 00:15:04 +0000867 SourceLocation RParenLoc) {
868 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +0000869 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000870
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000871 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Douglas Gregor2b88c112010-09-08 00:15:04 +0000872 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregorce934142009-05-20 18:46:25 +0000873 LParenLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000874 Exprs,
Douglas Gregorce934142009-05-20 18:46:25 +0000875 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000876 }
877
Sebastian Redld74dd492012-02-12 18:41:05 +0000878 bool ListInitialization = LParenLoc.isInvalid();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000879 assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
Sebastian Redld74dd492012-02-12 18:41:05 +0000880 && "List initialization must have initializer list as expression.");
881 SourceRange FullRange = SourceRange(TyBeginLoc,
882 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
883
Douglas Gregordd04d332009-01-16 18:33:17 +0000884 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000885 // If the expression list is a single expression, the type conversion
886 // expression is equivalent (in definedness, and if defined in meaning) to the
887 // corresponding cast expression.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000888 if (Exprs.size() == 1 && !ListInitialization) {
John McCallb50451a2011-10-05 07:41:44 +0000889 Expr *Arg = Exprs[0];
John McCallb50451a2011-10-05 07:41:44 +0000890 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000891 }
892
Eli Friedman576cbd02012-02-29 00:00:28 +0000893 QualType ElemTy = Ty;
894 if (Ty->isArrayType()) {
895 if (!ListInitialization)
896 return ExprError(Diag(TyBeginLoc,
897 diag::err_value_init_for_array_type) << FullRange);
898 ElemTy = Context.getBaseElementType(Ty);
899 }
900
901 if (!Ty->isVoidType() &&
902 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000903 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +0000904 return ExprError();
905
906 if (RequireNonAbstractType(TyBeginLoc, Ty,
907 diag::err_allocation_of_abstract_type))
908 return ExprError();
909
Douglas Gregor8ec51732010-09-08 21:40:08 +0000910 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000911 InitializationKind Kind =
912 Exprs.size() ? ListInitialization
913 ? InitializationKind::CreateDirectList(TyBeginLoc)
914 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
915 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
916 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
917 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000918
Richard Smith90061902013-09-23 02:20:00 +0000919 if (Result.isInvalid() || !ListInitialization)
920 return Result;
921
922 Expr *Inner = Result.get();
923 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
924 Inner = BTE->getSubExpr();
925 if (isa<InitListExpr>(Inner)) {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000926 // If the list-initialization doesn't involve a constructor call, we'll get
927 // the initializer-list (with corrected type) back, but that's not what we
928 // want, since it will be treated as an initializer list in further
929 // processing. Explicitly insert a cast here.
Richard Smith90061902013-09-23 02:20:00 +0000930 QualType ResultType = Result.get()->getType();
931 Result = Owned(CXXFunctionalCastExpr::Create(
932 Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
933 CK_NoOp, Result.take(), /*Path=*/ 0, LParenLoc, RParenLoc));
Sebastian Redl2b80af42012-02-13 19:55:43 +0000934 }
935
Douglas Gregor8ec51732010-09-08 21:40:08 +0000936 // FIXME: Improve AST representation?
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000937 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000938}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000939
John McCall284c48f2011-01-27 09:37:56 +0000940/// doesUsualArrayDeleteWantSize - Answers whether the usual
941/// operator delete[] for the given type has a size_t parameter.
942static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
943 QualType allocType) {
944 const RecordType *record =
945 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
946 if (!record) return false;
947
948 // Try to find an operator delete[] in class scope.
949
950 DeclarationName deleteName =
951 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
952 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
953 S.LookupQualifiedName(ops, record->getDecl());
954
955 // We're just doing this for information.
956 ops.suppressDiagnostics();
957
958 // Very likely: there's no operator delete[].
959 if (ops.empty()) return false;
960
961 // If it's ambiguous, it should be illegal to call operator delete[]
962 // on this thing, so it doesn't matter if we allocate extra space or not.
963 if (ops.isAmbiguous()) return false;
964
965 LookupResult::Filter filter = ops.makeFilter();
966 while (filter.hasNext()) {
967 NamedDecl *del = filter.next()->getUnderlyingDecl();
968
969 // C++0x [basic.stc.dynamic.deallocation]p2:
970 // A template instance is never a usual deallocation function,
971 // regardless of its signature.
972 if (isa<FunctionTemplateDecl>(del)) {
973 filter.erase();
974 continue;
975 }
976
977 // C++0x [basic.stc.dynamic.deallocation]p2:
978 // If class T does not declare [an operator delete[] with one
979 // parameter] but does declare a member deallocation function
980 // named operator delete[] with exactly two parameters, the
981 // second of which has type std::size_t, then this function
982 // is a usual deallocation function.
983 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
984 filter.erase();
985 continue;
986 }
987 }
988 filter.done();
989
990 if (!ops.isSingleResult()) return false;
991
992 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
993 return (del->getNumParams() == 2);
994}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000995
Sebastian Redld74dd492012-02-12 18:41:05 +0000996/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +0000997///
Sebastian Redld74dd492012-02-12 18:41:05 +0000998/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +0000999/// @code new (memory) int[size][4] @endcode
1000/// or
1001/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001002///
1003/// \param StartLoc The first location of the expression.
1004/// \param UseGlobal True if 'new' was prefixed with '::'.
1005/// \param PlacementLParen Opening paren of the placement arguments.
1006/// \param PlacementArgs Placement new arguments.
1007/// \param PlacementRParen Closing paren of the placement arguments.
1008/// \param TypeIdParens If the type is in parens, the source range.
1009/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001010/// \param Initializer The initializing expression or initializer-list, or null
1011/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001012ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001013Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001014 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001015 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001016 Declarator &D, Expr *Initializer) {
Richard Smith74aeef52013-04-26 16:15:35 +00001017 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
Richard Smith30482bc2011-02-20 03:19:35 +00001018
Sebastian Redl351bb782008-12-02 14:43:59 +00001019 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +00001020 // If the specified type is an array, unwrap it and save the expression.
1021 if (D.getNumTypeObjects() > 0 &&
1022 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
James Dennettf14a6e52012-06-15 22:23:43 +00001023 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith30482bc2011-02-20 03:19:35 +00001024 if (TypeContainsAuto)
1025 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1026 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001027 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001028 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1029 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001030 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001031 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1032 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001033
Sebastian Redl351bb782008-12-02 14:43:59 +00001034 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001035 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001036 }
1037
Douglas Gregor73341c42009-09-11 00:18:58 +00001038 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001039 if (ArraySize) {
1040 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001041 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1042 break;
1043
1044 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1045 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001046 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001047 if (getLangOpts().CPlusPlus1y) {
1048 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1049 // shall be a converted constant expression (5.19) of type std::size_t
1050 // and shall evaluate to a strictly positive value.
1051 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1052 assert(IntWidth && "Builtin type of size 0?");
1053 llvm::APSInt Value(IntWidth);
1054 Array.NumElts
1055 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1056 CCEK_NewExpr)
1057 .take();
1058 } else {
1059 Array.NumElts
1060 = VerifyIntegerConstantExpression(NumElts, 0,
1061 diag::err_new_array_nonconst)
1062 .take();
1063 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001064 if (!Array.NumElts)
1065 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001066 }
1067 }
1068 }
1069 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001070
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +00001071 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCall8cb7bdf2010-06-04 23:28:52 +00001072 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001073 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001074 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001075
Sebastian Redl6047f072012-02-16 12:22:20 +00001076 SourceRange DirectInitRange;
1077 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1078 DirectInitRange = List->getSourceRange();
1079
David Blaikie7b97aef2012-11-07 00:12:38 +00001080 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001081 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001082 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001083 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001084 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001085 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001086 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001087 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001088 DirectInitRange,
1089 Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001090 TypeContainsAuto);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001091}
1092
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001093static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1094 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001095 if (!Init)
1096 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001097 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1098 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001099 if (isa<ImplicitValueInitExpr>(Init))
1100 return true;
1101 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1102 return !CCE->isListInitialization() &&
1103 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001104 else if (Style == CXXNewExpr::ListInit) {
1105 assert(isa<InitListExpr>(Init) &&
1106 "Shouldn't create list CXXConstructExprs for arrays.");
1107 return true;
1108 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001109 return false;
1110}
1111
John McCalldadc5752010-08-24 06:29:42 +00001112ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001113Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001114 SourceLocation PlacementLParen,
1115 MultiExprArg PlacementArgs,
1116 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001117 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001118 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001119 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001120 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001121 SourceRange DirectInitRange,
1122 Expr *Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001123 bool TypeMayContainAuto) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001124 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001125 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001126
Sebastian Redl6047f072012-02-16 12:22:20 +00001127 CXXNewExpr::InitializationStyle initStyle;
1128 if (DirectInitRange.isValid()) {
1129 assert(Initializer && "Have parens but no initializer.");
1130 initStyle = CXXNewExpr::CallInit;
1131 } else if (Initializer && isa<InitListExpr>(Initializer))
1132 initStyle = CXXNewExpr::ListInit;
1133 else {
1134 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1135 isa<CXXConstructExpr>(Initializer)) &&
1136 "Initializer expression that cannot have been implicitly created.");
1137 initStyle = CXXNewExpr::NoInit;
1138 }
1139
1140 Expr **Inits = &Initializer;
1141 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001142 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1143 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1144 Inits = List->getExprs();
1145 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001146 }
1147
Richard Smithdd2ca572012-11-26 08:32:48 +00001148 // Determine whether we've already built the initializer.
1149 bool HaveCompleteInit = false;
1150 if (Initializer && isa<CXXConstructExpr>(Initializer) &&
1151 !isa<CXXTemporaryObjectExpr>(Initializer))
1152 HaveCompleteInit = true;
1153 else if (Initializer && isa<ImplicitValueInitExpr>(Initializer))
1154 HaveCompleteInit = true;
1155
Richard Smith74801c82012-07-08 04:13:07 +00001156 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00001157 if (TypeMayContainAuto && AllocType->isUndeducedType()) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001158 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001159 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1160 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001161 if (initStyle == CXXNewExpr::ListInit)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001162 return ExprError(Diag(Inits[0]->getLocStart(),
Sebastian Redl6047f072012-02-16 12:22:20 +00001163 diag::err_auto_new_requires_parens)
1164 << AllocType << TypeRange);
1165 if (NumInits > 1) {
1166 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001167 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001168 diag::err_auto_new_ctor_multiple_expressions)
1169 << AllocType << TypeRange);
1170 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001171 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001172 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001173 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001174 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001175 << AllocType << Deduce->getType()
1176 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001177 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001178 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001179 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001180 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001181
Douglas Gregorcda95f42010-05-16 16:01:03 +00001182 // Per C++0x [expr.new]p5, the type being constructed may be a
1183 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001184 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001185 if (const ConstantArrayType *Array
1186 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001187 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1188 Context.getSizeType(),
1189 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001190 AllocType = Array->getElementType();
1191 }
1192 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001193
Douglas Gregor3999e152010-10-06 16:00:31 +00001194 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1195 return ExprError();
1196
Sebastian Redl6047f072012-02-16 12:22:20 +00001197 if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001198 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1199 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001200 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001201 }
1202
John McCall31168b02011-06-15 23:02:42 +00001203 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001204 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001205 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1206 AllocType->isObjCLifetimeType()) {
1207 AllocType = Context.getLifetimeQualifiedType(AllocType,
1208 AllocType->getObjCARCImplicitLifetime());
1209 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001210
John McCall31168b02011-06-15 23:02:42 +00001211 QualType ResultType = Context.getPointerType(AllocType);
1212
John McCall5e77d762013-04-16 07:28:30 +00001213 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1214 ExprResult result = CheckPlaceholderExpr(ArraySize);
1215 if (result.isInvalid()) return ExprError();
1216 ArraySize = result.take();
1217 }
Richard Smith8dd34252012-02-04 07:07:42 +00001218 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1219 // integral or enumeration type with a non-negative value."
1220 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1221 // enumeration type, or a class type for which a single non-explicit
1222 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001223 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001224 // std::size_t.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001225 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001226 ExprResult ConvertedSize;
1227 if (getLangOpts().CPlusPlus1y) {
1228 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1229 assert(IntWidth && "Builtin type of size 0?");
1230 llvm::APSInt Value(IntWidth);
1231 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1232 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001233
Larisse Voufobf4aa572013-06-18 03:08:53 +00001234 if (!ConvertedSize.isInvalid() &&
1235 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001236 // Diagnose the compatibility of this conversion.
1237 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1238 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001239 } else {
1240 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1241 protected:
1242 Expr *ArraySize;
1243
1244 public:
1245 SizeConvertDiagnoser(Expr *ArraySize)
1246 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1247 ArraySize(ArraySize) {}
1248
1249 virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1250 QualType T) {
1251 return S.Diag(Loc, diag::err_array_size_not_integral)
1252 << S.getLangOpts().CPlusPlus11 << T;
1253 }
1254
1255 virtual SemaDiagnosticBuilder diagnoseIncomplete(
1256 Sema &S, SourceLocation Loc, QualType T) {
1257 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1258 << T << ArraySize->getSourceRange();
1259 }
1260
1261 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
1262 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
1263 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1264 }
1265
1266 virtual SemaDiagnosticBuilder noteExplicitConv(
1267 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
1268 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1269 << ConvTy->isEnumeralType() << ConvTy;
1270 }
1271
1272 virtual SemaDiagnosticBuilder diagnoseAmbiguous(
1273 Sema &S, SourceLocation Loc, QualType T) {
1274 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1275 }
1276
1277 virtual SemaDiagnosticBuilder noteAmbiguous(
1278 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
1279 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1280 << ConvTy->isEnumeralType() << ConvTy;
1281 }
Richard Smithccc11812013-05-21 19:05:48 +00001282
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001283 virtual SemaDiagnosticBuilder diagnoseConversion(
1284 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
1285 return S.Diag(Loc,
1286 S.getLangOpts().CPlusPlus11
1287 ? diag::warn_cxx98_compat_array_size_conversion
1288 : diag::ext_array_size_conversion)
1289 << T << ConvTy->isEnumeralType() << ConvTy;
1290 }
1291 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001292
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001293 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1294 SizeDiagnoser);
1295 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001296 if (ConvertedSize.isInvalid())
1297 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001298
John McCallb268a282010-08-23 23:25:46 +00001299 ArraySize = ConvertedSize.take();
John McCall9b80c212012-01-11 00:14:46 +00001300 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001301
Douglas Gregor0bf31402010-10-08 23:50:27 +00001302 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001303 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001304
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001305 // C++98 [expr.new]p7:
1306 // The expression in a direct-new-declarator shall have integral type
1307 // with a non-negative value.
1308 //
1309 // Let's see if this is a constant < 0. If so, we reject it out of
1310 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1311 // array type.
1312 //
1313 // Note: such a construct has well-defined semantics in C++11: it throws
1314 // std::bad_array_new_length.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001315 if (!ArraySize->isValueDependent()) {
1316 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001317 // We've already performed any required implicit conversion to integer or
1318 // unscoped enumeration type.
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001319 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001320 if (Value < llvm::APSInt(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001321 llvm::APInt::getNullValue(Value.getBitWidth()),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001322 Value.isUnsigned())) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001323 if (getLangOpts().CPlusPlus11)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001324 Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001325 diag::warn_typecheck_negative_array_new_size)
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001326 << ArraySize->getSourceRange();
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001327 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001328 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001329 diag::err_typecheck_negative_array_size)
1330 << ArraySize->getSourceRange());
1331 } else if (!AllocType->isDependentType()) {
1332 unsigned ActiveSizeBits =
1333 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1334 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001335 if (getLangOpts().CPlusPlus11)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001336 Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001337 diag::warn_array_new_too_large)
1338 << Value.toString(10)
1339 << ArraySize->getSourceRange();
1340 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001341 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001342 diag::err_array_too_large)
1343 << Value.toString(10)
1344 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001345 }
1346 }
Douglas Gregorf2753b32010-07-13 15:54:32 +00001347 } else if (TypeIdParens.isValid()) {
1348 // Can't have dynamic array size when the type-id is in parentheses.
1349 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1350 << ArraySize->getSourceRange()
1351 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1352 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001353
Douglas Gregorf2753b32010-07-13 15:54:32 +00001354 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001355 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001356 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001357
John McCall036f2f62011-05-15 07:14:44 +00001358 // Note that we do *not* convert the argument in any way. It can
1359 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001360 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001361
Sebastian Redlbd150f42008-11-21 19:14:01 +00001362 FunctionDecl *OperatorNew = 0;
1363 FunctionDecl *OperatorDelete = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001364
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001365 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001366 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001367 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001368 SourceRange(PlacementLParen, PlacementRParen),
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001369 UseGlobal, AllocType, ArraySize, PlacementArgs,
1370 OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001371 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001372
1373 // If this is an array allocation, compute whether the usual array
1374 // deallocation function for the type has a size_t parameter.
1375 bool UsualArrayDeleteWantsSize = false;
1376 if (ArraySize && !AllocType->isDependentType())
1377 UsualArrayDeleteWantsSize
1378 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1379
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001380 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001381 if (OperatorNew) {
1382 // Add default arguments, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001383 const FunctionProtoType *Proto =
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001384 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001385 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00001386 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001388 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1,
1389 PlacementArgs, AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001390 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001391
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001392 if (!AllPlaceArgs.empty())
1393 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00001394
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001395 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00001396
1397 // FIXME: Missing call to CheckFunctionCall or equivalent
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001399
Nick Lewycky411fc652012-01-24 21:15:41 +00001400 // Warn if the type is over-aligned and is being allocated by global operator
1401 // new.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001402 if (PlacementArgs.empty() && OperatorNew &&
Nick Lewycky411fc652012-01-24 21:15:41 +00001403 (OperatorNew->isImplicit() ||
1404 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1405 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1406 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1407 if (Align > SuitableAlign)
1408 Diag(StartLoc, diag::warn_overaligned_type)
1409 << AllocType
1410 << unsigned(Align / Context.getCharWidth())
1411 << unsigned(SuitableAlign / Context.getCharWidth());
1412 }
1413 }
1414
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001415 QualType InitType = AllocType;
Sebastian Redl6047f072012-02-16 12:22:20 +00001416 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001417 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1418 // dialect distinction.
1419 if (ResultType->isArrayType() || ArraySize) {
1420 if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1421 SourceRange InitRange(Inits[0]->getLocStart(),
1422 Inits[NumInits - 1]->getLocEnd());
1423 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1424 return ExprError();
1425 }
1426 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1427 // We do the initialization typechecking against the array type
1428 // corresponding to the number of initializers + 1 (to also check
1429 // default-initialization).
1430 unsigned NumElements = ILE->getNumInits() + 1;
1431 InitType = Context.getConstantArrayType(AllocType,
1432 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1433 ArrayType::Normal, 0);
1434 }
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001435 }
1436
Richard Smithdd2ca572012-11-26 08:32:48 +00001437 // If we can perform the initialization, and we've not already done so,
1438 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00001439 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001440 !Expr::hasAnyTypeDependentArguments(
Richard Smithdd2ca572012-11-26 08:32:48 +00001441 llvm::makeArrayRef(Inits, NumInits)) &&
1442 !HaveCompleteInit) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001443 // C++11 [expr.new]p15:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001444 // A new-expression that creates an object of type T initializes that
1445 // object as follows:
1446 InitializationKind Kind
1447 // - If the new-initializer is omitted, the object is default-
1448 // initialized (8.5); if no initialization is performed,
1449 // the object has indeterminate value
Sebastian Redl6047f072012-02-16 12:22:20 +00001450 = initStyle == CXXNewExpr::NoInit
1451 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001452 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001453 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +00001454 : initStyle == CXXNewExpr::ListInit
1455 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1456 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1457 DirectInitRange.getBegin(),
1458 DirectInitRange.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001459
Douglas Gregor85dabae2009-12-16 01:38:02 +00001460 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001461 = InitializedEntity::InitializeNew(StartLoc, InitType);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001462 InitializationSequence InitSeq(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001463 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00001464 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00001465 if (FullInit.isInvalid())
1466 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467
Sebastian Redl6047f072012-02-16 12:22:20 +00001468 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1469 // we don't want the initialized object to be destructed.
1470 if (CXXBindTemporaryExpr *Binder =
1471 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1472 FullInit = Owned(Binder->getSubExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001473
Sebastian Redl6047f072012-02-16 12:22:20 +00001474 Initializer = FullInit.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001475 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001476
Douglas Gregor6642ca22010-02-26 05:06:18 +00001477 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00001478 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00001479 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1480 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001481 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00001482 }
1483 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00001484 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1485 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001486 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00001487 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00001488
John McCall928a2572011-07-13 20:12:57 +00001489 // C++0x [expr.new]p17:
1490 // If the new expression creates an array of objects of class type,
1491 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00001492 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1493 if (ArraySize && !BaseAllocType->isDependentType()) {
1494 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1495 if (CXXDestructorDecl *dtor = LookupDestructor(
1496 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1497 MarkFunctionReferenced(StartLoc, dtor);
1498 CheckDestructorAccess(StartLoc, dtor,
1499 PDiag(diag::err_access_dtor)
1500 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00001501 if (DiagnoseUseOfDecl(dtor, StartLoc))
1502 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00001503 }
John McCall928a2572011-07-13 20:12:57 +00001504 }
1505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001506
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001507 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00001508 OperatorDelete,
John McCall284c48f2011-01-27 09:37:56 +00001509 UsualArrayDeleteWantsSize,
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001510 PlacementArgs, TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001511 ArraySize, initStyle, Initializer,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001512 ResultType, AllocTypeInfo,
David Blaikie7b97aef2012-11-07 00:12:38 +00001513 Range, DirectInitRange));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001514}
1515
Sebastian Redl6047f072012-02-16 12:22:20 +00001516/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00001517/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00001518bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00001519 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00001520 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1521 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00001522 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001523 return Diag(Loc, diag::err_bad_new_type)
1524 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001525 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001526 return Diag(Loc, diag::err_bad_new_type)
1527 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001528 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001529 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00001530 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00001531 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00001532 diag::err_allocation_of_abstract_type))
1533 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00001534 else if (AllocType->isVariablyModifiedType())
1535 return Diag(Loc, diag::err_variably_modified_new_type)
1536 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00001537 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1538 return Diag(Loc, diag::err_address_space_qualified_new)
1539 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001540 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001541 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1542 QualType BaseAllocType = Context.getBaseElementType(AT);
1543 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1544 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001545 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00001546 << BaseAllocType;
1547 }
1548 }
Douglas Gregor39d1a092011-04-15 19:46:20 +00001549
Sebastian Redlbd150f42008-11-21 19:14:01 +00001550 return false;
1551}
1552
Douglas Gregor6642ca22010-02-26 05:06:18 +00001553/// \brief Determine whether the given function is a non-placement
1554/// deallocation function.
Richard Smith1cdec012013-09-29 04:40:38 +00001555static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001556 if (FD->isInvalidDecl())
1557 return false;
1558
1559 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1560 return Method->isUsualDeallocationFunction();
1561
Richard Smith1cdec012013-09-29 04:40:38 +00001562 if (FD->getOverloadedOperator() != OO_Delete &&
1563 FD->getOverloadedOperator() != OO_Array_Delete)
1564 return false;
1565
1566 if (FD->getNumParams() == 1)
1567 return true;
1568
1569 return S.getLangOpts().SizedDeallocation && FD->getNumParams() == 2 &&
1570 S.Context.hasSameUnqualifiedType(FD->getParamDecl(1)->getType(),
1571 S.Context.getSizeType());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001572}
1573
Sebastian Redlfaf68082008-12-03 20:26:15 +00001574/// FindAllocationFunctions - Finds the overloads of operator new and delete
1575/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001576bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1577 bool UseGlobal, QualType AllocType,
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001578 bool IsArray, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00001579 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00001580 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001581 // --- Choosing an allocation function ---
1582 // C++ 5.3.4p8 - 14 & 18
1583 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1584 // in the scope of the allocated class.
1585 // 2) If an array size is given, look for operator new[], else look for
1586 // operator new.
1587 // 3) The first argument is always size_t. Append the arguments from the
1588 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001589
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001590 SmallVector<Expr*, 8> AllocArgs(1 + PlaceArgs.size());
Sebastian Redlfaf68082008-12-03 20:26:15 +00001591 // We don't care about the actual value of this argument.
1592 // FIXME: Should the Sema create the expression and embed it in the syntax
1593 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001594 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00001595 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00001596 Context.getSizeType(),
1597 SourceLocation());
1598 AllocArgs[0] = &Size;
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001599 std::copy(PlaceArgs.begin(), PlaceArgs.end(), AllocArgs.begin() + 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001600
Douglas Gregor6642ca22010-02-26 05:06:18 +00001601 // C++ [expr.new]p8:
1602 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001603 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00001604 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001605 // type, the allocation function's name is operator new[] and the
1606 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00001607 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1608 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001609 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1610 IsArray ? OO_Array_Delete : OO_Delete);
1611
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001612 QualType AllocElemType = Context.getBaseElementType(AllocType);
1613
1614 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +00001615 CXXRecordDecl *Record
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001616 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001617 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, Record,
1618 /*AllowMissing=*/true, OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001619 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001620 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00001621
Sebastian Redlfaf68082008-12-03 20:26:15 +00001622 if (!OperatorNew) {
1623 // Didn't find a member overload. Look for a global one.
1624 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +00001625 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Aaron Ballman324fbee2013-05-30 01:55:39 +00001626 bool FallbackEnabled = IsArray && Context.getLangOpts().MicrosoftMode;
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001627 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
Aaron Ballman324fbee2013-05-30 01:55:39 +00001628 /*AllowMissing=*/FallbackEnabled, OperatorNew,
1629 /*Diagnose=*/!FallbackEnabled)) {
1630 if (!FallbackEnabled)
1631 return true;
1632
1633 // MSVC will fall back on trying to find a matching global operator new
1634 // if operator new[] cannot be found. Also, MSVC will leak by not
1635 // generating a call to operator delete or operator delete[], but we
1636 // will not replicate that bug.
1637 NewName = Context.DeclarationNames.getCXXOperatorName(OO_New);
1638 DeleteName = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
1639 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001640 /*AllowMissing=*/false, OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001641 return true;
Aaron Ballman324fbee2013-05-30 01:55:39 +00001642 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001643 }
1644
John McCall0f55a032010-04-20 02:18:25 +00001645 // We don't need an operator delete if we're running under
1646 // -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001647 if (!getLangOpts().Exceptions) {
John McCall0f55a032010-04-20 02:18:25 +00001648 OperatorDelete = 0;
1649 return false;
1650 }
1651
Anders Carlsson6f9dabf2009-05-31 20:26:12 +00001652 // FindAllocationOverload can change the passed in arguments, so we need to
1653 // copy them back.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001654 if (!PlaceArgs.empty())
1655 std::copy(AllocArgs.begin() + 1, AllocArgs.end(), PlaceArgs.data());
Mike Stump11289f42009-09-09 15:08:12 +00001656
Douglas Gregor6642ca22010-02-26 05:06:18 +00001657 // C++ [expr.new]p19:
1658 //
1659 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001660 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00001661 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001662 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00001663 // the scope of T. If this lookup fails to find the name, or if
1664 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001665 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001666 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001667 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001668 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001669 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001670 LookupQualifiedName(FoundDelete, RD);
1671 }
John McCallfb6f5262010-03-18 08:19:33 +00001672 if (FoundDelete.isAmbiguous())
1673 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00001674
1675 if (FoundDelete.empty()) {
1676 DeclareGlobalNewDelete();
1677 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1678 }
1679
1680 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00001681
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001682 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00001683
John McCalld3be2c82010-09-14 21:34:24 +00001684 // Whether we're looking for a placement operator delete is dictated
1685 // by whether we selected a placement operator new, not by whether
1686 // we had explicit placement arguments. This matters for things like
1687 // struct A { void *operator new(size_t, int = 0); ... };
1688 // A *a = new A()
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001689 bool isPlacementNew = (!PlaceArgs.empty() || OperatorNew->param_size() != 1);
John McCalld3be2c82010-09-14 21:34:24 +00001690
1691 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001692 // C++ [expr.new]p20:
1693 // A declaration of a placement deallocation function matches the
1694 // declaration of a placement allocation function if it has the
1695 // same number of parameters and, after parameter transformations
1696 // (8.3.5), all parameter types except the first are
1697 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001698 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00001699 // To perform this comparison, we compute the function type that
1700 // the deallocation function should have, and use that type both
1701 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00001702 //
1703 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001704 QualType ExpectedFunctionType;
1705 {
1706 const FunctionProtoType *Proto
1707 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00001708
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001709 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001710 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001711 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1712 ArgTypes.push_back(Proto->getArgType(I));
1713
John McCalldb40c7f2010-12-14 08:05:40 +00001714 FunctionProtoType::ExtProtoInfo EPI;
1715 EPI.Variadic = Proto->isVariadic();
1716
Douglas Gregor6642ca22010-02-26 05:06:18 +00001717 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00001718 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001719 }
1720
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001721 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001722 DEnd = FoundDelete.end();
1723 D != DEnd; ++D) {
1724 FunctionDecl *Fn = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001725 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6642ca22010-02-26 05:06:18 +00001726 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1727 // Perform template argument deduction to try to match the
1728 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00001729 TemplateDeductionInfo Info(StartLoc);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001730 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1731 continue;
1732 } else
1733 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1734
1735 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001736 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001737 }
1738 } else {
1739 // C++ [expr.new]p20:
1740 // [...] Any non-placement deallocation function matches a
1741 // non-placement allocation function. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001742 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001743 DEnd = FoundDelete.end();
1744 D != DEnd; ++D) {
1745 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
Richard Smith1cdec012013-09-29 04:40:38 +00001746 if (isNonPlacementDeallocationFunction(*this, Fn))
John McCalla0296f72010-03-19 07:35:19 +00001747 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001748 }
Richard Smith1cdec012013-09-29 04:40:38 +00001749
1750 // C++1y [expr.new]p22:
1751 // For a non-placement allocation function, the normal deallocation
1752 // function lookup is used
1753 // C++1y [expr.delete]p?:
1754 // If [...] deallocation function lookup finds both a usual deallocation
1755 // function with only a pointer parameter and a usual deallocation
1756 // function with both a pointer parameter and a size parameter, then the
1757 // selected deallocation function shall be the one with two parameters.
1758 // Otherwise, the selected deallocation function shall be the function
1759 // with one parameter.
1760 if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
1761 if (Matches[0].second->getNumParams() == 1)
1762 Matches.erase(Matches.begin());
1763 else
1764 Matches.erase(Matches.begin() + 1);
1765 assert(Matches[0].second->getNumParams() == 2 &&
1766 "found an unexpected uusal deallocation function");
1767 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00001768 }
1769
1770 // C++ [expr.new]p20:
1771 // [...] If the lookup finds a single matching deallocation
1772 // function, that function will be called; otherwise, no
1773 // deallocation function will be called.
1774 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001775 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001776
1777 // C++0x [expr.new]p20:
1778 // If the lookup finds the two-parameter form of a usual
1779 // deallocation function (3.7.4.2) and that function, considered
1780 // as a placement deallocation function, would have been
1781 // selected as a match for the allocation function, the program
1782 // is ill-formed.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001783 if (!PlaceArgs.empty() && getLangOpts().CPlusPlus11 &&
Richard Smith1cdec012013-09-29 04:40:38 +00001784 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001785 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001786 << SourceRange(PlaceArgs.front()->getLocStart(),
1787 PlaceArgs.back()->getLocEnd());
Richard Smith1cdec012013-09-29 04:40:38 +00001788 if (!OperatorDelete->isImplicit())
1789 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1790 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001791 } else {
1792 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001793 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001794 }
1795 }
1796
Sebastian Redlfaf68082008-12-03 20:26:15 +00001797 return false;
1798}
1799
Sebastian Redl33a31012008-12-04 22:20:51 +00001800/// FindAllocationOverload - Find an fitting overload for the allocation
1801/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001802bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001803 DeclarationName Name, MultiExprArg Args,
1804 DeclContext *Ctx,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001805 bool AllowMissing, FunctionDecl *&Operator,
1806 bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001807 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1808 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001809 if (R.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001810 if (AllowMissing || !Diagnose)
Sebastian Redl33a31012008-12-04 22:20:51 +00001811 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001812 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001813 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001814 }
1815
John McCallfb6f5262010-03-18 08:19:33 +00001816 if (R.isAmbiguous())
1817 return true;
1818
1819 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001820
John McCallbc077cf2010-02-08 23:07:23 +00001821 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001822 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001823 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001824 // Even member operator new/delete are implicitly treated as
1825 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001826 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001827
John McCalla0296f72010-03-19 07:35:19 +00001828 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1829 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001830 /*ExplicitTemplateArgs=*/0,
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001831 Args, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001832 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001833 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001834 }
1835
John McCalla0296f72010-03-19 07:35:19 +00001836 FunctionDecl *Fn = cast<FunctionDecl>(D);
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001837 AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001838 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001839 }
1840
1841 // Do the resolution.
1842 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00001843 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001844 case OR_Success: {
1845 // Got one!
1846 FunctionDecl *FnDecl = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00001847 MarkFunctionReferenced(StartLoc, FnDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001848 // The first argument is size_t, and the first parameter must be size_t,
1849 // too. This is checked on declaration and can be assumed. (It can't be
1850 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001851 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001852 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001853 for (unsigned i = 0; (i < Args.size() && i < NumArgsInFnDecl); ++i) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001854 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1855 FnDecl->getParamDecl(i));
1856
1857 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1858 return true;
1859
John McCalldadc5752010-08-24 06:29:42 +00001860 ExprResult Result
Alexis Hunt1f69a022011-05-12 22:46:29 +00001861 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor34147272010-03-26 20:35:59 +00001862 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001863 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001864
Douglas Gregor34147272010-03-26 20:35:59 +00001865 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001866 }
Richard Smith921bd202012-02-26 09:11:52 +00001867
Sebastian Redl33a31012008-12-04 22:20:51 +00001868 Operator = FnDecl;
Richard Smith921bd202012-02-26 09:11:52 +00001869
1870 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1871 Best->FoundDecl, Diagnose) == AR_inaccessible)
1872 return true;
1873
Sebastian Redl33a31012008-12-04 22:20:51 +00001874 return false;
1875 }
1876
1877 case OR_No_Viable_Function:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001878 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001879 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1880 << Name << Range;
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001881 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
Chandler Carruthe6c88182011-06-08 10:26:03 +00001882 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001883 return true;
1884
1885 case OR_Ambiguous:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001886 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001887 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1888 << Name << Range;
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001889 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args);
Chandler Carruthe6c88182011-06-08 10:26:03 +00001890 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001891 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001892
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001893 case OR_Deleted: {
Chandler Carruthe6c88182011-06-08 10:26:03 +00001894 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001895 Diag(StartLoc, diag::err_ovl_deleted_call)
1896 << Best->Function->isDeleted()
1897 << Name
1898 << getDeletedOrUnavailableSuffix(Best->Function)
1899 << Range;
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001900 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
Chandler Carruthe6c88182011-06-08 10:26:03 +00001901 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00001902 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001903 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001904 }
David Blaikie83d382b2011-09-23 05:06:16 +00001905 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl33a31012008-12-04 22:20:51 +00001906}
1907
1908
Sebastian Redlfaf68082008-12-03 20:26:15 +00001909/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1910/// delete. These are:
1911/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00001912/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00001913/// void* operator new(std::size_t) throw(std::bad_alloc);
1914/// void* operator new[](std::size_t) throw(std::bad_alloc);
1915/// void operator delete(void *) throw();
1916/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00001917/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00001918/// void* operator new(std::size_t);
1919/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00001920/// void operator delete(void *) noexcept;
1921/// void operator delete[](void *) noexcept;
1922/// // C++1y:
1923/// void* operator new(std::size_t);
1924/// void* operator new[](std::size_t);
1925/// void operator delete(void *) noexcept;
1926/// void operator delete[](void *) noexcept;
1927/// void operator delete(void *, std::size_t) noexcept;
1928/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001929/// @endcode
1930/// Note that the placement and nothrow forms of new are *not* implicitly
1931/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001932void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001933 if (GlobalNewDeleteDeclared)
1934 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001935
Douglas Gregor87f54062009-09-15 22:30:29 +00001936 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001937 // [...] The following allocation and deallocation functions (18.4) are
1938 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00001939 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001940 //
Sebastian Redl37588092011-03-14 18:08:30 +00001941 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00001942 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001943 // void* operator new[](std::size_t) throw(std::bad_alloc);
1944 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00001945 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00001946 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00001947 // void* operator new(std::size_t);
1948 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00001949 // void operator delete(void*) noexcept;
1950 // void operator delete[](void*) noexcept;
1951 // C++1y:
1952 // void* operator new(std::size_t);
1953 // void* operator new[](std::size_t);
1954 // void operator delete(void*) noexcept;
1955 // void operator delete[](void*) noexcept;
1956 // void operator delete(void*, std::size_t) noexcept;
1957 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00001958 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00001960 // new, operator new[], operator delete, operator delete[].
1961 //
1962 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1963 // "std" or "bad_alloc" as necessary to form the exception specification.
1964 // However, we do not make these implicit declarations visible to name
1965 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001966 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001967 // The "std::bad_alloc" class has not yet been declared, so build it
1968 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001969 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1970 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001971 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001972 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001973 0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001974 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00001975 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001976
Sebastian Redlfaf68082008-12-03 20:26:15 +00001977 GlobalNewDeleteDeclared = true;
1978
1979 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1980 QualType SizeT = Context.getSizeType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001981 bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001982
Sebastian Redlfaf68082008-12-03 20:26:15 +00001983 DeclareGlobalAllocationFunction(
1984 Context.DeclarationNames.getCXXOperatorName(OO_New),
Richard Smith1cdec012013-09-29 04:40:38 +00001985 VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001986 DeclareGlobalAllocationFunction(
1987 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Richard Smith1cdec012013-09-29 04:40:38 +00001988 VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001989 DeclareGlobalAllocationFunction(
1990 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1991 Context.VoidTy, VoidPtr);
1992 DeclareGlobalAllocationFunction(
1993 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1994 Context.VoidTy, VoidPtr);
Richard Smith1cdec012013-09-29 04:40:38 +00001995 if (getLangOpts().SizedDeallocation) {
1996 DeclareGlobalAllocationFunction(
1997 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1998 Context.VoidTy, VoidPtr, Context.getSizeType());
1999 DeclareGlobalAllocationFunction(
2000 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2001 Context.VoidTy, VoidPtr, Context.getSizeType());
2002 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002003}
2004
2005/// DeclareGlobalAllocationFunction - Declares a single implicit global
2006/// allocation function if it doesn't already exist.
2007void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002008 QualType Return,
2009 QualType Param1, QualType Param2,
Nuno Lopes13c88c72009-12-16 16:59:22 +00002010 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002011 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
Richard Smith1cdec012013-09-29 04:40:38 +00002012 unsigned NumParams = Param2.isNull() ? 1 : 2;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002013
2014 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002015 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2016 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2017 Alloc != AllocEnd; ++Alloc) {
2018 // Only look at non-template functions, as it is the predefined,
2019 // non-templated allocation function we are trying to declare here.
2020 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith1cdec012013-09-29 04:40:38 +00002021 if (Func->getNumParams() == NumParams) {
2022 QualType InitialParam1Type =
2023 Context.getCanonicalType(Func->getParamDecl(0)
2024 ->getType().getUnqualifiedType());
2025 QualType InitialParam2Type =
2026 NumParams == 2
2027 ? Context.getCanonicalType(Func->getParamDecl(1)
2028 ->getType().getUnqualifiedType())
2029 : QualType();
Chandler Carruth93538422010-02-03 11:02:14 +00002030 // FIXME: Do we need to check for default arguments here?
Richard Smith1cdec012013-09-29 04:40:38 +00002031 if (InitialParam1Type == Param1 &&
2032 (NumParams == 1 || InitialParam2Type == Param2)) {
Richard Smith42713d72013-07-14 02:01:48 +00002033 if (AddMallocAttr && !Func->hasAttr<MallocAttr>())
Serge Pavlovd5489072013-09-14 12:00:01 +00002034 Func->addAttr(::new (Context) MallocAttr(SourceLocation(),
2035 Context));
2036 // Make the function visible to name lookup, even if we found it in
2037 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002038 // allocation function, or is suppressing that function.
2039 Func->setHidden(false);
Chandler Carruth93538422010-02-03 11:02:14 +00002040 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002041 }
Chandler Carruth93538422010-02-03 11:02:14 +00002042 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002043 }
2044 }
2045
Douglas Gregor87f54062009-09-15 22:30:29 +00002046 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002047 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002048 = (Name.getCXXOverloadedOperator() == OO_New ||
2049 Name.getCXXOverloadedOperator() == OO_Array_New);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002050 if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002051 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002052 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00002053 }
John McCalldb40c7f2010-12-14 08:05:40 +00002054
2055 FunctionProtoType::ExtProtoInfo EPI;
John McCalldb40c7f2010-12-14 08:05:40 +00002056 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002057 if (!getLangOpts().CPlusPlus11) {
Sebastian Redl37588092011-03-14 18:08:30 +00002058 EPI.ExceptionSpecType = EST_Dynamic;
2059 EPI.NumExceptions = 1;
2060 EPI.Exceptions = &BadAllocType;
2061 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002062 } else {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002063 EPI.ExceptionSpecType = getLangOpts().CPlusPlus11 ?
Sebastian Redl37588092011-03-14 18:08:30 +00002064 EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002066
Richard Smith1cdec012013-09-29 04:40:38 +00002067 QualType Params[] = { Param1, Param2 };
2068
2069 QualType FnType = Context.getFunctionType(
2070 Return, ArrayRef<QualType>(Params, NumParams), EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002071 FunctionDecl *Alloc =
Abramo Bagnaradff19302011-03-08 08:55:46 +00002072 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
2073 SourceLocation(), Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002074 FnType, /*TInfo=*/0, SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002075 Alloc->setImplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002076
Nuno Lopes13c88c72009-12-16 16:59:22 +00002077 if (AddMallocAttr)
Alexis Huntdcfba7b2010-08-18 23:23:40 +00002078 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002079
Richard Smith1cdec012013-09-29 04:40:38 +00002080 ParmVarDecl *ParamDecls[2];
2081 for (unsigned I = 0; I != NumParams; ++I)
2082 ParamDecls[I] = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
2083 SourceLocation(), 0,
2084 Params[I], /*TInfo=*/0,
2085 SC_None, 0);
2086 Alloc->setParams(ArrayRef<ParmVarDecl*>(ParamDecls, NumParams));
Sebastian Redlfaf68082008-12-03 20:26:15 +00002087
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00002088 // FIXME: Also add this declaration to the IdentifierResolver, but
2089 // make sure it is at the end of the chain to coincide with the
2090 // global scope.
John McCallcc14d1f2010-08-24 08:50:51 +00002091 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002092}
2093
Richard Smith1cdec012013-09-29 04:40:38 +00002094FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2095 bool CanProvideSize,
2096 DeclarationName Name) {
2097 DeclareGlobalNewDelete();
2098
2099 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2100 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2101
2102 // C++ [expr.new]p20:
2103 // [...] Any non-placement deallocation function matches a
2104 // non-placement allocation function. [...]
2105 llvm::SmallVector<FunctionDecl*, 2> Matches;
2106 for (LookupResult::iterator D = FoundDelete.begin(),
2107 DEnd = FoundDelete.end();
2108 D != DEnd; ++D) {
2109 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*D))
2110 if (isNonPlacementDeallocationFunction(*this, Fn))
2111 Matches.push_back(Fn);
2112 }
2113
2114 // C++1y [expr.delete]p?:
2115 // If the type is complete and deallocation function lookup finds both a
2116 // usual deallocation function with only a pointer parameter and a usual
2117 // deallocation function with both a pointer parameter and a size
2118 // parameter, then the selected deallocation function shall be the one
2119 // with two parameters. Otherwise, the selected deallocation function
2120 // shall be the function with one parameter.
2121 if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
2122 unsigned NumArgs = CanProvideSize ? 2 : 1;
2123 if (Matches[0]->getNumParams() != NumArgs)
2124 Matches.erase(Matches.begin());
2125 else
2126 Matches.erase(Matches.begin() + 1);
2127 assert(Matches[0]->getNumParams() == NumArgs &&
2128 "found an unexpected uusal deallocation function");
2129 }
2130
2131 assert(Matches.size() == 1 &&
2132 "unexpectedly have multiple usual deallocation functions");
2133 return Matches.front();
2134}
2135
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002136bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2137 DeclarationName Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00002138 FunctionDecl* &Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002139 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002140 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002141 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002142
John McCall27b18f82009-11-17 02:14:36 +00002143 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002144 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002145
Chandler Carruthb6f99172010-06-28 00:30:51 +00002146 Found.suppressDiagnostics();
2147
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002148 SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002149 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2150 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00002151 NamedDecl *ND = (*F)->getUnderlyingDecl();
2152
2153 // Ignore template operator delete members from the check for a usual
2154 // deallocation function.
2155 if (isa<FunctionTemplateDecl>(ND))
2156 continue;
2157
2158 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00002159 Matches.push_back(F.getPair());
2160 }
2161
2162 // There's exactly one suitable operator; pick it.
2163 if (Matches.size() == 1) {
2164 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Alexis Hunt1f69a022011-05-12 22:46:29 +00002165
2166 if (Operator->isDeleted()) {
2167 if (Diagnose) {
2168 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002169 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002170 }
2171 return true;
2172 }
2173
Richard Smith921bd202012-02-26 09:11:52 +00002174 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2175 Matches[0], Diagnose) == AR_inaccessible)
2176 return true;
2177
John McCall66a87592010-08-04 00:31:26 +00002178 return false;
2179
2180 // We found multiple suitable operators; complain about the ambiguity.
2181 } else if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002182 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002183 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2184 << Name << RD;
John McCall66a87592010-08-04 00:31:26 +00002185
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002186 for (SmallVectorImpl<DeclAccessPair>::iterator
Alexis Huntf91729462011-05-12 22:46:25 +00002187 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
2188 Diag((*F)->getUnderlyingDecl()->getLocation(),
2189 diag::note_member_declared_here) << Name;
2190 }
John McCall66a87592010-08-04 00:31:26 +00002191 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002192 }
2193
2194 // We did find operator delete/operator delete[] declarations, but
2195 // none of them were suitable.
2196 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002197 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002198 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2199 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002200
Alexis Huntf91729462011-05-12 22:46:25 +00002201 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2202 F != FEnd; ++F)
2203 Diag((*F)->getUnderlyingDecl()->getLocation(),
2204 diag::note_member_declared_here) << Name;
2205 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002206 return true;
2207 }
2208
2209 // Look for a global declaration.
Richard Smith1cdec012013-09-29 04:40:38 +00002210 Operator = FindUsualDeallocationFunction(StartLoc, true, Name);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002211 return false;
2212}
2213
Sebastian Redlbd150f42008-11-21 19:14:01 +00002214/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2215/// @code ::delete ptr; @endcode
2216/// or
2217/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00002218ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00002219Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00002220 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002221 // C++ [expr.delete]p1:
2222 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00002223 // non-explicit conversion function to a pointer type. The result has type
2224 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002225 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00002226 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2227
John Wiegley01296292011-04-08 18:41:53 +00002228 ExprResult Ex = Owned(ExE);
Anders Carlssona471db02009-08-16 20:29:29 +00002229 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002230 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00002231 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00002232
John Wiegley01296292011-04-08 18:41:53 +00002233 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00002234 // Perform lvalue-to-rvalue cast, if needed.
2235 Ex = DefaultLvalueConversion(Ex.take());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00002236 if (Ex.isInvalid())
2237 return ExprError();
John McCallef429022012-03-09 04:08:29 +00002238
John Wiegley01296292011-04-08 18:41:53 +00002239 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002240
Richard Smithccc11812013-05-21 19:05:48 +00002241 class DeleteConverter : public ContextualImplicitConverter {
2242 public:
2243 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002244
Richard Smithccc11812013-05-21 19:05:48 +00002245 bool match(QualType ConvType) {
2246 // FIXME: If we have an operator T* and an operator void*, we must pick
2247 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002248 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00002249 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00002250 return true;
2251 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002252 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002253
Richard Smithccc11812013-05-21 19:05:48 +00002254 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2255 QualType T) {
2256 return S.Diag(Loc, diag::err_delete_operand) << T;
2257 }
2258
2259 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2260 QualType T) {
2261 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
2262 }
2263
2264 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2265 QualType T, QualType ConvTy) {
2266 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
2267 }
2268
2269 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2270 QualType ConvTy) {
2271 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2272 << ConvTy;
2273 }
2274
2275 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2276 QualType T) {
2277 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
2278 }
2279
2280 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2281 QualType ConvTy) {
2282 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2283 << ConvTy;
2284 }
2285
2286 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2287 QualType T, QualType ConvTy) {
2288 llvm_unreachable("conversion functions are permitted");
2289 }
2290 } Converter;
2291
2292 Ex = PerformContextualImplicitConversion(StartLoc, Ex.take(), Converter);
2293 if (Ex.isInvalid())
2294 return ExprError();
2295 Type = Ex.get()->getType();
2296 if (!Converter.match(Type))
2297 // FIXME: PerformContextualImplicitConversion should return ExprError
2298 // itself in this case.
2299 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002300
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002301 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00002302 QualType PointeeElem = Context.getBaseElementType(Pointee);
2303
2304 if (unsigned AddressSpace = Pointee.getAddressSpace())
2305 return Diag(Ex.get()->getLocStart(),
2306 diag::err_address_space_qualified_delete)
2307 << Pointee.getUnqualifiedType() << AddressSpace;
2308
2309 CXXRecordDecl *PointeeRD = 0;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00002310 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002311 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00002312 // effectively bans deletion of "void*". However, most compilers support
2313 // this, so we treat it as a warning unless we're in a SFINAE context.
2314 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00002315 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00002316 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002317 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00002318 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00002319 } else if (!Pointee->isDependentType()) {
2320 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002321 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00002322 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2323 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2324 }
2325 }
2326
Douglas Gregor98496dc2009-09-29 21:38:53 +00002327 // C++ [expr.delete]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002328 // [Note: a pointer to a const type can be the operand of a
2329 // delete-expression; it is not necessary to cast away the constness
2330 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor98496dc2009-09-29 21:38:53 +00002331 // of the delete-expression. ]
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002332
2333 if (Pointee->isArrayType() && !ArrayForm) {
2334 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00002335 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002336 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2337 ArrayForm = true;
2338 }
2339
Anders Carlssona471db02009-08-16 20:29:29 +00002340 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2341 ArrayForm ? OO_Array_Delete : OO_Delete);
2342
Eli Friedmanae4280f2011-07-26 22:25:31 +00002343 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002344 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00002345 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2346 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00002347 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002348
John McCall284c48f2011-01-27 09:37:56 +00002349 // If we're allocating an array of records, check whether the
2350 // usual operator delete[] has a size_t parameter.
2351 if (ArrayForm) {
2352 // If the user specifically asked to use the global allocator,
2353 // we'll need to do the lookup into the class.
2354 if (UseGlobal)
2355 UsualArrayDeleteWantsSize =
2356 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2357
2358 // Otherwise, the usual operator delete[] should be the
2359 // function we just found.
2360 else if (isa<CXXMethodDecl>(OperatorDelete))
2361 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2362 }
2363
Richard Smitheec915d62012-02-18 04:13:32 +00002364 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00002365 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00002366 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002367 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00002368 if (DiagnoseUseOfDecl(Dtor, StartLoc))
2369 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002370 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00002371
2372 // C++ [expr.delete]p3:
2373 // In the first alternative (delete object), if the static type of the
2374 // object to be deleted is different from its dynamic type, the static
2375 // type shall be a base class of the dynamic type of the object to be
2376 // deleted and the static type shall have a virtual destructor or the
2377 // behavior is undefined.
2378 //
2379 // Note: a final class cannot be derived from, no issue there
Eli Friedman1b71a222011-07-26 23:27:24 +00002380 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00002381 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedman1b71a222011-07-26 23:27:24 +00002382 if (dtor && !dtor->isVirtual()) {
2383 if (PointeeRD->isAbstract()) {
2384 // If the class is abstract, we warn by default, because we're
2385 // sure the code has undefined behavior.
2386 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2387 << PointeeElem;
2388 } else if (!ArrayForm) {
2389 // Otherwise, if this is not an array delete, it's a bit suspect,
2390 // but not necessarily wrong.
2391 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2392 }
2393 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00002394 }
John McCall31168b02011-06-15 23:02:42 +00002395
Anders Carlssona471db02009-08-16 20:29:29 +00002396 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002397
Richard Smith1cdec012013-09-29 04:40:38 +00002398 if (!OperatorDelete)
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002399 // Look for a global declaration.
Richard Smith1cdec012013-09-29 04:40:38 +00002400 OperatorDelete = FindUsualDeallocationFunction(
2401 StartLoc, !RequireCompleteType(StartLoc, Pointee, 0) &&
2402 (!ArrayForm || UsualArrayDeleteWantsSize ||
2403 Pointee.isDestructedType()),
2404 DeleteName);
Mike Stump11289f42009-09-09 15:08:12 +00002405
Eli Friedmanfa0df832012-02-02 03:46:19 +00002406 MarkFunctionReferenced(StartLoc, OperatorDelete);
John McCall284c48f2011-01-27 09:37:56 +00002407
Douglas Gregorfa778132011-02-01 15:50:11 +00002408 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00002409 if (PointeeRD) {
2410 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley01296292011-04-08 18:41:53 +00002411 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00002412 PDiag(diag::err_access_dtor) << PointeeElem);
2413 }
2414 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002415 }
2416
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002417 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall284c48f2011-01-27 09:37:56 +00002418 ArrayFormAsWritten,
2419 UsualArrayDeleteWantsSize,
John Wiegley01296292011-04-08 18:41:53 +00002420 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002421}
2422
Douglas Gregor633caca2009-11-23 23:44:04 +00002423/// \brief Check the use of the given variable as a C++ condition in an if,
2424/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00002425ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00002426 SourceLocation StmtLoc,
2427 bool ConvertToBoolean) {
Richard Smith27d807c2013-04-30 13:56:41 +00002428 if (ConditionVar->isInvalidDecl())
2429 return ExprError();
2430
Douglas Gregor633caca2009-11-23 23:44:04 +00002431 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002432
Douglas Gregor633caca2009-11-23 23:44:04 +00002433 // C++ [stmt.select]p2:
2434 // The declarator shall not specify a function or an array.
2435 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002436 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00002437 diag::err_invalid_use_of_function_type)
2438 << ConditionVar->getSourceRange());
2439 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002440 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00002441 diag::err_invalid_use_of_array_type)
2442 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00002443
John Wiegley01296292011-04-08 18:41:53 +00002444 ExprResult Condition =
Abramo Bagnara7945c982012-01-27 09:46:47 +00002445 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2446 SourceLocation(),
2447 ConditionVar,
John McCall113bee02012-03-10 09:33:50 +00002448 /*enclosing*/ false,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002449 ConditionVar->getLocation(),
2450 ConditionVar->getType().getNonReferenceType(),
John Wiegley01296292011-04-08 18:41:53 +00002451 VK_LValue));
Eli Friedman2dfa7932012-01-16 21:00:51 +00002452
Eli Friedmanfa0df832012-02-02 03:46:19 +00002453 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00002454
John Wiegley01296292011-04-08 18:41:53 +00002455 if (ConvertToBoolean) {
2456 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2457 if (Condition.isInvalid())
2458 return ExprError();
2459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002460
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002461 return Condition;
Douglas Gregor633caca2009-11-23 23:44:04 +00002462}
2463
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002464/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley01296292011-04-08 18:41:53 +00002465ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002466 // C++ 6.4p4:
2467 // The value of a condition that is an initialized declaration in a statement
2468 // other than a switch statement is the value of the declared variable
2469 // implicitly converted to type bool. If that conversion is ill-formed, the
2470 // program is ill-formed.
2471 // The value of a condition that is an expression is the value of the
2472 // expression, implicitly converted to bool.
2473 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00002474 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002475}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002476
2477/// Helper function to determine whether this is the (deprecated) C++
2478/// conversion from a string literal to a pointer to non-const char or
2479/// non-const wchar_t (for narrow and wide string literals,
2480/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00002481bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002482Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2483 // Look inside the implicit cast, if it exists.
2484 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2485 From = Cast->getSubExpr();
2486
2487 // A string literal (2.13.4) that is not a wide string literal can
2488 // be converted to an rvalue of type "pointer to char"; a wide
2489 // string literal can be converted to an rvalue of type "pointer
2490 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00002491 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002492 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00002493 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00002494 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002495 // This conversion is considered only when there is an
2496 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00002497 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2498 switch (StrLit->getKind()) {
2499 case StringLiteral::UTF8:
2500 case StringLiteral::UTF16:
2501 case StringLiteral::UTF32:
2502 // We don't allow UTF literals to be implicitly converted
2503 break;
2504 case StringLiteral::Ascii:
2505 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2506 ToPointeeType->getKind() == BuiltinType::Char_S);
2507 case StringLiteral::Wide:
2508 return ToPointeeType->isWideCharType();
2509 }
2510 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002511 }
2512
2513 return false;
2514}
Douglas Gregor39c16d42008-10-24 04:54:22 +00002515
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002516static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00002517 SourceLocation CastLoc,
2518 QualType Ty,
2519 CastKind Kind,
2520 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00002521 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002522 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00002523 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00002524 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002525 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00002526 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00002527 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00002528 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002529
Richard Smith72d74052013-07-20 19:41:36 +00002530 if (S.RequireNonAbstractType(CastLoc, Ty,
2531 diag::err_allocation_of_abstract_type))
2532 return ExprError();
2533
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002534 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00002535 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002536
John McCall5dadb652012-04-07 03:04:20 +00002537 S.CheckConstructorAccess(CastLoc, Constructor,
2538 InitializedEntity::InitializeTemporary(Ty),
2539 Constructor->getAccess());
Richard Smithd59b8322012-12-19 01:39:02 +00002540
Douglas Gregorc7a31072011-10-10 22:41:00 +00002541 ExprResult Result
2542 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
Richard Smithd59b8322012-12-19 01:39:02 +00002543 ConstructorArgs, HadMultipleCandidates,
2544 /*ListInit*/ false, /*ZeroInit*/ false,
Douglas Gregorc7a31072011-10-10 22:41:00 +00002545 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00002546 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00002547 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002548
Douglas Gregora4253922010-04-16 22:17:36 +00002549 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2550 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002551
John McCalle3027922010-08-25 11:45:40 +00002552 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00002553 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002554
Douglas Gregora4253922010-04-16 22:17:36 +00002555 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00002556 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2557 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002558 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00002559 if (Result.isInvalid())
2560 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00002561 // Record usage of conversion in an implicit cast.
2562 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2563 Result.get()->getType(),
2564 CK_UserDefinedConversion,
2565 Result.get(), 0,
2566 Result.get()->getValueKind()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002567
John McCall30909032011-09-21 08:36:56 +00002568 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2569
Douglas Gregor668443e2011-01-20 00:18:04 +00002570 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00002571 }
2572 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002573}
Douglas Gregora4253922010-04-16 22:17:36 +00002574
Douglas Gregor5fb53972009-01-14 15:45:31 +00002575/// PerformImplicitConversion - Perform an implicit conversion of the
2576/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00002577/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002578/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002579/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00002580ExprResult
2581Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002582 const ImplicitConversionSequence &ICS,
John McCall31168b02011-06-15 23:02:42 +00002583 AssignmentAction Action,
2584 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00002585 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00002586 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00002587 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2588 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00002589 if (Res.isInvalid())
2590 return ExprError();
2591 From = Res.take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002592 break;
John Wiegley01296292011-04-08 18:41:53 +00002593 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002594
Anders Carlsson110b07b2009-09-15 06:28:28 +00002595 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002596
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00002597 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00002598 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00002599 QualType BeforeToType;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002600 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlsson110b07b2009-09-15 06:28:28 +00002601 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00002602 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002603
Anders Carlsson110b07b2009-09-15 06:28:28 +00002604 // If the user-defined conversion is specified by a conversion function,
2605 // the initial standard conversion sequence converts the source type to
2606 // the implicit object parameter of the conversion function.
2607 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00002608 } else {
2609 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00002610 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002611 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00002612 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002613 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian55824512009-11-06 00:23:08 +00002614 // initial standard conversion sequence converts the source type to the
2615 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00002616 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2617 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002618 }
Richard Smith72d74052013-07-20 19:41:36 +00002619 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00002620 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00002621 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00002622 PerformImplicitConversion(From, BeforeToType,
2623 ICS.UserDefined.Before, AA_Converting,
2624 CCK);
John Wiegley01296292011-04-08 18:41:53 +00002625 if (Res.isInvalid())
2626 return ExprError();
2627 From = Res.take();
Fariborz Jahanian55824512009-11-06 00:23:08 +00002628 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002629
2630 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00002631 = BuildCXXCastArgument(*this,
2632 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00002633 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002634 CastKind, cast<CXXMethodDecl>(FD),
2635 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002636 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00002637 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00002638
2639 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002640 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002641
John Wiegley01296292011-04-08 18:41:53 +00002642 From = CastArg.take();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002643
Richard Smith507840d2011-11-29 22:48:16 +00002644 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2645 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00002646 }
John McCall0d1da222010-01-12 00:44:57 +00002647
2648 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00002649 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00002650 PDiag(diag::err_typecheck_ambiguous_condition)
2651 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00002652 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002653
Douglas Gregor39c16d42008-10-24 04:54:22 +00002654 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00002655 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002656
2657 case ImplicitConversionSequence::BadConversion:
John Wiegley01296292011-04-08 18:41:53 +00002658 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002659 }
2660
2661 // Everything went well.
John Wiegley01296292011-04-08 18:41:53 +00002662 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002663}
2664
Richard Smith507840d2011-11-29 22:48:16 +00002665/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00002666/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00002667/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00002668/// expression. Flavor is the context in which we're performing this
2669/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00002670ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00002671Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002672 const StandardConversionSequence& SCS,
John McCall31168b02011-06-15 23:02:42 +00002673 AssignmentAction Action,
2674 CheckedConversionKind CCK) {
2675 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2676
Mike Stump87c57ac2009-05-16 07:39:55 +00002677 // Overall FIXME: we are recomputing too many types here and doing far too
2678 // much extra work. What this means is that we need to keep track of more
2679 // information that is computed when we try the implicit conversion initially,
2680 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002681 QualType FromType = From->getType();
John McCall31168b02011-06-15 23:02:42 +00002682
Douglas Gregor2fe98832008-11-03 19:09:14 +00002683 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00002684 // FIXME: When can ToType be a reference type?
2685 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002686 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00002687 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002688 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002689 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002690 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00002691 return ExprError();
2692 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2693 ToType, SCS.CopyConstructor,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002694 ConstructorArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002695 /*HadMultipleCandidates*/ false,
Richard Smithd59b8322012-12-19 01:39:02 +00002696 /*ListInit*/ false, /*ZeroInit*/ false,
John Wiegley01296292011-04-08 18:41:53 +00002697 CXXConstructExpr::CK_Complete,
2698 SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002699 }
John Wiegley01296292011-04-08 18:41:53 +00002700 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2701 ToType, SCS.CopyConstructor,
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002702 From, /*HadMultipleCandidates*/ false,
Richard Smithd59b8322012-12-19 01:39:02 +00002703 /*ListInit*/ false, /*ZeroInit*/ false,
John Wiegley01296292011-04-08 18:41:53 +00002704 CXXConstructExpr::CK_Complete,
2705 SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00002706 }
2707
Douglas Gregor980fb162010-04-29 18:24:40 +00002708 // Resolve overloaded function references.
2709 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2710 DeclAccessPair Found;
2711 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2712 true, Found);
2713 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00002714 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00002715
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002716 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00002717 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002718
Douglas Gregor980fb162010-04-29 18:24:40 +00002719 From = FixOverloadedFunctionReference(From, Found, Fn);
2720 FromType = From->getType();
2721 }
2722
Richard Smitha23ab512013-05-23 00:30:41 +00002723 // If we're converting to an atomic type, first convert to the corresponding
2724 // non-atomic type.
2725 QualType ToAtomicType;
2726 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
2727 ToAtomicType = ToType;
2728 ToType = ToAtomic->getValueType();
2729 }
2730
Richard Smith507840d2011-11-29 22:48:16 +00002731 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002732 switch (SCS.First) {
2733 case ICK_Identity:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002734 // Nothing to do.
2735 break;
2736
Eli Friedman946b7b52012-01-24 22:51:26 +00002737 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00002738 assert(From->getObjectKind() != OK_ObjCProperty);
John McCall34376a62010-12-04 03:47:34 +00002739 FromType = FromType.getUnqualifiedType();
Eli Friedman946b7b52012-01-24 22:51:26 +00002740 ExprResult FromRes = DefaultLvalueConversion(From);
2741 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2742 From = FromRes.take();
John McCall34376a62010-12-04 03:47:34 +00002743 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00002744 }
John McCall34376a62010-12-04 03:47:34 +00002745
Douglas Gregor39c16d42008-10-24 04:54:22 +00002746 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00002747 FromType = Context.getArrayDecayedType(FromType);
Richard Smith507840d2011-11-29 22:48:16 +00002748 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2749 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002750 break;
2751
2752 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002753 FromType = Context.getPointerType(FromType);
Richard Smith507840d2011-11-29 22:48:16 +00002754 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2755 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002756 break;
2757
2758 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002759 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002760 }
2761
Richard Smith507840d2011-11-29 22:48:16 +00002762 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00002763 switch (SCS.Second) {
2764 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00002765 // If both sides are functions (or pointers/references to them), there could
2766 // be incompatible exception declarations.
2767 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002768 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002769 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002770 break;
2771
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002772 case ICK_NoReturn_Adjustment:
2773 // If both sides are functions (or pointers/references to them), there could
2774 // be incompatible exception declarations.
2775 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002776 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002777
Richard Smith507840d2011-11-29 22:48:16 +00002778 From = ImpCastExprToType(From, ToType, CK_NoOp,
2779 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002780 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002781
Douglas Gregor39c16d42008-10-24 04:54:22 +00002782 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002783 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00002784 if (ToType->isBooleanType()) {
2785 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
2786 SCS.Second == ICK_Integral_Promotion &&
2787 "only enums with fixed underlying type can promote to bool");
2788 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
2789 VK_RValue, /*BasePath=*/0, CCK).take();
2790 } else {
2791 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2792 VK_RValue, /*BasePath=*/0, CCK).take();
2793 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00002794 break;
2795
2796 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002797 case ICK_Floating_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002798 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2799 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002800 break;
2801
2802 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00002803 case ICK_Complex_Conversion: {
2804 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2805 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2806 CastKind CK;
2807 if (FromEl->isRealFloatingType()) {
2808 if (ToEl->isRealFloatingType())
2809 CK = CK_FloatingComplexCast;
2810 else
2811 CK = CK_FloatingComplexToIntegralComplex;
2812 } else if (ToEl->isRealFloatingType()) {
2813 CK = CK_IntegralComplexToFloatingComplex;
2814 } else {
2815 CK = CK_IntegralComplexCast;
2816 }
Richard Smith507840d2011-11-29 22:48:16 +00002817 From = ImpCastExprToType(From, ToType, CK,
2818 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002819 break;
John McCall8cb679e2010-11-15 09:13:47 +00002820 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00002821
Douglas Gregor39c16d42008-10-24 04:54:22 +00002822 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00002823 if (ToType->isRealFloatingType())
Richard Smith507840d2011-11-29 22:48:16 +00002824 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2825 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002826 else
Richard Smith507840d2011-11-29 22:48:16 +00002827 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2828 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002829 break;
2830
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002831 case ICK_Compatible_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002832 From = ImpCastExprToType(From, ToType, CK_NoOp,
2833 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002834 break;
2835
John McCall31168b02011-06-15 23:02:42 +00002836 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002837 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002838 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002839 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00002840 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002841 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002842 diag::ext_typecheck_convert_incompatible_pointer)
2843 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00002844 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002845 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002846 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002847 diag::ext_typecheck_convert_incompatible_pointer)
2848 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00002849 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00002850
Douglas Gregor33823722011-06-11 01:09:30 +00002851 if (From->getType()->isObjCObjectPointerType() &&
2852 ToType->isObjCObjectPointerType())
2853 EmitRelatedResultTypeNote(From);
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002854 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00002855 else if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002856 !CheckObjCARCUnavailableWeakConversion(ToType,
2857 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00002858 if (Action == AA_Initializing)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002859 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00002860 diag::err_arc_weak_unavailable_assign);
2861 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002862 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00002863 diag::err_arc_convesion_of_weak_unavailable)
2864 << (Action == AA_Casting) << From->getType() << ToType
2865 << From->getSourceRange();
2866 }
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002867
John McCall8cb679e2010-11-15 09:13:47 +00002868 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002869 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002870 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002871 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00002872
2873 // Make sure we extend blocks if necessary.
2874 // FIXME: doing this here is really ugly.
2875 if (Kind == CK_BlockPointerToObjCPointerCast) {
2876 ExprResult E = From;
2877 (void) PrepareCastToObjCObjectPointer(E);
2878 From = E.take();
2879 }
Fariborz Jahanian374089e2013-07-31 17:12:26 +00002880 if (getLangOpts().ObjCAutoRefCount)
2881 CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00002882 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2883 .take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002884 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002885 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002886
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002887 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00002888 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002889 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002890 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002891 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002892 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002893 return ExprError();
Richard Smith507840d2011-11-29 22:48:16 +00002894 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2895 .take();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002896 break;
2897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002898
Abramo Bagnara7ccce982011-04-07 09:26:19 +00002899 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002900 // Perform half-to-boolean conversion via float.
2901 if (From->getType()->isHalfType()) {
2902 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2903 FromType = Context.FloatTy;
2904 }
2905
Richard Smith507840d2011-11-29 22:48:16 +00002906 From = ImpCastExprToType(From, Context.BoolTy,
2907 ScalarTypeToBooleanCastKind(FromType),
2908 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002909 break;
2910
Douglas Gregor88d292c2010-05-13 16:44:06 +00002911 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00002912 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002913 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002914 ToType.getNonReferenceType(),
2915 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002916 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00002917 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00002918 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002919 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00002920
Richard Smith507840d2011-11-29 22:48:16 +00002921 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2922 CK_DerivedToBase, From->getValueKind(),
2923 &BasePath, CCK).take();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002924 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00002925 }
2926
Douglas Gregor46188682010-05-18 22:42:18 +00002927 case ICK_Vector_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002928 From = ImpCastExprToType(From, ToType, CK_BitCast,
2929 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002930 break;
2931
2932 case ICK_Vector_Splat:
Richard Smith507840d2011-11-29 22:48:16 +00002933 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2934 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002935 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002936
Douglas Gregor46188682010-05-18 22:42:18 +00002937 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00002938 // Case 1. x -> _Complex y
2939 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2940 QualType ElType = ToComplex->getElementType();
2941 bool isFloatingComplex = ElType->isRealFloatingType();
2942
2943 // x -> y
2944 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2945 // do nothing
2946 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00002947 From = ImpCastExprToType(From, ElType,
2948 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCall8cb679e2010-11-15 09:13:47 +00002949 } else {
2950 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00002951 From = ImpCastExprToType(From, ElType,
2952 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCall8cb679e2010-11-15 09:13:47 +00002953 }
2954 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00002955 From = ImpCastExprToType(From, ToType,
2956 isFloatingComplex ? CK_FloatingRealToComplex
2957 : CK_IntegralRealToComplex).take();
John McCall8cb679e2010-11-15 09:13:47 +00002958
2959 // Case 2. _Complex x -> y
2960 } else {
2961 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2962 assert(FromComplex);
2963
2964 QualType ElType = FromComplex->getElementType();
2965 bool isFloatingComplex = ElType->isRealFloatingType();
2966
2967 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00002968 From = ImpCastExprToType(From, ElType,
2969 isFloatingComplex ? CK_FloatingComplexToReal
2970 : CK_IntegralComplexToReal,
2971 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002972
2973 // x -> y
2974 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2975 // do nothing
2976 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00002977 From = ImpCastExprToType(From, ToType,
2978 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2979 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002980 } else {
2981 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00002982 From = ImpCastExprToType(From, ToType,
2983 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2984 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002985 }
2986 }
Douglas Gregor46188682010-05-18 22:42:18 +00002987 break;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002988
2989 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00002990 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2991 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall31168b02011-06-15 23:02:42 +00002992 break;
2993 }
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002994
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002995 case ICK_TransparentUnionConversion: {
John Wiegley01296292011-04-08 18:41:53 +00002996 ExprResult FromRes = Owned(From);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002997 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002998 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2999 if (FromRes.isInvalid())
3000 return ExprError();
3001 From = FromRes.take();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003002 assert ((ConvTy == Sema::Compatible) &&
3003 "Improper transparent union conversion");
3004 (void)ConvTy;
3005 break;
3006 }
3007
Guy Benyei259f9f42013-02-07 16:05:33 +00003008 case ICK_Zero_Event_Conversion:
3009 From = ImpCastExprToType(From, ToType,
3010 CK_ZeroToOCLEvent,
3011 From->getValueKind()).take();
3012 break;
3013
Douglas Gregor46188682010-05-18 22:42:18 +00003014 case ICK_Lvalue_To_Rvalue:
3015 case ICK_Array_To_Pointer:
3016 case ICK_Function_To_Pointer:
3017 case ICK_Qualification:
3018 case ICK_Num_Conversion_Kinds:
David Blaikie83d382b2011-09-23 05:06:16 +00003019 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003020 }
3021
3022 switch (SCS.Third) {
3023 case ICK_Identity:
3024 // Nothing to do.
3025 break;
3026
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003027 case ICK_Qualification: {
3028 // The qualification keeps the category of the inner expression, unless the
3029 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00003030 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003031 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00003032 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
3033 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregore489a7d2010-02-28 18:30:25 +00003034
Douglas Gregore981bb02011-03-14 16:13:32 +00003035 if (SCS.DeprecatedStringLiteralToCharPtr &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00003036 !getLangOpts().WritableStrings)
Douglas Gregore489a7d2010-02-28 18:30:25 +00003037 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
3038 << ToType.getNonReferenceType();
3039
Douglas Gregor39c16d42008-10-24 04:54:22 +00003040 break;
Richard Smitha23ab512013-05-23 00:30:41 +00003041 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003042
Douglas Gregor39c16d42008-10-24 04:54:22 +00003043 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003044 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003045 }
3046
Douglas Gregor298f43d2012-04-12 20:42:30 +00003047 // If this conversion sequence involved a scalar -> atomic conversion, perform
3048 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00003049 if (!ToAtomicType.isNull()) {
3050 assert(Context.hasSameType(
3051 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3052 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
3053 VK_RValue, 0, CCK).take();
3054 }
3055
John Wiegley01296292011-04-08 18:41:53 +00003056 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00003057}
3058
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003059ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00003060 SourceLocation KWLoc,
3061 ParsedType Ty,
3062 SourceLocation RParen) {
3063 TypeSourceInfo *TSInfo;
3064 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump11289f42009-09-09 15:08:12 +00003065
Douglas Gregor54e5b132010-09-09 16:14:44 +00003066 if (!TSInfo)
3067 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003068 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor54e5b132010-09-09 16:14:44 +00003069}
3070
Chandler Carruth8e172c62011-05-01 06:51:22 +00003071/// \brief Check the completeness of a type in a unary type trait.
3072///
3073/// If the particular type trait requires a complete type, tries to complete
3074/// it. If completing the type fails, a diagnostic is emitted and false
3075/// returned. If completing the type succeeds or no completion was required,
3076/// returns true.
3077static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
3078 UnaryTypeTrait UTT,
3079 SourceLocation Loc,
3080 QualType ArgTy) {
3081 // C++0x [meta.unary.prop]p3:
3082 // For all of the class templates X declared in this Clause, instantiating
3083 // that template with a template argument that is a class template
3084 // specialization may result in the implicit instantiation of the template
3085 // argument if and only if the semantics of X require that the argument
3086 // must be a complete type.
3087 // We apply this rule to all the type trait expressions used to implement
3088 // these class templates. We also try to follow any GCC documented behavior
3089 // in these expressions to ensure portability of standard libraries.
3090 switch (UTT) {
Chandler Carruth8e172c62011-05-01 06:51:22 +00003091 // is_complete_type somewhat obviously cannot require a complete type.
3092 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003093 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003094
3095 // These traits are modeled on the type predicates in C++0x
3096 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3097 // requiring a complete type, as whether or not they return true cannot be
3098 // impacted by the completeness of the type.
3099 case UTT_IsVoid:
3100 case UTT_IsIntegral:
3101 case UTT_IsFloatingPoint:
3102 case UTT_IsArray:
3103 case UTT_IsPointer:
3104 case UTT_IsLvalueReference:
3105 case UTT_IsRvalueReference:
3106 case UTT_IsMemberFunctionPointer:
3107 case UTT_IsMemberObjectPointer:
3108 case UTT_IsEnum:
3109 case UTT_IsUnion:
3110 case UTT_IsClass:
3111 case UTT_IsFunction:
3112 case UTT_IsReference:
3113 case UTT_IsArithmetic:
3114 case UTT_IsFundamental:
3115 case UTT_IsObject:
3116 case UTT_IsScalar:
3117 case UTT_IsCompound:
3118 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003119 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003120
3121 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
3122 // which requires some of its traits to have the complete type. However,
3123 // the completeness of the type cannot impact these traits' semantics, and
3124 // so they don't require it. This matches the comments on these traits in
3125 // Table 49.
3126 case UTT_IsConst:
3127 case UTT_IsVolatile:
3128 case UTT_IsSigned:
3129 case UTT_IsUnsigned:
3130 return true;
3131
3132 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003133 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00003134 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00003135 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00003136 case UTT_IsStandardLayout:
3137 case UTT_IsPOD:
3138 case UTT_IsLiteral:
3139 case UTT_IsEmpty:
3140 case UTT_IsPolymorphic:
3141 case UTT_IsAbstract:
John McCallbf4a7d72012-09-25 07:32:49 +00003142 case UTT_IsInterfaceClass:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003143 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003144
Douglas Gregordca70af2011-12-03 18:14:24 +00003145 // These traits require a complete type.
3146 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00003147 case UTT_IsSealed:
Douglas Gregordca70af2011-12-03 18:14:24 +00003148
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003149 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00003150 // [meta.unary.prop] despite not being named the same. They are specified
3151 // by both GCC and the Embarcadero C++ compiler, and require the complete
3152 // type due to the overarching C++0x type predicates being implemented
3153 // requiring the complete type.
3154 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00003155 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00003156 case UTT_HasNothrowConstructor:
3157 case UTT_HasNothrowCopy:
3158 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00003159 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00003160 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00003161 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00003162 case UTT_HasTrivialCopy:
3163 case UTT_HasTrivialDestructor:
3164 case UTT_HasVirtualDestructor:
3165 // Arrays of unknown bound are expressly allowed.
3166 QualType ElTy = ArgTy;
3167 if (ArgTy->isIncompleteArrayType())
3168 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
3169
3170 // The void type is expressly allowed.
3171 if (ElTy->isVoidType())
3172 return true;
3173
3174 return !S.RequireCompleteType(
3175 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00003176 }
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +00003177 llvm_unreachable("Type trait not handled by switch");
Chandler Carruth8e172c62011-05-01 06:51:22 +00003178}
3179
Joao Matosc9523d42013-03-27 01:34:16 +00003180static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
3181 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
3182 bool (CXXRecordDecl::*HasTrivial)() const,
3183 bool (CXXRecordDecl::*HasNonTrivial)() const,
3184 bool (CXXMethodDecl::*IsDesiredOp)() const)
3185{
3186 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3187 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
3188 return true;
3189
3190 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
3191 DeclarationNameInfo NameInfo(Name, KeyLoc);
3192 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
3193 if (Self.LookupQualifiedName(Res, RD)) {
3194 bool FoundOperator = false;
3195 Res.suppressDiagnostics();
3196 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3197 Op != OpEnd; ++Op) {
3198 if (isa<FunctionTemplateDecl>(*Op))
3199 continue;
3200
3201 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3202 if((Operator->*IsDesiredOp)()) {
3203 FoundOperator = true;
3204 const FunctionProtoType *CPT =
3205 Operator->getType()->getAs<FunctionProtoType>();
3206 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3207 if (!CPT || !CPT->isNothrow(Self.Context))
3208 return false;
3209 }
3210 }
3211 return FoundOperator;
3212 }
3213 return false;
3214}
3215
Chandler Carruth8e172c62011-05-01 06:51:22 +00003216static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
3217 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003218 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00003219
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003220 ASTContext &C = Self.Context;
3221 switch(UTT) {
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003222 // Type trait expressions corresponding to the primary type category
3223 // predicates in C++0x [meta.unary.cat].
3224 case UTT_IsVoid:
3225 return T->isVoidType();
3226 case UTT_IsIntegral:
3227 return T->isIntegralType(C);
3228 case UTT_IsFloatingPoint:
3229 return T->isFloatingType();
3230 case UTT_IsArray:
3231 return T->isArrayType();
3232 case UTT_IsPointer:
3233 return T->isPointerType();
3234 case UTT_IsLvalueReference:
3235 return T->isLValueReferenceType();
3236 case UTT_IsRvalueReference:
3237 return T->isRValueReferenceType();
3238 case UTT_IsMemberFunctionPointer:
3239 return T->isMemberFunctionPointerType();
3240 case UTT_IsMemberObjectPointer:
3241 return T->isMemberDataPointerType();
3242 case UTT_IsEnum:
3243 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00003244 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00003245 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003246 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00003247 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003248 case UTT_IsFunction:
3249 return T->isFunctionType();
3250
3251 // Type trait expressions which correspond to the convenient composition
3252 // predicates in C++0x [meta.unary.comp].
3253 case UTT_IsReference:
3254 return T->isReferenceType();
3255 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00003256 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003257 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00003258 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003259 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00003260 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003261 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00003262 // Note: semantic analysis depends on Objective-C lifetime types to be
3263 // considered scalar types. However, such types do not actually behave
3264 // like scalar types at run time (since they may require retain/release
3265 // operations), so we report them as non-scalar.
3266 if (T->isObjCLifetimeType()) {
3267 switch (T.getObjCLifetime()) {
3268 case Qualifiers::OCL_None:
3269 case Qualifiers::OCL_ExplicitNone:
3270 return true;
3271
3272 case Qualifiers::OCL_Strong:
3273 case Qualifiers::OCL_Weak:
3274 case Qualifiers::OCL_Autoreleasing:
3275 return false;
3276 }
3277 }
3278
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00003279 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003280 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00003281 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003282 case UTT_IsMemberPointer:
3283 return T->isMemberPointerType();
3284
3285 // Type trait expressions which correspond to the type property predicates
3286 // in C++0x [meta.unary.prop].
3287 case UTT_IsConst:
3288 return T.isConstQualified();
3289 case UTT_IsVolatile:
3290 return T.isVolatileQualified();
3291 case UTT_IsTrivial:
John McCall31168b02011-06-15 23:02:42 +00003292 return T.isTrivialType(Self.Context);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00003293 case UTT_IsTriviallyCopyable:
John McCall31168b02011-06-15 23:02:42 +00003294 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003295 case UTT_IsStandardLayout:
3296 return T->isStandardLayoutType();
3297 case UTT_IsPOD:
Benjamin Kramera3c0dad2012-04-28 10:00:33 +00003298 return T.isPODType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003299 case UTT_IsLiteral:
Richard Smithd9f663b2013-04-22 15:31:51 +00003300 return T->isLiteralType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003301 case UTT_IsEmpty:
3302 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3303 return !RD->isUnion() && RD->isEmpty();
3304 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003305 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00003306 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3307 return RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003308 return false;
3309 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00003310 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3311 return RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003312 return false;
John McCallbf4a7d72012-09-25 07:32:49 +00003313 case UTT_IsInterfaceClass:
3314 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3315 return RD->isInterface();
3316 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00003317 case UTT_IsFinal:
3318 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3319 return RD->hasAttr<FinalAttr>();
3320 return false;
David Majnemera5433082013-10-18 00:33:31 +00003321 case UTT_IsSealed:
3322 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3323 if (FinalAttr *FA = RD->getAttr<FinalAttr>())
3324 return FA->isSpelledAsSealed();
3325 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00003326 case UTT_IsSigned:
3327 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00003328 case UTT_IsUnsigned:
3329 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003330
3331 // Type trait expressions which query classes regarding their construction,
3332 // destruction, and copying. Rather than being based directly on the
3333 // related type predicates in the standard, they are specified by both
3334 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3335 // specifications.
3336 //
3337 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3338 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00003339 //
3340 // Note that these builtins do not behave as documented in g++: if a class
3341 // has both a trivial and a non-trivial special member of a particular kind,
3342 // they return false! For now, we emulate this behavior.
3343 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
3344 // does not correctly compute triviality in the presence of multiple special
3345 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00003346 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003347 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3348 // If __is_pod (type) is true then the trait is true, else if type is
3349 // a cv class or union type (or array thereof) with a trivial default
3350 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00003351 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003352 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00003353 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3354 return RD->hasTrivialDefaultConstructor() &&
3355 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003356 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00003357 case UTT_HasTrivialMoveConstructor:
3358 // This trait is implemented by MSVC 2012 and needed to parse the
3359 // standard library headers. Specifically this is used as the logic
3360 // behind std::is_trivially_move_constructible (20.9.4.3).
3361 if (T.isPODType(Self.Context))
3362 return true;
3363 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3364 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
3365 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003366 case UTT_HasTrivialCopy:
3367 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3368 // If __is_pod (type) is true or type is a reference type then
3369 // the trait is true, else if type is a cv class or union type
3370 // with a trivial copy constructor ([class.copy]) then the trait
3371 // is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00003372 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003373 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00003374 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3375 return RD->hasTrivialCopyConstructor() &&
3376 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003377 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00003378 case UTT_HasTrivialMoveAssign:
3379 // This trait is implemented by MSVC 2012 and needed to parse the
3380 // standard library headers. Specifically it is used as the logic
3381 // behind std::is_trivially_move_assignable (20.9.4.3)
3382 if (T.isPODType(Self.Context))
3383 return true;
3384 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3385 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
3386 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003387 case UTT_HasTrivialAssign:
3388 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3389 // If type is const qualified or is a reference type then the
3390 // trait is false. Otherwise if __is_pod (type) is true then the
3391 // trait is true, else if type is a cv class or union type with
3392 // a trivial copy assignment ([class.copy]) then the trait is
3393 // true, else it is false.
3394 // Note: the const and reference restrictions are interesting,
3395 // given that const and reference members don't prevent a class
3396 // from having a trivial copy assignment operator (but do cause
3397 // errors if the copy assignment operator is actually used, q.v.
3398 // [class.copy]p12).
3399
Richard Smith92f241f2012-12-08 02:53:02 +00003400 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003401 return false;
John McCall31168b02011-06-15 23:02:42 +00003402 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003403 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00003404 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3405 return RD->hasTrivialCopyAssignment() &&
3406 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003407 return false;
3408 case UTT_HasTrivialDestructor:
3409 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3410 // If __is_pod (type) is true or type is a reference type
3411 // then the trait is true, else if type is a cv class or union
3412 // type (or array thereof) with a trivial destructor
3413 // ([class.dtor]) then the trait is true, else it is
3414 // false.
John McCall31168b02011-06-15 23:02:42 +00003415 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003416 return true;
John McCall31168b02011-06-15 23:02:42 +00003417
3418 // Objective-C++ ARC: autorelease types don't require destruction.
3419 if (T->isObjCLifetimeType() &&
3420 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3421 return true;
3422
Richard Smith92f241f2012-12-08 02:53:02 +00003423 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3424 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003425 return false;
3426 // TODO: Propagate nothrowness for implicitly declared special members.
3427 case UTT_HasNothrowAssign:
3428 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3429 // If type is const qualified or is a reference type then the
3430 // trait is false. Otherwise if __has_trivial_assign (type)
3431 // is true then the trait is true, else if type is a cv class
3432 // or union type with copy assignment operators that are known
3433 // not to throw an exception then the trait is true, else it is
3434 // false.
3435 if (C.getBaseElementType(T).isConstQualified())
3436 return false;
3437 if (T->isReferenceType())
3438 return false;
John McCall31168b02011-06-15 23:02:42 +00003439 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00003440 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003441
Joao Matosc9523d42013-03-27 01:34:16 +00003442 if (const RecordType *RT = T->getAs<RecordType>())
3443 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3444 &CXXRecordDecl::hasTrivialCopyAssignment,
3445 &CXXRecordDecl::hasNonTrivialCopyAssignment,
3446 &CXXMethodDecl::isCopyAssignmentOperator);
3447 return false;
3448 case UTT_HasNothrowMoveAssign:
3449 // This trait is implemented by MSVC 2012 and needed to parse the
3450 // standard library headers. Specifically this is used as the logic
3451 // behind std::is_nothrow_move_assignable (20.9.4.3).
3452 if (T.isPODType(Self.Context))
3453 return true;
3454
3455 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
3456 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
3457 &CXXRecordDecl::hasTrivialMoveAssignment,
3458 &CXXRecordDecl::hasNonTrivialMoveAssignment,
3459 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003460 return false;
3461 case UTT_HasNothrowCopy:
3462 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3463 // If __has_trivial_copy (type) is true then the trait is true, else
3464 // if type is a cv class or union type with copy constructors that are
3465 // known not to throw an exception then the trait is true, else it is
3466 // false.
John McCall31168b02011-06-15 23:02:42 +00003467 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003468 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00003469 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
3470 if (RD->hasTrivialCopyConstructor() &&
3471 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003472 return true;
3473
3474 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003475 unsigned FoundTQs;
David Blaikieff7d47a2012-12-19 00:45:41 +00003476 DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3477 for (DeclContext::lookup_const_iterator Con = R.begin(),
3478 ConEnd = R.end(); Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00003479 // A template constructor is never a copy constructor.
3480 // FIXME: However, it may actually be selected at the actual overload
3481 // resolution point.
3482 if (isa<FunctionTemplateDecl>(*Con))
3483 continue;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003484 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3485 if (Constructor->isCopyConstructor(FoundTQs)) {
3486 FoundConstructor = true;
3487 const FunctionProtoType *CPT
3488 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00003489 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3490 if (!CPT)
3491 return false;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003492 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00003493 // For now, we'll be conservative and assume that they can throw.
Richard Smith938f40b2011-06-11 17:19:42 +00003494 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3495 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003496 }
3497 }
3498
Richard Smith938f40b2011-06-11 17:19:42 +00003499 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003500 }
3501 return false;
3502 case UTT_HasNothrowConstructor:
3503 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3504 // If __has_trivial_constructor (type) is true then the trait is
3505 // true, else if type is a cv class or union type (or array
3506 // thereof) with a default constructor that is known not to
3507 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00003508 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003509 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00003510 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
3511 if (RD->hasTrivialDefaultConstructor() &&
3512 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003513 return true;
3514
David Blaikieff7d47a2012-12-19 00:45:41 +00003515 DeclContext::lookup_const_result R = Self.LookupConstructors(RD);
3516 for (DeclContext::lookup_const_iterator Con = R.begin(),
3517 ConEnd = R.end(); Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00003518 // FIXME: In C++0x, a constructor template can be a default constructor.
3519 if (isa<FunctionTemplateDecl>(*Con))
3520 continue;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003521 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3522 if (Constructor->isDefaultConstructor()) {
3523 const FunctionProtoType *CPT
3524 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00003525 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3526 if (!CPT)
3527 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003528 // TODO: check whether evaluating default arguments can throw.
3529 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl31ad7542011-03-13 17:09:40 +00003530 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003531 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003532 }
3533 }
3534 return false;
3535 case UTT_HasVirtualDestructor:
3536 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3537 // If type is a class type with a virtual destructor ([class.dtor])
3538 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00003539 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00003540 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003541 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003542 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003543
3544 // These type trait expressions are modeled on the specifications for the
3545 // Embarcadero C++0x type trait functions:
3546 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3547 case UTT_IsCompleteType:
3548 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3549 // Returns True if and only if T is a complete type at the point of the
3550 // function call.
3551 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003552 }
Chandler Carruthb42fb192011-05-01 07:44:17 +00003553 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003554}
3555
3556ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00003557 SourceLocation KWLoc,
3558 TypeSourceInfo *TSInfo,
3559 SourceLocation RParen) {
3560 QualType T = TSInfo->getType();
Chandler Carruthb0776202011-04-30 10:07:32 +00003561 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3562 return ExprError();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003563
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003564 bool Value = false;
3565 if (!T->isDependentType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00003566 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003567
3568 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson1f9648d2009-07-07 19:06:02 +00003569 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003570}
Sebastian Redl5822f082009-02-07 20:10:22 +00003571
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003572ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3573 SourceLocation KWLoc,
3574 ParsedType LhsTy,
3575 ParsedType RhsTy,
3576 SourceLocation RParen) {
3577 TypeSourceInfo *LhsTSInfo;
3578 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3579 if (!LhsTSInfo)
3580 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3581
3582 TypeSourceInfo *RhsTSInfo;
3583 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3584 if (!RhsTSInfo)
3585 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3586
3587 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3588}
3589
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00003590/// \brief Determine whether T has a non-trivial Objective-C lifetime in
3591/// ARC mode.
3592static bool hasNontrivialObjCLifetime(QualType T) {
3593 switch (T.getObjCLifetime()) {
3594 case Qualifiers::OCL_ExplicitNone:
3595 return false;
3596
3597 case Qualifiers::OCL_Strong:
3598 case Qualifiers::OCL_Weak:
3599 case Qualifiers::OCL_Autoreleasing:
3600 return true;
3601
3602 case Qualifiers::OCL_None:
3603 return T->isObjCLifetimeType();
3604 }
3605
3606 llvm_unreachable("Unknown ObjC lifetime qualifier");
3607}
3608
Douglas Gregor29c42f22012-02-24 07:38:34 +00003609static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3610 ArrayRef<TypeSourceInfo *> Args,
3611 SourceLocation RParenLoc) {
3612 switch (Kind) {
3613 case clang::TT_IsTriviallyConstructible: {
3614 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00003615 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00003616 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00003617 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00003618 // definition for is_constructible, as defined below, is known to call
3619 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00003620 //
3621 // The predicate condition for a template specialization
3622 // is_constructible<T, Args...> shall be satisfied if and only if the
3623 // following variable definition would be well-formed for some invented
3624 // variable t:
3625 //
3626 // T t(create<Args>()...);
3627 if (Args.empty()) {
3628 S.Diag(KWLoc, diag::err_type_trait_arity)
3629 << 1 << 1 << 1 << (int)Args.size();
3630 return false;
3631 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00003632
3633 // Precondition: T and all types in the parameter pack Args shall be
3634 // complete types, (possibly cv-qualified) void, or arrays of
3635 // unknown bound.
Douglas Gregor29c42f22012-02-24 07:38:34 +00003636 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
Eli Friedman9ea1e162013-09-11 02:53:02 +00003637 QualType ArgTy = Args[I]->getType();
3638 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00003639 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00003640
3641 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00003642 diag::err_incomplete_type_used_in_type_trait_expr))
3643 return false;
3644 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00003645
3646 // Make sure the first argument is a complete type.
3647 if (Args[0]->getType()->isIncompleteType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00003648 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00003649
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003650 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3651 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00003652 ArgExprs.reserve(Args.size() - 1);
3653 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3654 QualType T = Args[I]->getType();
3655 if (T->isObjectType() || T->isFunctionType())
3656 T = S.Context.getRValueReferenceType(T);
3657 OpaqueArgExprs.push_back(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003658 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
Douglas Gregor29c42f22012-02-24 07:38:34 +00003659 T.getNonLValueExprType(S.Context),
3660 Expr::getValueKindForType(T)));
3661 ArgExprs.push_back(&OpaqueArgExprs.back());
3662 }
3663
3664 // Perform the initialization in an unevaluated context within a SFINAE
3665 // trap at translation unit scope.
3666 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3667 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3668 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3669 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3670 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3671 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003672 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00003673 if (Init.Failed())
3674 return false;
3675
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003676 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00003677 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3678 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00003679
3680 // Under Objective-C ARC, if the destination has non-trivial Objective-C
3681 // lifetime, this is a non-trivial construction.
3682 if (S.getLangOpts().ObjCAutoRefCount &&
3683 hasNontrivialObjCLifetime(Args[0]->getType().getNonReferenceType()))
3684 return false;
3685
3686 // The initialization succeeded; now make sure there are no non-trivial
Douglas Gregor29c42f22012-02-24 07:38:34 +00003687 // calls.
3688 return !Result.get()->hasNonTrivialCall(S.Context);
3689 }
3690 }
3691
3692 return false;
3693}
3694
3695ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3696 ArrayRef<TypeSourceInfo *> Args,
3697 SourceLocation RParenLoc) {
3698 bool Dependent = false;
3699 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3700 if (Args[I]->getType()->isDependentType()) {
3701 Dependent = true;
3702 break;
3703 }
3704 }
3705
3706 bool Value = false;
3707 if (!Dependent)
3708 Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3709
3710 return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind,
3711 Args, RParenLoc, Value);
3712}
3713
3714ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3715 ArrayRef<ParsedType> Args,
3716 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003717 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00003718 ConvertedArgs.reserve(Args.size());
3719
3720 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3721 TypeSourceInfo *TInfo;
3722 QualType T = GetTypeFromParser(Args[I], &TInfo);
3723 if (!TInfo)
3724 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3725
3726 ConvertedArgs.push_back(TInfo);
3727 }
3728
3729 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3730}
3731
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003732static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3733 QualType LhsT, QualType RhsT,
3734 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003735 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3736 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003737
3738 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00003739 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003740 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00003741 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003742 // Base and Derived are not unions and name the same class type without
3743 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003744
John McCall388ef532011-01-28 22:02:36 +00003745 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3746 if (!lhsRecord) return false;
3747
3748 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3749 if (!rhsRecord) return false;
3750
3751 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3752 == (lhsRecord == rhsRecord));
3753
3754 if (lhsRecord == rhsRecord)
3755 return !lhsRecord->getDecl()->isUnion();
3756
3757 // C++0x [meta.rel]p2:
3758 // If Base and Derived are class types and are different types
3759 // (ignoring possible cv-qualifiers) then Derived shall be a
3760 // complete type.
3761 if (Self.RequireCompleteType(KeyLoc, RhsT,
3762 diag::err_incomplete_type_used_in_type_trait_expr))
3763 return false;
3764
3765 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3766 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3767 }
John Wiegley65497cc2011-04-27 23:09:49 +00003768 case BTT_IsSame:
3769 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00003770 case BTT_TypeCompatible:
3771 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3772 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00003773 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00003774 case BTT_IsConvertibleTo: {
3775 // C++0x [meta.rel]p4:
3776 // Given the following function prototype:
3777 //
3778 // template <class T>
3779 // typename add_rvalue_reference<T>::type create();
3780 //
3781 // the predicate condition for a template specialization
3782 // is_convertible<From, To> shall be satisfied if and only if
3783 // the return expression in the following code would be
3784 // well-formed, including any implicit conversions to the return
3785 // type of the function:
3786 //
3787 // To test() {
3788 // return create<From>();
3789 // }
3790 //
3791 // Access checking is performed as if in a context unrelated to To and
3792 // From. Only the validity of the immediate context of the expression
3793 // of the return-statement (including conversions to the return type)
3794 // is considered.
3795 //
3796 // We model the initialization as a copy-initialization of a temporary
3797 // of the appropriate type, which for this expression is identical to the
3798 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00003799
3800 // Functions aren't allowed to return function or array types.
3801 if (RhsT->isFunctionType() || RhsT->isArrayType())
3802 return false;
3803
3804 // A return statement in a void function must have void type.
3805 if (RhsT->isVoidType())
3806 return LhsT->isVoidType();
3807
3808 // A function definition requires a complete, non-abstract return type.
3809 if (Self.RequireCompleteType(KeyLoc, RhsT, 0) ||
3810 Self.RequireNonAbstractType(KeyLoc, RhsT, 0))
3811 return false;
3812
3813 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00003814 if (LhsT->isObjectType() || LhsT->isFunctionType())
3815 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00003816
3817 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00003818 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00003819 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00003820 Expr::getValueKindForType(LhsT));
3821 Expr *FromPtr = &From;
3822 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3823 SourceLocation()));
3824
Eli Friedmana59b1902012-01-25 01:05:57 +00003825 // Perform the initialization in an unevaluated context within a SFINAE
3826 // trap at translation unit scope.
3827 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00003828 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3829 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00003830 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003831 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00003832 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00003833
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003834 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00003835 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3836 }
Douglas Gregor1be329d2012-02-23 07:33:15 +00003837
3838 case BTT_IsTriviallyAssignable: {
3839 // C++11 [meta.unary.prop]p3:
3840 // is_trivially_assignable is defined as:
3841 // is_assignable<T, U>::value is true and the assignment, as defined by
3842 // is_assignable, is known to call no operation that is not trivial
3843 //
3844 // is_assignable is defined as:
3845 // The expression declval<T>() = declval<U>() is well-formed when
3846 // treated as an unevaluated operand (Clause 5).
3847 //
3848 // For both, T and U shall be complete types, (possibly cv-qualified)
3849 // void, or arrays of unknown bound.
3850 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3851 Self.RequireCompleteType(KeyLoc, LhsT,
3852 diag::err_incomplete_type_used_in_type_trait_expr))
3853 return false;
3854 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3855 Self.RequireCompleteType(KeyLoc, RhsT,
3856 diag::err_incomplete_type_used_in_type_trait_expr))
3857 return false;
3858
3859 // cv void is never assignable.
3860 if (LhsT->isVoidType() || RhsT->isVoidType())
3861 return false;
3862
3863 // Build expressions that emulate the effect of declval<T>() and
3864 // declval<U>().
3865 if (LhsT->isObjectType() || LhsT->isFunctionType())
3866 LhsT = Self.Context.getRValueReferenceType(LhsT);
3867 if (RhsT->isObjectType() || RhsT->isFunctionType())
3868 RhsT = Self.Context.getRValueReferenceType(RhsT);
3869 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3870 Expr::getValueKindForType(LhsT));
3871 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3872 Expr::getValueKindForType(RhsT));
3873
3874 // Attempt the assignment in an unevaluated context within a SFINAE
3875 // trap at translation unit scope.
3876 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3877 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3878 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3879 ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs);
3880 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3881 return false;
3882
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00003883 // Under Objective-C ARC, if the destination has non-trivial Objective-C
3884 // lifetime, this is a non-trivial assignment.
3885 if (Self.getLangOpts().ObjCAutoRefCount &&
3886 hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
3887 return false;
3888
Douglas Gregor1be329d2012-02-23 07:33:15 +00003889 return !Result.get()->hasNonTrivialCall(Self.Context);
3890 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003891 }
3892 llvm_unreachable("Unknown type trait or not implemented");
3893}
3894
3895ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3896 SourceLocation KWLoc,
3897 TypeSourceInfo *LhsTSInfo,
3898 TypeSourceInfo *RhsTSInfo,
3899 SourceLocation RParen) {
3900 QualType LhsT = LhsTSInfo->getType();
3901 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003902
John McCall388ef532011-01-28 22:02:36 +00003903 if (BTT == BTT_TypeCompatible) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003904 if (getLangOpts().CPlusPlus) {
Francois Pichet34b21132010-12-08 22:35:30 +00003905 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3906 << SourceRange(KWLoc, RParen);
3907 return ExprError();
3908 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003909 }
3910
3911 bool Value = false;
3912 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3913 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3914
Francois Pichet34b21132010-12-08 22:35:30 +00003915 // Select trait result type.
3916 QualType ResultType;
3917 switch (BTT) {
Francois Pichet34b21132010-12-08 22:35:30 +00003918 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley65497cc2011-04-27 23:09:49 +00003919 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3920 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichet34b21132010-12-08 22:35:30 +00003921 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor8006e762011-01-27 20:28:01 +00003922 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Douglas Gregor1be329d2012-02-23 07:33:15 +00003923 case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy;
Francois Pichet34b21132010-12-08 22:35:30 +00003924 }
3925
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003926 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3927 RhsTSInfo, Value, RParen,
Francois Pichet34b21132010-12-08 22:35:30 +00003928 ResultType));
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003929}
3930
John Wiegley6242b6a2011-04-28 00:16:57 +00003931ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3932 SourceLocation KWLoc,
3933 ParsedType Ty,
3934 Expr* DimExpr,
3935 SourceLocation RParen) {
3936 TypeSourceInfo *TSInfo;
3937 QualType T = GetTypeFromParser(Ty, &TSInfo);
3938 if (!TSInfo)
3939 TSInfo = Context.getTrivialTypeSourceInfo(T);
3940
3941 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3942}
3943
3944static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3945 QualType T, Expr *DimExpr,
3946 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003947 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00003948
3949 switch(ATT) {
3950 case ATT_ArrayRank:
3951 if (T->isArrayType()) {
3952 unsigned Dim = 0;
3953 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3954 ++Dim;
3955 T = AT->getElementType();
3956 }
3957 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00003958 }
John Wiegleyd3522222011-04-28 02:06:46 +00003959 return 0;
3960
John Wiegley6242b6a2011-04-28 00:16:57 +00003961 case ATT_ArrayExtent: {
3962 llvm::APSInt Value;
3963 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00003964 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00003965 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00003966 false).isInvalid())
3967 return 0;
3968 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00003969 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3970 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00003971 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00003972 }
Richard Smithf4c51d92012-02-04 09:53:13 +00003973 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00003974
3975 if (T->isArrayType()) {
3976 unsigned D = 0;
3977 bool Matched = false;
3978 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3979 if (Dim == D) {
3980 Matched = true;
3981 break;
3982 }
3983 ++D;
3984 T = AT->getElementType();
3985 }
3986
John Wiegleyd3522222011-04-28 02:06:46 +00003987 if (Matched && T->isArrayType()) {
3988 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3989 return CAT->getSize().getLimitedValue();
3990 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003991 }
John Wiegleyd3522222011-04-28 02:06:46 +00003992 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00003993 }
3994 }
3995 llvm_unreachable("Unknown type trait or not implemented");
3996}
3997
3998ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3999 SourceLocation KWLoc,
4000 TypeSourceInfo *TSInfo,
4001 Expr* DimExpr,
4002 SourceLocation RParen) {
4003 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00004004
Chandler Carruthc5276e52011-05-01 08:48:21 +00004005 // FIXME: This should likely be tracked as an APInt to remove any host
4006 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004007 uint64_t Value = 0;
4008 if (!T->isDependentType())
4009 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4010
Chandler Carruthc5276e52011-05-01 08:48:21 +00004011 // While the specification for these traits from the Embarcadero C++
4012 // compiler's documentation says the return type is 'unsigned int', Clang
4013 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4014 // compiler, there is no difference. On several other platforms this is an
4015 // important distinction.
John Wiegley6242b6a2011-04-28 00:16:57 +00004016 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth9cf632c2011-05-01 07:49:26 +00004017 DimExpr, RParen,
Chandler Carruthc5276e52011-05-01 08:48:21 +00004018 Context.getSizeType()));
John Wiegley6242b6a2011-04-28 00:16:57 +00004019}
4020
John Wiegleyf9f65842011-04-25 06:54:41 +00004021ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004022 SourceLocation KWLoc,
4023 Expr *Queried,
4024 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004025 // If error parsing the expression, ignore.
4026 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004027 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00004028
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004029 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004030
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004031 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00004032}
4033
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004034static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4035 switch (ET) {
4036 case ET_IsLValueExpr: return E->isLValue();
4037 case ET_IsRValueExpr: return E->isRValue();
4038 }
4039 llvm_unreachable("Expression trait not covered by switch");
4040}
4041
John Wiegleyf9f65842011-04-25 06:54:41 +00004042ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004043 SourceLocation KWLoc,
4044 Expr *Queried,
4045 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004046 if (Queried->isTypeDependent()) {
4047 // Delay type-checking for type-dependent expressions.
4048 } else if (Queried->getType()->isPlaceholderType()) {
4049 ExprResult PE = CheckPlaceholderExpr(Queried);
4050 if (PE.isInvalid()) return ExprError();
4051 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
4052 }
4053
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004054 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00004055
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004056 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
4057 RParen, Context.BoolTy));
John Wiegleyf9f65842011-04-25 06:54:41 +00004058}
4059
Richard Trieu82402a02011-09-15 21:56:47 +00004060QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004061 ExprValueKind &VK,
4062 SourceLocation Loc,
4063 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004064 assert(!LHS.get()->getType()->isPlaceholderType() &&
4065 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00004066 "placeholders should have been weeded out by now");
4067
4068 // The LHS undergoes lvalue conversions if this is ->*.
4069 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004070 LHS = DefaultLvalueConversion(LHS.take());
4071 if (LHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004072 }
4073
4074 // The RHS always undergoes lvalue conversions.
Richard Trieu82402a02011-09-15 21:56:47 +00004075 RHS = DefaultLvalueConversion(RHS.take());
4076 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004077
Sebastian Redl5822f082009-02-07 20:10:22 +00004078 const char *OpSpelling = isIndirect ? "->*" : ".*";
4079 // C++ 5.5p2
4080 // The binary operator .* [p3: ->*] binds its second operand, which shall
4081 // be of type "pointer to member of T" (where T is a completely-defined
4082 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00004083 QualType RHSType = RHS.get()->getType();
4084 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004085 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00004086 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00004087 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00004088 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004089 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004090
Sebastian Redl5822f082009-02-07 20:10:22 +00004091 QualType Class(MemPtr->getClass(), 0);
4092
Douglas Gregord07ba342010-10-13 20:41:14 +00004093 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
4094 // member pointer points must be completely-defined. However, there is no
4095 // reason for this semantic distinction, and the rule is not enforced by
4096 // other compilers. Therefore, we do not check this property, as it is
4097 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00004098
Sebastian Redl5822f082009-02-07 20:10:22 +00004099 // C++ 5.5p2
4100 // [...] to its first operand, which shall be of class T or of a class of
4101 // which T is an unambiguous and accessible base class. [p3: a pointer to
4102 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00004103 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00004104 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004105 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
4106 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00004107 else {
4108 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00004109 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00004110 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00004111 return QualType();
4112 }
4113 }
4114
Richard Trieu82402a02011-09-15 21:56:47 +00004115 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00004116 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004117 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
4118 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00004119 return QualType();
4120 }
Anders Carlssona70cff62010-04-24 19:06:50 +00004121 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00004122 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00004123 // FIXME: Would it be useful to print full ambiguity paths, or is that
4124 // overkill?
Richard Trieu82402a02011-09-15 21:56:47 +00004125 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl5822f082009-02-07 20:10:22 +00004126 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
4127 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00004128 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00004129 return QualType();
4130 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00004131 // Cast LHS to type of use.
4132 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00004133 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004134
John McCallcf142162010-08-07 06:22:56 +00004135 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004136 BuildBasePathArray(Paths, BasePath);
Richard Trieu82402a02011-09-15 21:56:47 +00004137 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
4138 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00004139 }
4140
Richard Trieu82402a02011-09-15 21:56:47 +00004141 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00004142 // Diagnose use of pointer-to-member type which when used as
4143 // the functional cast in a pointer-to-member expression.
4144 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
4145 return QualType();
4146 }
John McCall7decc9e2010-11-18 06:31:45 +00004147
Sebastian Redl5822f082009-02-07 20:10:22 +00004148 // C++ 5.5p2
4149 // The result is an object or a function of the type specified by the
4150 // second operand.
4151 // The cv qualifiers are the union of those in the pointer and the left side,
4152 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00004153 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00004154 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00004155
Douglas Gregor1d042092011-01-26 16:40:18 +00004156 // C++0x [expr.mptr.oper]p6:
4157 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004158 // ill-formed if the second operand is a pointer to member function with
4159 // ref-qualifier &. In a ->* expression or in a .* expression whose object
4160 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00004161 // is a pointer to member function with ref-qualifier &&.
4162 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
4163 switch (Proto->getRefQualifier()) {
4164 case RQ_None:
4165 // Do nothing
4166 break;
4167
4168 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00004169 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00004170 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00004171 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00004172 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004173
Douglas Gregor1d042092011-01-26 16:40:18 +00004174 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00004175 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00004176 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00004177 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00004178 break;
4179 }
4180 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004181
John McCall7decc9e2010-11-18 06:31:45 +00004182 // C++ [expr.mptr.oper]p6:
4183 // The result of a .* expression whose second operand is a pointer
4184 // to a data member is of the same value category as its
4185 // first operand. The result of a .* expression whose second
4186 // operand is a pointer to a member function is a prvalue. The
4187 // result of an ->* expression is an lvalue if its second operand
4188 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00004189 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00004190 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00004191 return Context.BoundMemberTy;
4192 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00004193 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00004194 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00004195 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00004196 }
John McCall7decc9e2010-11-18 06:31:45 +00004197
Sebastian Redl5822f082009-02-07 20:10:22 +00004198 return Result;
4199}
Sebastian Redl1a99f442009-04-16 17:51:27 +00004200
Sebastian Redl1a99f442009-04-16 17:51:27 +00004201/// \brief Try to convert a type to another according to C++0x 5.16p3.
4202///
4203/// This is part of the parameter validation for the ? operator. If either
4204/// value operand is a class type, the two operands are attempted to be
4205/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00004206/// It returns true if the program is ill-formed and has already been diagnosed
4207/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004208static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
4209 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00004210 bool &HaveConversion,
4211 QualType &ToType) {
4212 HaveConversion = false;
4213 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004214
4215 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00004216 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00004217 // C++0x 5.16p3
4218 // The process for determining whether an operand expression E1 of type T1
4219 // can be converted to match an operand expression E2 of type T2 is defined
4220 // as follows:
4221 // -- If E2 is an lvalue:
John McCall086a4642010-11-24 05:12:34 +00004222 bool ToIsLvalue = To->isLValue();
Douglas Gregorf9edf802010-03-26 20:59:55 +00004223 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004224 // E1 can be converted to match E2 if E1 can be implicitly converted to
4225 // type "lvalue reference to T2", subject to the constraint that in the
4226 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00004227 QualType T = Self.Context.getLValueReferenceType(ToType);
4228 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004229
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004230 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00004231 if (InitSeq.isDirectReferenceBinding()) {
4232 ToType = T;
4233 HaveConversion = true;
4234 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004235 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004236
Douglas Gregor838fcc32010-03-26 20:14:36 +00004237 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004238 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004239 }
John McCall65eb8792010-02-25 01:37:24 +00004240
Sebastian Redl1a99f442009-04-16 17:51:27 +00004241 // -- If E2 is an rvalue, or if the conversion above cannot be done:
4242 // -- if E1 and E2 have class type, and the underlying class types are
4243 // the same or one is a base class of the other:
4244 QualType FTy = From->getType();
4245 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004246 const RecordType *FRec = FTy->getAs<RecordType>();
4247 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004248 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00004249 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004250 if (FRec && TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00004251 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004252 // E1 can be converted to match E2 if the class of T2 is the
4253 // same type as, or a base class of, the class of T1, and
4254 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00004255 if (FRec == TRec || FDerivedFromT) {
4256 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00004257 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004258 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004259 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00004260 HaveConversion = true;
4261 return false;
4262 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263
Douglas Gregor838fcc32010-03-26 20:14:36 +00004264 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004265 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004266 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268
Douglas Gregor838fcc32010-03-26 20:14:36 +00004269 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004270 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004271
Douglas Gregor838fcc32010-03-26 20:14:36 +00004272 // -- Otherwise: E1 can be converted to match E2 if E1 can be
4273 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004274 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00004275 // an rvalue).
4276 //
4277 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
4278 // to the array-to-pointer or function-to-pointer conversions.
4279 if (!TTy->getAs<TagType>())
4280 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004281
Douglas Gregor838fcc32010-03-26 20:14:36 +00004282 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004283 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004284 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00004285 ToType = TTy;
4286 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004287 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00004288
Sebastian Redl1a99f442009-04-16 17:51:27 +00004289 return false;
4290}
4291
4292/// \brief Try to find a common type for two according to C++0x 5.16p5.
4293///
4294/// This is part of the parameter validation for the ? operator. If either
4295/// value operand is a class type, overload resolution is used to find a
4296/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00004297static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004298 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004299 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004300 OverloadCandidateSet CandidateSet(QuestionLoc);
Richard Smithe54c3072013-05-05 15:51:06 +00004301 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004302 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004303
4304 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004305 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00004306 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004307 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00004308 ExprResult LHSRes =
4309 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
4310 Best->Conversions[0], Sema::AA_Converting);
4311 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004312 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004313 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00004314
4315 ExprResult RHSRes =
4316 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
4317 Best->Conversions[1], Sema::AA_Converting);
4318 if (RHSRes.isInvalid())
4319 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004320 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00004321 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00004322 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004323 return false;
John Wiegley01296292011-04-08 18:41:53 +00004324 }
4325
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004326 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004327
4328 // Emit a better diagnostic if one of the expressions is a null pointer
4329 // constant and the other is a pointer type. In this case, the user most
4330 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004331 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004332 return true;
4333
4334 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004335 << LHS.get()->getType() << RHS.get()->getType()
4336 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004337 return true;
4338
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004339 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004340 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00004341 << LHS.get()->getType() << RHS.get()->getType()
4342 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00004343 // FIXME: Print the possible common types by printing the return types of
4344 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004345 break;
4346
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004347 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00004348 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004349 }
4350 return true;
4351}
4352
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004353/// \brief Perform an "extended" implicit conversion as returned by
4354/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00004355static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00004356 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00004357 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00004358 SourceLocation());
John Wiegley01296292011-04-08 18:41:53 +00004359 Expr *Arg = E.take();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004360 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004361 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00004362 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004363 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004364
John Wiegley01296292011-04-08 18:41:53 +00004365 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004366 return false;
4367}
4368
Sebastian Redl1a99f442009-04-16 17:51:27 +00004369/// \brief Check the operands of ?: under C++ semantics.
4370///
4371/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4372/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00004373QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4374 ExprResult &RHS, ExprValueKind &VK,
4375 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00004376 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00004377 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4378 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004379
Richard Smith45edb702012-08-07 22:06:48 +00004380 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00004381 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00004382 if (!Cond.get()->isTypeDependent()) {
4383 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
4384 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004385 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004386 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004387 }
4388
John McCall7decc9e2010-11-18 06:31:45 +00004389 // Assume r-value.
4390 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004391 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00004392
Sebastian Redl1a99f442009-04-16 17:51:27 +00004393 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00004394 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004395 return Context.DependentTy;
4396
Richard Smith45edb702012-08-07 22:06:48 +00004397 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00004398 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00004399 QualType LTy = LHS.get()->getType();
4400 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004401 bool LVoid = LTy->isVoidType();
4402 bool RVoid = RTy->isVoidType();
4403 if (LVoid || RVoid) {
4404 // ... then the [l2r] conversions are performed on the second and third
4405 // operands ...
John Wiegley01296292011-04-08 18:41:53 +00004406 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4407 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4408 if (LHS.isInvalid() || RHS.isInvalid())
4409 return QualType();
Richard Smith45edb702012-08-07 22:06:48 +00004410
4411 // Finish off the lvalue-to-rvalue conversion by copy-initializing a
4412 // temporary if necessary. DefaultFunctionArrayLvalueConversion doesn't
4413 // do this part for us.
4414 ExprResult &NonVoid = LVoid ? RHS : LHS;
4415 if (NonVoid.get()->getType()->isRecordType() &&
4416 NonVoid.get()->isGLValue()) {
David Blaikie6154ef92012-09-10 22:05:41 +00004417 if (RequireNonAbstractType(QuestionLoc, NonVoid.get()->getType(),
4418 diag::err_allocation_of_abstract_type))
4419 return QualType();
Richard Smith45edb702012-08-07 22:06:48 +00004420 InitializedEntity Entity =
4421 InitializedEntity::InitializeTemporary(NonVoid.get()->getType());
4422 NonVoid = PerformCopyInitialization(Entity, SourceLocation(), NonVoid);
4423 if (NonVoid.isInvalid())
4424 return QualType();
4425 }
4426
John Wiegley01296292011-04-08 18:41:53 +00004427 LTy = LHS.get()->getType();
4428 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004429
4430 // ... and one of the following shall hold:
4431 // -- The second or the third operand (but not both) is a throw-
Richard Smith45edb702012-08-07 22:06:48 +00004432 // expression; the result is of the type of the other and is a prvalue.
David Majnemera9d4f772013-06-02 08:40:42 +00004433 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenCasts());
4434 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenCasts());
Sebastian Redl1a99f442009-04-16 17:51:27 +00004435 if (LThrow && !RThrow)
4436 return RTy;
4437 if (RThrow && !LThrow)
4438 return LTy;
4439
4440 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00004441 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004442 if (LVoid && RVoid)
4443 return Context.VoidTy;
4444
4445 // Neither holds, error.
4446 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4447 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00004448 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004449 return QualType();
4450 }
4451
4452 // Neither is void.
4453
Richard Smithf2b084f2012-08-08 06:13:49 +00004454 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00004455 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00004456 // either has (cv) class type [...] an attempt is made to convert each of
4457 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004458 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00004459 (LTy->isRecordType() || RTy->isRecordType())) {
4460 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
4461 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00004462 QualType L2RType, R2LType;
4463 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00004464 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00004465 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004466 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00004467 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468
Sebastian Redl1a99f442009-04-16 17:51:27 +00004469 // If both can be converted, [...] the program is ill-formed.
4470 if (HaveL2R && HaveR2L) {
4471 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00004472 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004473 return QualType();
4474 }
4475
4476 // If exactly one conversion is possible, that conversion is applied to
4477 // the chosen operand and the converted operands are used in place of the
4478 // original operands for the remainder of this section.
4479 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00004480 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004481 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004482 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004483 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00004484 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004485 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004486 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004487 }
4488 }
4489
Richard Smithf2b084f2012-08-08 06:13:49 +00004490 // C++11 [expr.cond]p3
4491 // if both are glvalues of the same value category and the same type except
4492 // for cv-qualification, an attempt is made to convert each of those
4493 // operands to the type of the other.
4494 ExprValueKind LVK = LHS.get()->getValueKind();
4495 ExprValueKind RVK = RHS.get()->getValueKind();
4496 if (!Context.hasSameType(LTy, RTy) &&
4497 Context.hasSameUnqualifiedType(LTy, RTy) &&
4498 LVK == RVK && LVK != VK_RValue) {
4499 // Since the unqualified types are reference-related and we require the
4500 // result to be as if a reference bound directly, the only conversion
4501 // we can perform is to add cv-qualifiers.
4502 Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
4503 Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
4504 if (RCVR.isStrictSupersetOf(LCVR)) {
4505 LHS = ImpCastExprToType(LHS.take(), RTy, CK_NoOp, LVK);
4506 LTy = LHS.get()->getType();
4507 }
4508 else if (LCVR.isStrictSupersetOf(RCVR)) {
4509 RHS = ImpCastExprToType(RHS.take(), LTy, CK_NoOp, RVK);
4510 RTy = RHS.get()->getType();
4511 }
4512 }
4513
4514 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00004515 // If the second and third operands are glvalues of the same value
4516 // category and have the same type, the result is of that type and
4517 // value category and it is a bit-field if the second or the third
4518 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00004519 // We only extend this to bitfields, not to the crazy other kinds of
4520 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00004521 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00004522 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00004523 LHS.get()->isOrdinaryOrBitFieldObject() &&
4524 RHS.get()->isOrdinaryOrBitFieldObject()) {
4525 VK = LHS.get()->getValueKind();
4526 if (LHS.get()->getObjectKind() == OK_BitField ||
4527 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00004528 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00004529 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00004530 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004531
Richard Smithf2b084f2012-08-08 06:13:49 +00004532 // C++11 [expr.cond]p5
4533 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00004534 // do not have the same type, and either has (cv) class type, ...
4535 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4536 // ... overload resolution is used to determine the conversions (if any)
4537 // to be applied to the operands. If the overload resolution fails, the
4538 // program is ill-formed.
4539 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4540 return QualType();
4541 }
4542
Richard Smithf2b084f2012-08-08 06:13:49 +00004543 // C++11 [expr.cond]p6
4544 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00004545 // conversions are performed on the second and third operands.
John Wiegley01296292011-04-08 18:41:53 +00004546 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4547 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4548 if (LHS.isInvalid() || RHS.isInvalid())
4549 return QualType();
4550 LTy = LHS.get()->getType();
4551 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004552
4553 // After those conversions, one of the following shall hold:
4554 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004555 // is of that type. If the operands have class type, the result
4556 // is a prvalue temporary of the result type, which is
4557 // copy-initialized from either the second operand or the third
4558 // operand depending on the value of the first operand.
4559 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4560 if (LTy->isRecordType()) {
4561 // The operands have class type. Make a temporary copy.
David Blaikie6154ef92012-09-10 22:05:41 +00004562 if (RequireNonAbstractType(QuestionLoc, LTy,
4563 diag::err_allocation_of_abstract_type))
4564 return QualType();
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004565 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00004566
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004567 ExprResult LHSCopy = PerformCopyInitialization(Entity,
4568 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00004569 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004570 if (LHSCopy.isInvalid())
4571 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004572
4573 ExprResult RHSCopy = PerformCopyInitialization(Entity,
4574 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00004575 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004576 if (RHSCopy.isInvalid())
4577 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578
John Wiegley01296292011-04-08 18:41:53 +00004579 LHS = LHSCopy;
4580 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004581 }
4582
Sebastian Redl1a99f442009-04-16 17:51:27 +00004583 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004584 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004585
Douglas Gregor46188682010-05-18 22:42:18 +00004586 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004587 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004588 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00004589
Sebastian Redl1a99f442009-04-16 17:51:27 +00004590 // -- The second and third operands have arithmetic or enumeration type;
4591 // the usual arithmetic conversions are performed to bring them to a
4592 // common type, and the result is of that type.
4593 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4594 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004595 if (LHS.isInvalid() || RHS.isInvalid())
4596 return QualType();
4597 return LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004598 }
4599
4600 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00004601 // type and the other is a null pointer constant, or both are null
4602 // pointer constants, at least one of which is non-integral; pointer
4603 // conversions and qualification conversions are performed to bring them
4604 // to their composite pointer type. The result is of the composite
4605 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00004606 // -- The second and third operands have pointer to member type, or one has
4607 // pointer to member type and the other is a null pointer constant;
4608 // pointer to member conversions and qualification conversions are
4609 // performed to bring them to a common type, whose cv-qualification
4610 // shall match the cv-qualification of either the second or the third
4611 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004612 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00004613 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004614 isSFINAEContext()? 0 : &NonStandardCompositeType);
4615 if (!Composite.isNull()) {
4616 if (NonStandardCompositeType)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004617 Diag(QuestionLoc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004618 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4619 << LTy << RTy << Composite
John Wiegley01296292011-04-08 18:41:53 +00004620 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004622 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004623 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004624
Douglas Gregor697a3912010-04-01 22:47:07 +00004625 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00004626 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4627 if (!Composite.isNull())
4628 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004629
Chandler Carruth9c9127e2011-02-19 00:13:59 +00004630 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00004631 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00004632 return QualType();
4633
Sebastian Redl1a99f442009-04-16 17:51:27 +00004634 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004635 << LHS.get()->getType() << RHS.get()->getType()
4636 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004637 return QualType();
4638}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004639
4640/// \brief Find a merged pointer type and convert the two expressions to it.
4641///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004642/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smithf2b084f2012-08-08 06:13:49 +00004643/// and @p E2 according to C++11 5.9p2. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004644/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004645/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004646///
Douglas Gregor19175ff2010-04-16 23:20:25 +00004647/// \param Loc The location of the operator requiring these two expressions to
4648/// be converted to the composite pointer type.
4649///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004650/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4651/// a non-standard (but still sane) composite type to which both expressions
4652/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4653/// will be set true.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004654QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00004655 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004656 bool *NonStandardCompositeType) {
4657 if (NonStandardCompositeType)
4658 *NonStandardCompositeType = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004659
David Blaikiebbafb8a2012-03-11 07:00:24 +00004660 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004661 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004662
Richard Smithf2b084f2012-08-08 06:13:49 +00004663 // C++11 5.9p2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004664 // Pointer conversions and qualification conversions are performed on
4665 // pointer operands to bring them to their composite pointer type. If
4666 // one operand is a null pointer constant, the composite pointer type is
Richard Smithf2b084f2012-08-08 06:13:49 +00004667 // std::nullptr_t if the other operand is also a null pointer constant or,
4668 // if the other operand is a pointer, the type of the other operand.
4669 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4670 !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
4671 if (T1->isNullPtrType() &&
4672 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4673 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
4674 return T1;
4675 }
4676 if (T2->isNullPtrType() &&
4677 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4678 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
4679 return T2;
4680 }
4681 return QualType();
4682 }
4683
Douglas Gregor56751b52009-09-25 04:25:58 +00004684 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004685 if (T2->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00004686 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004687 else
John Wiegley01296292011-04-08 18:41:53 +00004688 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004689 return T2;
4690 }
Douglas Gregor56751b52009-09-25 04:25:58 +00004691 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004692 if (T1->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00004693 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004694 else
John Wiegley01296292011-04-08 18:41:53 +00004695 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004696 return T1;
4697 }
Mike Stump11289f42009-09-09 15:08:12 +00004698
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004699 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00004700 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4701 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004702 return QualType();
4703
4704 // Otherwise, of one of the operands has type "pointer to cv1 void," then
4705 // the other has type "pointer to cv2 T" and the composite pointer type is
4706 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4707 // Otherwise, the composite pointer type is a pointer type similar to the
4708 // type of one of the operands, with a cv-qualification signature that is
4709 // the union of the cv-qualification signatures of the operand types.
4710 // In practice, the first part here is redundant; it's subsumed by the second.
4711 // What we do here is, we build the two possible composite types, and try the
4712 // conversions in both directions. If only one works, or if the two composite
4713 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00004714 // FIXME: extended qualifiers?
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004715 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redl658262f2009-11-16 21:03:45 +00004716 QualifierVector QualifierUnion;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004717 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redl658262f2009-11-16 21:03:45 +00004718 ContainingClassVector;
4719 ContainingClassVector MemberOfClass;
4720 QualType Composite1 = Context.getCanonicalType(T1),
4721 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004722 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004723 do {
4724 const PointerType *Ptr1, *Ptr2;
4725 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4726 (Ptr2 = Composite2->getAs<PointerType>())) {
4727 Composite1 = Ptr1->getPointeeType();
4728 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004729
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004730 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004731 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004732 if (NonStandardCompositeType &&
4733 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4734 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004735
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004736 QualifierUnion.push_back(
4737 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4738 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
4739 continue;
4740 }
Mike Stump11289f42009-09-09 15:08:12 +00004741
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004742 const MemberPointerType *MemPtr1, *MemPtr2;
4743 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4744 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4745 Composite1 = MemPtr1->getPointeeType();
4746 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004747
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004748 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004749 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004750 if (NonStandardCompositeType &&
4751 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4752 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004753
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004754 QualifierUnion.push_back(
4755 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4756 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4757 MemPtr2->getClass()));
4758 continue;
4759 }
Mike Stump11289f42009-09-09 15:08:12 +00004760
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004761 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00004762
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004763 // Cannot unwrap any more types.
4764 break;
4765 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00004766
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004767 if (NeedConstBefore && NonStandardCompositeType) {
4768 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004769 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004770 // requirements of C++ [conv.qual]p4 bullet 3.
4771 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4772 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4773 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4774 *NonStandardCompositeType = true;
4775 }
4776 }
4777 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004778
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004779 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00004780 ContainingClassVector::reverse_iterator MOC
4781 = MemberOfClass.rbegin();
4782 for (QualifierVector::reverse_iterator
4783 I = QualifierUnion.rbegin(),
4784 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004785 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00004786 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004787 if (MOC->first && MOC->second) {
4788 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00004789 Composite1 = Context.getMemberPointerType(
4790 Context.getQualifiedType(Composite1, Quals),
4791 MOC->first);
4792 Composite2 = Context.getMemberPointerType(
4793 Context.getQualifiedType(Composite2, Quals),
4794 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004795 } else {
4796 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00004797 Composite1
4798 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4799 Composite2
4800 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004801 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004802 }
4803
Douglas Gregor19175ff2010-04-16 23:20:25 +00004804 // Try to convert to the first composite pointer type.
4805 InitializedEntity Entity1
4806 = InitializedEntity::InitializeTemporary(Composite1);
4807 InitializationKind Kind
4808 = InitializationKind::CreateCopy(Loc, SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004809 InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
4810 InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
Mike Stump11289f42009-09-09 15:08:12 +00004811
Douglas Gregor19175ff2010-04-16 23:20:25 +00004812 if (E1ToC1 && E2ToC1) {
4813 // Conversion to Composite1 is viable.
4814 if (!Context.hasSameType(Composite1, Composite2)) {
4815 // Composite2 is a different type from Composite1. Check whether
4816 // Composite2 is also viable.
4817 InitializedEntity Entity2
4818 = InitializedEntity::InitializeTemporary(Composite2);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004819 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4820 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00004821 if (E1ToC2 && E2ToC2) {
4822 // Both Composite1 and Composite2 are viable and are different;
4823 // this is an ambiguity.
4824 return QualType();
4825 }
4826 }
4827
4828 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00004829 ExprResult E1Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004830 = E1ToC1.Perform(*this, Entity1, Kind, E1);
Douglas Gregor19175ff2010-04-16 23:20:25 +00004831 if (E1Result.isInvalid())
4832 return QualType();
4833 E1 = E1Result.takeAs<Expr>();
4834
4835 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00004836 ExprResult E2Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004837 = E2ToC1.Perform(*this, Entity1, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00004838 if (E2Result.isInvalid())
4839 return QualType();
4840 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004841
Douglas Gregor19175ff2010-04-16 23:20:25 +00004842 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004843 }
4844
Douglas Gregor19175ff2010-04-16 23:20:25 +00004845 // Check whether Composite2 is viable.
4846 InitializedEntity Entity2
4847 = InitializedEntity::InitializeTemporary(Composite2);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004848 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
4849 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00004850 if (!E1ToC2 || !E2ToC2)
4851 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004852
Douglas Gregor19175ff2010-04-16 23:20:25 +00004853 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00004854 ExprResult E1Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004855 = E1ToC2.Perform(*this, Entity2, Kind, E1);
Douglas Gregor19175ff2010-04-16 23:20:25 +00004856 if (E1Result.isInvalid())
4857 return QualType();
4858 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004859
Douglas Gregor19175ff2010-04-16 23:20:25 +00004860 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00004861 ExprResult E2Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004862 = E2ToC2.Perform(*this, Entity2, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00004863 if (E2Result.isInvalid())
4864 return QualType();
4865 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004866
Douglas Gregor19175ff2010-04-16 23:20:25 +00004867 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004868}
Anders Carlsson85a307d2009-05-17 18:41:29 +00004869
John McCalldadc5752010-08-24 06:29:42 +00004870ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00004871 if (!E)
4872 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004873
John McCall31168b02011-06-15 23:02:42 +00004874 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4875
4876 // If the result is a glvalue, we shouldn't bind it.
4877 if (!E->isRValue())
Anders Carlssonf86a8d12009-08-15 23:41:35 +00004878 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00004879
John McCall31168b02011-06-15 23:02:42 +00004880 // In ARC, calls that return a retainable type can return retained,
4881 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004882 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00004883 E->getType()->isObjCRetainableType()) {
4884
4885 bool ReturnsRetained;
4886
4887 // For actual calls, we compute this by examining the type of the
4888 // called value.
4889 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4890 Expr *Callee = Call->getCallee()->IgnoreParens();
4891 QualType T = Callee->getType();
4892
4893 if (T == Context.BoundMemberTy) {
4894 // Handle pointer-to-members.
4895 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4896 T = BinOp->getRHS()->getType();
4897 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4898 T = Mem->getMemberDecl()->getType();
4899 }
4900
4901 if (const PointerType *Ptr = T->getAs<PointerType>())
4902 T = Ptr->getPointeeType();
4903 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4904 T = Ptr->getPointeeType();
4905 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4906 T = MemPtr->getPointeeType();
4907
4908 const FunctionType *FTy = T->getAs<FunctionType>();
4909 assert(FTy && "call to value not of function type?");
4910 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4911
4912 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4913 // type always produce a +1 object.
4914 } else if (isa<StmtExpr>(E)) {
4915 ReturnsRetained = true;
4916
Ted Kremeneke65b0862012-03-06 20:05:56 +00004917 // We hit this case with the lambda conversion-to-block optimization;
4918 // we don't want any extra casts here.
4919 } else if (isa<CastExpr>(E) &&
4920 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
4921 return Owned(E);
4922
John McCall31168b02011-06-15 23:02:42 +00004923 // For message sends and property references, we try to find an
4924 // actual method. FIXME: we should infer retention by selector in
4925 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00004926 } else {
4927 ObjCMethodDecl *D = 0;
4928 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4929 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00004930 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4931 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00004932 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4933 D = ArrayLit->getArrayWithObjectsMethod();
4934 } else if (ObjCDictionaryLiteral *DictLit
4935 = dyn_cast<ObjCDictionaryLiteral>(E)) {
4936 D = DictLit->getDictWithObjectsMethod();
4937 }
John McCall31168b02011-06-15 23:02:42 +00004938
4939 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00004940
4941 // Don't do reclaims on performSelector calls; despite their
4942 // return type, the invoked method doesn't necessarily actually
4943 // return an object.
4944 if (!ReturnsRetained &&
4945 D && D->getMethodFamily() == OMF_performSelector)
4946 return Owned(E);
John McCall31168b02011-06-15 23:02:42 +00004947 }
4948
John McCall16de4d22011-11-14 19:53:16 +00004949 // Don't reclaim an object of Class type.
4950 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4951 return Owned(E);
4952
John McCall4db5c3c2011-07-07 06:58:02 +00004953 ExprNeedsCleanups = true;
4954
John McCall2d637d22011-09-10 06:18:15 +00004955 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4956 : CK_ARCReclaimReturnedObject);
John McCall4db5c3c2011-07-07 06:58:02 +00004957 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4958 VK_RValue));
John McCall31168b02011-06-15 23:02:42 +00004959 }
4960
David Blaikiebbafb8a2012-03-11 07:00:24 +00004961 if (!getLangOpts().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00004962 return Owned(E);
Douglas Gregor363b1512009-12-24 18:51:59 +00004963
Peter Collingbournec331a1e2012-01-26 03:33:51 +00004964 // Search for the base element type (cf. ASTContext::getBaseElementType) with
4965 // a fast path for the common case that the type is directly a RecordType.
4966 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4967 const RecordType *RT = 0;
4968 while (!RT) {
4969 switch (T->getTypeClass()) {
4970 case Type::Record:
4971 RT = cast<RecordType>(T);
4972 break;
4973 case Type::ConstantArray:
4974 case Type::IncompleteArray:
4975 case Type::VariableArray:
4976 case Type::DependentSizedArray:
4977 T = cast<ArrayType>(T)->getElementType().getTypePtr();
4978 break;
4979 default:
4980 return Owned(E);
4981 }
4982 }
Mike Stump11289f42009-09-09 15:08:12 +00004983
Richard Smithfd555f62012-02-22 02:04:18 +00004984 // That should be enough to guarantee that this type is complete, if we're
4985 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00004986 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00004987 if (RD->isInvalidDecl() || RD->isDependentContext())
John McCall67da35c2010-02-04 22:26:26 +00004988 return Owned(E);
Richard Smithfd555f62012-02-22 02:04:18 +00004989
4990 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
4991 CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00004992
John McCall31168b02011-06-15 23:02:42 +00004993 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00004994 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00004995 CheckDestructorAccess(E->getExprLoc(), Destructor,
4996 PDiag(diag::err_access_dtor_temp)
4997 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00004998 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
4999 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00005000
Richard Smithfd555f62012-02-22 02:04:18 +00005001 // If destructor is trivial, we can avoid the extra copy.
5002 if (Destructor->isTrivial())
5003 return Owned(E);
Richard Smitheec915d62012-02-18 04:13:32 +00005004
John McCall28fc7092011-11-10 05:35:25 +00005005 // We need a cleanup, but we don't need to remember the temporary.
John McCall31168b02011-06-15 23:02:42 +00005006 ExprNeedsCleanups = true;
Richard Smithfd555f62012-02-22 02:04:18 +00005007 }
Richard Smitheec915d62012-02-18 04:13:32 +00005008
5009 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00005010 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
5011
5012 if (IsDecltype)
5013 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
5014
5015 return Owned(Bind);
Anders Carlsson2d4cada2009-05-30 20:36:53 +00005016}
5017
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005018ExprResult
John McCall5d413782010-12-06 08:20:24 +00005019Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005020 if (SubExpr.isInvalid())
5021 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005022
John McCall5d413782010-12-06 08:20:24 +00005023 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005024}
5025
John McCall28fc7092011-11-10 05:35:25 +00005026Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
5027 assert(SubExpr && "sub expression can't be null!");
5028
Eli Friedman3bda6b12012-02-02 23:15:15 +00005029 CleanupVarDeclMarking();
5030
John McCall28fc7092011-11-10 05:35:25 +00005031 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
5032 assert(ExprCleanupObjects.size() >= FirstCleanup);
5033 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
5034 if (!ExprNeedsCleanups)
5035 return SubExpr;
5036
5037 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
5038 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
5039 ExprCleanupObjects.size() - FirstCleanup);
5040
5041 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
5042 DiscardCleanupsInEvaluationContext();
5043
5044 return E;
5045}
5046
John McCall5d413782010-12-06 08:20:24 +00005047Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005048 assert(SubStmt && "sub statement can't be null!");
5049
Eli Friedman3bda6b12012-02-02 23:15:15 +00005050 CleanupVarDeclMarking();
5051
John McCall31168b02011-06-15 23:02:42 +00005052 if (!ExprNeedsCleanups)
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005053 return SubStmt;
5054
5055 // FIXME: In order to attach the temporaries, wrap the statement into
5056 // a StmtExpr; currently this is only used for asm statements.
5057 // This is hacky, either create a new CXXStmtWithTemporaries statement or
5058 // a new AsmStmtWithTemporaries.
Nico Webera2a0eb92012-12-29 20:03:39 +00005059 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005060 SourceLocation(),
5061 SourceLocation());
5062 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
5063 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00005064 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005065}
5066
Richard Smithfd555f62012-02-22 02:04:18 +00005067/// Process the expression contained within a decltype. For such expressions,
5068/// certain semantic checks on temporaries are delayed until this point, and
5069/// are omitted for the 'topmost' call in the decltype expression. If the
5070/// topmost call bound a temporary, strip that temporary off the expression.
5071ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005072 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00005073
5074 // C++11 [expr.call]p11:
5075 // If a function call is a prvalue of object type,
5076 // -- if the function call is either
5077 // -- the operand of a decltype-specifier, or
5078 // -- the right operand of a comma operator that is the operand of a
5079 // decltype-specifier,
5080 // a temporary object is not introduced for the prvalue.
5081
5082 // Recursively rebuild ParenExprs and comma expressions to strip out the
5083 // outermost CXXBindTemporaryExpr, if any.
5084 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5085 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
5086 if (SubExpr.isInvalid())
5087 return ExprError();
5088 if (SubExpr.get() == PE->getSubExpr())
5089 return Owned(E);
5090 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take());
5091 }
5092 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5093 if (BO->getOpcode() == BO_Comma) {
5094 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
5095 if (RHS.isInvalid())
5096 return ExprError();
5097 if (RHS.get() == BO->getRHS())
5098 return Owned(E);
5099 return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(),
5100 BO_Comma, BO->getType(),
5101 BO->getValueKind(),
5102 BO->getObjectKind(),
Lang Hames5de91cc2012-10-02 04:45:10 +00005103 BO->getOperatorLoc(),
5104 BO->isFPContractable()));
Richard Smithfd555f62012-02-22 02:04:18 +00005105 }
5106 }
5107
5108 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
5109 if (TopBind)
5110 E = TopBind->getSubExpr();
5111
5112 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005113 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00005114
Richard Smithf86b0ae2012-07-28 19:54:11 +00005115 // In MS mode, don't perform any extra checking of call return types within a
5116 // decltype expression.
5117 if (getLangOpts().MicrosoftMode)
5118 return Owned(E);
5119
Richard Smithfd555f62012-02-22 02:04:18 +00005120 // Perform the semantic checks we delayed until this point.
5121 CallExpr *TopCall = dyn_cast<CallExpr>(E);
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005122 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
5123 I != N; ++I) {
5124 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00005125 if (Call == TopCall)
5126 continue;
5127
5128 if (CheckCallReturnType(Call->getCallReturnType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005129 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00005130 Call, Call->getDirectCallee()))
5131 return ExprError();
5132 }
5133
5134 // Now all relevant types are complete, check the destructors are accessible
5135 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005136 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
5137 I != N; ++I) {
5138 CXXBindTemporaryExpr *Bind =
5139 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00005140 if (Bind == TopBind)
5141 continue;
5142
5143 CXXTemporary *Temp = Bind->getTemporary();
5144
5145 CXXRecordDecl *RD =
5146 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5147 CXXDestructorDecl *Destructor = LookupDestructor(RD);
5148 Temp->setDestructor(Destructor);
5149
Richard Smith7d847b12012-05-11 22:20:10 +00005150 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
5151 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00005152 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00005153 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00005154 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
5155 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00005156
5157 // We need a cleanup, but we don't need to remember the temporary.
5158 ExprNeedsCleanups = true;
5159 }
5160
5161 // Possibly strip off the top CXXBindTemporaryExpr.
5162 return Owned(E);
5163}
5164
Richard Smith79c927b2013-11-06 19:31:51 +00005165/// Note a set of 'operator->' functions that were used for a member access.
5166static void noteOperatorArrows(Sema &S,
5167 llvm::ArrayRef<FunctionDecl *> OperatorArrows) {
5168 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
5169 // FIXME: Make this configurable?
5170 unsigned Limit = 9;
5171 if (OperatorArrows.size() > Limit) {
5172 // Produce Limit-1 normal notes and one 'skipping' note.
5173 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
5174 SkipCount = OperatorArrows.size() - (Limit - 1);
5175 }
5176
5177 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
5178 if (I == SkipStart) {
5179 S.Diag(OperatorArrows[I]->getLocation(),
5180 diag::note_operator_arrows_suppressed)
5181 << SkipCount;
5182 I += SkipCount;
5183 } else {
5184 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
5185 << OperatorArrows[I]->getCallResultType();
5186 ++I;
5187 }
5188 }
5189}
5190
John McCalldadc5752010-08-24 06:29:42 +00005191ExprResult
John McCallb268a282010-08-23 23:25:46 +00005192Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallba7bf592010-08-24 05:47:05 +00005193 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00005194 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005195 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00005196 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00005197 if (Result.isInvalid()) return ExprError();
5198 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00005199
John McCall526ab472011-10-25 17:37:35 +00005200 Result = CheckPlaceholderExpr(Base);
5201 if (Result.isInvalid()) return ExprError();
5202 Base = Result.take();
5203
John McCallb268a282010-08-23 23:25:46 +00005204 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00005205 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005206 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00005207 // If we have a pointer to a dependent type and are using the -> operator,
5208 // the object type is the type that the pointer points to. We might still
5209 // have enough information about that type to do something useful.
5210 if (OpKind == tok::arrow)
5211 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
5212 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005213
John McCallba7bf592010-08-24 05:47:05 +00005214 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00005215 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00005216 return Owned(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005217 }
Mike Stump11289f42009-09-09 15:08:12 +00005218
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005219 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00005220 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005221 // returned, with the original second operand.
5222 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00005223 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005224 bool NoArrowOperatorFound = false;
5225 bool FirstIteration = true;
5226 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00005227 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00005228 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00005229 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00005230 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005231
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005232 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00005233 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
5234 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00005235 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00005236 noteOperatorArrows(*this, OperatorArrows);
5237 Diag(OpLoc, diag::note_operator_arrow_depth)
5238 << getLangOpts().ArrowDepth;
5239 return ExprError();
5240 }
5241
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005242 Result = BuildOverloadedArrowExpr(
5243 S, Base, OpLoc,
5244 // When in a template specialization and on the first loop iteration,
5245 // potentially give the default diagnostic (with the fixit in a
5246 // separate note) instead of having the error reported back to here
5247 // and giving a diagnostic with a fixit attached to the error itself.
5248 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
5249 ? 0
5250 : &NoArrowOperatorFound);
5251 if (Result.isInvalid()) {
5252 if (NoArrowOperatorFound) {
5253 if (FirstIteration) {
5254 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00005255 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005256 << FixItHint::CreateReplacement(OpLoc, ".");
5257 OpKind = tok::period;
5258 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00005259 }
5260 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5261 << BaseType << Base->getSourceRange();
5262 CallExpr *CE = dyn_cast<CallExpr>(Base);
5263 if (Decl *CD = (CE ? CE->getCalleeDecl() : 0)) {
5264 Diag(CD->getLocStart(),
5265 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005266 }
5267 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005268 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005269 }
John McCallb268a282010-08-23 23:25:46 +00005270 Base = Result.get();
5271 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00005272 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00005273 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00005274 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00005275 if (!CTypes.insert(CBaseType)) {
Richard Smith79c927b2013-11-06 19:31:51 +00005276 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
5277 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00005278 return ExprError();
5279 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005280 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005281 }
Mike Stump11289f42009-09-09 15:08:12 +00005282
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005283 if (OpKind == tok::arrow &&
5284 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00005285 BaseType = BaseType->getPointeeType();
5286 }
Mike Stump11289f42009-09-09 15:08:12 +00005287
Douglas Gregorbf3a8262012-01-12 16:11:24 +00005288 // Objective-C properties allow "." access on Objective-C pointer types,
5289 // so adjust the base type to the object type itself.
5290 if (BaseType->isObjCObjectPointerType())
5291 BaseType = BaseType->getPointeeType();
5292
5293 // C++ [basic.lookup.classref]p2:
5294 // [...] If the type of the object expression is of pointer to scalar
5295 // type, the unqualified-id is looked up in the context of the complete
5296 // postfix-expression.
5297 //
5298 // This also indicates that we could be parsing a pseudo-destructor-name.
5299 // Note that Objective-C class and object types can be pseudo-destructor
5300 // expressions or normal member (ivar or property) access expressions.
5301 if (BaseType->isObjCObjectOrInterfaceType()) {
5302 MayBePseudoDestructor = true;
5303 } else if (!BaseType->isRecordType()) {
John McCallba7bf592010-08-24 05:47:05 +00005304 ObjectType = ParsedType();
Douglas Gregore610ada2010-02-24 18:44:31 +00005305 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00005306 return Owned(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00005307 }
Mike Stump11289f42009-09-09 15:08:12 +00005308
Douglas Gregor3024f072012-04-16 07:05:22 +00005309 // The object type must be complete (or dependent), or
5310 // C++11 [expr.prim.general]p3:
5311 // Unlike the object expression in other contexts, *this is not required to
5312 // be of complete type for purposes of class member access (5.2.5) outside
5313 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00005314 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00005315 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005316 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00005317 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005318
Douglas Gregor2b6ca462009-09-03 21:38:09 +00005319 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005320 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00005321 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00005322 // type C (or of pointer to a class type C), the unqualified-id is looked
5323 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00005324 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005325 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005326}
5327
John McCalldadc5752010-08-24 06:29:42 +00005328ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCallb268a282010-08-23 23:25:46 +00005329 Expr *MemExpr) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005330 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCallb268a282010-08-23 23:25:46 +00005331 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
5332 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregora771f462010-03-31 17:46:05 +00005333 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005334
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005335 return ActOnCallExpr(/*Scope*/ 0,
John McCallb268a282010-08-23 23:25:46 +00005336 MemExpr,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005337 /*LPLoc*/ ExpectedLParenLoc,
Dmitri Gribenko78852e92013-05-05 20:40:26 +00005338 None,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005339 /*RPLoc*/ ExpectedLParenLoc);
5340}
Douglas Gregore610ada2010-02-24 18:44:31 +00005341
Eli Friedman6601b552012-01-25 04:29:24 +00005342static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00005343 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00005344 if (Base->hasPlaceholderType()) {
5345 ExprResult result = S.CheckPlaceholderExpr(Base);
5346 if (result.isInvalid()) return true;
5347 Base = result.take();
5348 }
5349 ObjectType = Base->getType();
5350
David Blaikie1d578782011-12-16 16:03:09 +00005351 // C++ [expr.pseudo]p2:
5352 // The left-hand side of the dot operator shall be of scalar type. The
5353 // left-hand side of the arrow operator shall be of pointer to scalar type.
5354 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00005355 // Note that this is rather different from the normal handling for the
5356 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00005357 if (OpKind == tok::arrow) {
5358 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
5359 ObjectType = Ptr->getPointeeType();
5360 } else if (!Base->isTypeDependent()) {
5361 // The user wrote "p->" when she probably meant "p."; fix it.
5362 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5363 << ObjectType << true
5364 << FixItHint::CreateReplacement(OpLoc, ".");
5365 if (S.isSFINAEContext())
5366 return true;
5367
5368 OpKind = tok::period;
5369 }
5370 }
5371
5372 return false;
5373}
5374
John McCalldadc5752010-08-24 06:29:42 +00005375ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00005376 SourceLocation OpLoc,
5377 tok::TokenKind OpKind,
5378 const CXXScopeSpec &SS,
5379 TypeSourceInfo *ScopeTypeInfo,
5380 SourceLocation CCLoc,
5381 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00005382 PseudoDestructorTypeStorage Destructed,
John McCalla2c4e722011-02-25 05:21:17 +00005383 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00005384 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005385
Eli Friedman0ce4de42012-01-25 04:35:06 +00005386 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00005387 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5388 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005389
Douglas Gregorc5c57342012-09-10 14:57:06 +00005390 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
5391 !ObjectType->isVectorType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005392 if (getLangOpts().MicrosoftMode && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00005393 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Nico Weber58829272012-01-23 05:50:57 +00005394 else
5395 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
5396 << ObjectType << Base->getSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005397 return ExprError();
5398 }
5399
5400 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005401 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005402 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00005403 if (DestructedTypeInfo) {
5404 QualType DestructedType = DestructedTypeInfo->getType();
5405 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00005406 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00005407 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
5408 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
5409 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
5410 << ObjectType << DestructedType << Base->getSourceRange()
5411 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005412
John McCall31168b02011-06-15 23:02:42 +00005413 // Recover by setting the destructed type to the object type.
5414 DestructedType = ObjectType;
5415 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregor678f90d2010-02-25 01:56:36 +00005416 DestructedTypeStart);
John McCall31168b02011-06-15 23:02:42 +00005417 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5418 } else if (DestructedType.getObjCLifetime() !=
5419 ObjectType.getObjCLifetime()) {
5420
5421 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
5422 // Okay: just pretend that the user provided the correctly-qualified
5423 // type.
5424 } else {
5425 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
5426 << ObjectType << DestructedType << Base->getSourceRange()
5427 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5428 }
5429
5430 // Recover by setting the destructed type to the object type.
5431 DestructedType = ObjectType;
5432 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5433 DestructedTypeStart);
5434 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5435 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00005436 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005437 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005438
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005439 // C++ [expr.pseudo]p2:
5440 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
5441 // form
5442 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005443 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005444 //
5445 // shall designate the same scalar type.
5446 if (ScopeTypeInfo) {
5447 QualType ScopeType = ScopeTypeInfo->getType();
5448 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00005449 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005450
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00005451 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005452 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00005453 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00005454 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005455
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005456 ScopeType = QualType();
5457 ScopeTypeInfo = 0;
5458 }
5459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005460
John McCallb268a282010-08-23 23:25:46 +00005461 Expr *Result
5462 = new (Context) CXXPseudoDestructorExpr(Context, Base,
5463 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00005464 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00005465 ScopeTypeInfo,
5466 CCLoc,
5467 TildeLoc,
5468 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005469
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005470 if (HasTrailingLParen)
John McCallb268a282010-08-23 23:25:46 +00005471 return Owned(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005472
John McCallb268a282010-08-23 23:25:46 +00005473 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005474}
5475
John McCalldadc5752010-08-24 06:29:42 +00005476ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00005477 SourceLocation OpLoc,
5478 tok::TokenKind OpKind,
5479 CXXScopeSpec &SS,
5480 UnqualifiedId &FirstTypeName,
5481 SourceLocation CCLoc,
5482 SourceLocation TildeLoc,
5483 UnqualifiedId &SecondTypeName,
5484 bool HasTrailingLParen) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005485 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5486 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5487 "Invalid first type name in pseudo-destructor");
5488 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5489 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5490 "Invalid second type name in pseudo-destructor");
5491
Eli Friedman0ce4de42012-01-25 04:35:06 +00005492 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00005493 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5494 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00005495
5496 // Compute the object type that we should use for name lookup purposes. Only
5497 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00005498 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00005499 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00005500 if (ObjectType->isRecordType())
5501 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00005502 else if (ObjectType->isDependentType())
5503 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00005504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005505
5506 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005507 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005508 QualType DestructedType;
5509 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00005510 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005511 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005512 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00005513 SecondTypeName.StartLocation,
Fariborz Jahanian87967422011-02-08 18:05:59 +00005514 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005515 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00005516 ((SS.isSet() && !computeDeclContext(SS, false)) ||
5517 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005518 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00005519 // couldn't find anything useful in scope. Just store the identifier and
5520 // it's location, and we'll perform (qualified) name lookup again at
5521 // template instantiation time.
5522 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5523 SecondTypeName.StartLocation);
5524 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005525 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005526 diag::err_pseudo_dtor_destructor_non_type)
5527 << SecondTypeName.Identifier << ObjectType;
5528 if (isSFINAEContext())
5529 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005530
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005531 // Recover by assuming we had the right type all along.
5532 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005533 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005534 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005535 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005536 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005537 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005538 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005539 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00005540 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00005541 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00005542 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005543 TemplateId->TemplateNameLoc,
5544 TemplateId->LAngleLoc,
5545 TemplateArgsPtr,
5546 TemplateId->RAngleLoc);
5547 if (T.isInvalid() || !T.get()) {
5548 // Recover by assuming we had the right type all along.
5549 DestructedType = ObjectType;
5550 } else
5551 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005553
5554 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005555 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00005556 if (!DestructedType.isNull()) {
5557 if (!DestructedTypeInfo)
5558 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005559 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00005560 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5561 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005562
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005563 // Convert the name of the scope type (the type prior to '::') into a type.
5564 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005565 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005566 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005567 FirstTypeName.Identifier) {
5568 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005569 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00005570 FirstTypeName.StartLocation,
Douglas Gregora6ce6082011-02-25 18:19:59 +00005571 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005572 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005573 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005574 diag::err_pseudo_dtor_destructor_non_type)
5575 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005576
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005577 if (isSFINAEContext())
5578 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005579
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005580 // Just drop this type. It's unnecessary anyway.
5581 ScopeType = QualType();
5582 } else
5583 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005584 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005585 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005586 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005587 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005588 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00005589 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00005590 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00005591 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005592 TemplateId->TemplateNameLoc,
5593 TemplateId->LAngleLoc,
5594 TemplateArgsPtr,
5595 TemplateId->RAngleLoc);
5596 if (T.isInvalid() || !T.get()) {
5597 // Recover by dropping this type.
5598 ScopeType = QualType();
5599 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005600 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005601 }
5602 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005603
Douglas Gregor90ad9222010-02-24 23:02:30 +00005604 if (!ScopeType.isNull() && !ScopeTypeInfo)
5605 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5606 FirstTypeName.StartLocation);
5607
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005608
John McCallb268a282010-08-23 23:25:46 +00005609 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00005610 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00005611 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00005612}
5613
David Blaikie1d578782011-12-16 16:03:09 +00005614ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5615 SourceLocation OpLoc,
5616 tok::TokenKind OpKind,
5617 SourceLocation TildeLoc,
5618 const DeclSpec& DS,
5619 bool HasTrailingLParen) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00005620 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00005621 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5622 return ExprError();
5623
5624 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5625
5626 TypeLocBuilder TLB;
5627 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5628 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5629 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5630 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5631
5632 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5633 0, SourceLocation(), TildeLoc,
5634 Destructed, HasTrailingLParen);
5635}
5636
John Wiegley01296292011-04-08 18:41:53 +00005637ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00005638 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005639 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00005640 if (Method->getParent()->isLambda() &&
5641 Method->getConversionType()->isBlockPointerType()) {
5642 // This is a lambda coversion to block pointer; check if the argument
5643 // is a LambdaExpr.
5644 Expr *SubE = E;
5645 CastExpr *CE = dyn_cast<CastExpr>(SubE);
5646 if (CE && CE->getCastKind() == CK_NoOp)
5647 SubE = CE->getSubExpr();
5648 SubE = SubE->IgnoreParens();
5649 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5650 SubE = BE->getSubExpr();
5651 if (isa<LambdaExpr>(SubE)) {
5652 // For the conversion to block pointer on a lambda expression, we
5653 // construct a special BlockLiteral instead; this doesn't really make
5654 // a difference in ARC, but outside of ARC the resulting block literal
5655 // follows the normal lifetime rules for block literals instead of being
5656 // autoreleased.
5657 DiagnosticErrorTrap Trap(Diags);
5658 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5659 E->getExprLoc(),
5660 Method, E);
5661 if (Exp.isInvalid())
5662 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5663 return Exp;
5664 }
5665 }
5666
5667
John Wiegley01296292011-04-08 18:41:53 +00005668 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
5669 FoundDecl, Method);
5670 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00005671 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00005672
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005673 MemberExpr *ME =
John Wiegley01296292011-04-08 18:41:53 +00005674 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005675 SourceLocation(), Context.BoundMemberTy,
John McCall7decc9e2010-11-18 06:31:45 +00005676 VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005677 if (HadMultipleCandidates)
5678 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00005679 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005680
John McCall7decc9e2010-11-18 06:31:45 +00005681 QualType ResultType = Method->getResultType();
5682 ExprValueKind VK = Expr::getValueKindForType(ResultType);
5683 ResultType = ResultType.getNonLValueExprType(Context);
5684
Douglas Gregor27381f32009-11-23 12:27:39 +00005685 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00005686 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00005687 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005688 return CE;
5689}
5690
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005691ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5692 SourceLocation RParen) {
Richard Smithf623c962012-04-17 00:58:00 +00005693 CanThrowResult CanThrow = canThrow(Operand);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005694 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
Richard Smithf623c962012-04-17 00:58:00 +00005695 CanThrow, KeyLoc, RParen));
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005696}
5697
5698ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5699 Expr *Operand, SourceLocation RParen) {
5700 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00005701}
5702
Eli Friedmanf798f652012-05-24 22:04:19 +00005703static bool IsSpecialDiscardedValue(Expr *E) {
5704 // In C++11, discarded-value expressions of a certain form are special,
5705 // according to [expr]p10:
5706 // The lvalue-to-rvalue conversion (4.1) is applied only if the
5707 // expression is an lvalue of volatile-qualified type and it has
5708 // one of the following forms:
5709 E = E->IgnoreParens();
5710
Eli Friedmanc49c2262012-05-24 22:36:31 +00005711 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00005712 if (isa<DeclRefExpr>(E))
5713 return true;
5714
Eli Friedmanc49c2262012-05-24 22:36:31 +00005715 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00005716 if (isa<ArraySubscriptExpr>(E))
5717 return true;
5718
Eli Friedmanc49c2262012-05-24 22:36:31 +00005719 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00005720 if (isa<MemberExpr>(E))
5721 return true;
5722
Eli Friedmanc49c2262012-05-24 22:36:31 +00005723 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00005724 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
5725 if (UO->getOpcode() == UO_Deref)
5726 return true;
5727
5728 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00005729 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00005730 if (BO->isPtrMemOp())
5731 return true;
5732
Eli Friedmanc49c2262012-05-24 22:36:31 +00005733 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00005734 if (BO->getOpcode() == BO_Comma)
5735 return IsSpecialDiscardedValue(BO->getRHS());
5736 }
5737
Eli Friedmanc49c2262012-05-24 22:36:31 +00005738 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00005739 // operands are one of the above, or
5740 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
5741 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
5742 IsSpecialDiscardedValue(CO->getFalseExpr());
5743 // The related edge case of "*x ?: *x".
5744 if (BinaryConditionalOperator *BCO =
5745 dyn_cast<BinaryConditionalOperator>(E)) {
5746 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
5747 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
5748 IsSpecialDiscardedValue(BCO->getFalseExpr());
5749 }
5750
5751 // Objective-C++ extensions to the rule.
5752 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
5753 return true;
5754
5755 return false;
5756}
5757
John McCall34376a62010-12-04 03:47:34 +00005758/// Perform the conversions required for an expression used in a
5759/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00005760ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00005761 if (E->hasPlaceholderType()) {
5762 ExprResult result = CheckPlaceholderExpr(E);
5763 if (result.isInvalid()) return Owned(E);
5764 E = result.take();
5765 }
5766
John McCallfee942d2010-12-02 02:07:15 +00005767 // C99 6.3.2.1:
5768 // [Except in specific positions,] an lvalue that does not have
5769 // array type is converted to the value stored in the
5770 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00005771 if (E->isRValue()) {
5772 // In C, function designators (i.e. expressions of function type)
5773 // are r-values, but we still want to do function-to-pointer decay
5774 // on them. This is both technically correct and convenient for
5775 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005776 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00005777 return DefaultFunctionArrayConversion(E);
5778
5779 return Owned(E);
5780 }
John McCallfee942d2010-12-02 02:07:15 +00005781
Eli Friedmanf798f652012-05-24 22:04:19 +00005782 if (getLangOpts().CPlusPlus) {
5783 // The C++11 standard defines the notion of a discarded-value expression;
5784 // normally, we don't need to do anything to handle it, but if it is a
5785 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
5786 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00005787 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00005788 E->getType().isVolatileQualified() &&
5789 IsSpecialDiscardedValue(E)) {
5790 ExprResult Res = DefaultLvalueConversion(E);
5791 if (Res.isInvalid())
5792 return Owned(E);
5793 E = Res.take();
Faisal Valia17d19f2013-11-07 05:17:06 +00005794 }
Eli Friedmanf798f652012-05-24 22:04:19 +00005795 return Owned(E);
5796 }
John McCall34376a62010-12-04 03:47:34 +00005797
5798 // GCC seems to also exclude expressions of incomplete enum type.
5799 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5800 if (!T->getDecl()->isComplete()) {
5801 // FIXME: stupid workaround for a codegen bug!
John Wiegley01296292011-04-08 18:41:53 +00005802 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
5803 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00005804 }
5805 }
5806
John Wiegley01296292011-04-08 18:41:53 +00005807 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5808 if (Res.isInvalid())
5809 return Owned(E);
5810 E = Res.take();
5811
John McCallca61b652010-12-04 12:29:11 +00005812 if (!E->getType()->isVoidType())
5813 RequireCompleteType(E->getExprLoc(), E->getType(),
5814 diag::err_incomplete_type);
John Wiegley01296292011-04-08 18:41:53 +00005815 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00005816}
5817
Faisal Valia17d19f2013-11-07 05:17:06 +00005818// If we can unambiguously determine whether Var can never be used
5819// in a constant expression, return true.
5820// - if the variable and its initializer are non-dependent, then
5821// we can unambiguously check if the variable is a constant expression.
5822// - if the initializer is not value dependent - we can determine whether
5823// it can be used to initialize a constant expression. If Init can not
5824// be used to initialize a constant expression we conclude that Var can
5825// never be a constant expression.
5826// - FXIME: if the initializer is dependent, we can still do some analysis and
5827// identify certain cases unambiguously as non-const by using a Visitor:
5828// - such as those that involve odr-use of a ParmVarDecl, involve a new
5829// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
5830static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
5831 ASTContext &Context) {
5832 if (isa<ParmVarDecl>(Var)) return true;
5833 const VarDecl *DefVD = 0;
5834
5835 // If there is no initializer - this can not be a constant expression.
5836 if (!Var->getAnyInitializer(DefVD)) return true;
5837 assert(DefVD);
5838 if (DefVD->isWeak()) return false;
5839 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
5840
5841 Expr *Init = cast<Expr>(Eval->Value);
5842
5843 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
5844 if (!Init->isValueDependent())
5845 return !DefVD->checkInitIsICE();
5846 // FIXME: We might still be able to do some analysis of Init here
5847 // to conclude that even in a dependent setting, Init can never
5848 // be a constexpr - but for now admit agnosticity.
5849 return false;
5850 }
5851 return !IsVariableAConstantExpression(Var, Context);
5852}
5853
5854/// \brief Check if the current lambda scope has any potential captures, and
5855/// whether they can be captured by any of the enclosing lambdas that are
5856/// ready to capture. If there is a lambda that can capture a nested
5857/// potential-capture, go ahead and do so. Also, check to see if any
5858/// variables are uncaptureable or do not involve an odr-use so do not
5859/// need to be captured.
5860
5861static void CheckLambdaCaptures(Expr *const FE,
5862 LambdaScopeInfo *const CurrentLSI, Sema &S) {
5863
5864 assert(!S.isUnevaluatedContext());
5865 assert(S.CurContext->isDependentContext());
5866 const bool IsFullExprInstantiationDependent =
5867 FE->isInstantiationDependent();
5868 // All the potentially captureable variables in the current nested
5869 // lambda (within a generic outer lambda), must be captured by an
5870 // outer lambda that is enclosed within a non-dependent context.
5871
5872 for (size_t I = 0, N = CurrentLSI->getNumPotentialVariableCaptures();
5873 I != N; ++I) {
5874 Expr *VarExpr = 0;
5875 VarDecl *Var = 0;
5876 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
5877 //
5878 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
5879 !IsFullExprInstantiationDependent)
5880 continue;
5881 // Climb up until we find a lambda that can capture:
5882 // - a generic-or-non-generic lambda call operator that is enclosed
5883 // within a non-dependent context.
5884 unsigned FunctionScopeIndexOfCapturableLambda = 0;
David Blaikief84a1052013-11-07 05:52:35 +00005885 if (GetInnermostEnclosingCapturableLambda(
5886 S.FunctionScopes, FunctionScopeIndexOfCapturableLambda,
5887 S.CurContext, Var, S)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00005888 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(),
5889 S, &FunctionScopeIndexOfCapturableLambda);
5890 }
5891 const bool IsVarNeverAConstantExpression =
5892 VariableCanNeverBeAConstantExpression(Var, S.Context);
5893 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
5894 // This full expression is not instantiation dependent or the variable
5895 // can not be used in a constant expression - which means
5896 // this variable must be odr-used here, so diagnose a
5897 // capture violation early, if the variable is un-captureable.
5898 // This is purely for diagnosing errors early. Otherwise, this
5899 // error would get diagnosed when the lambda becomes capture ready.
5900 QualType CaptureType, DeclRefType;
5901 SourceLocation ExprLoc = VarExpr->getExprLoc();
5902 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
5903 /*EllipsisLoc*/ SourceLocation(),
5904 /*BuildAndDiagnose*/false, CaptureType,
5905 DeclRefType, 0)) {
5906 // We will never be able to capture this variable, and we need
5907 // to be able to in any and all instantiations, so diagnose it.
5908 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
5909 /*EllipsisLoc*/ SourceLocation(),
5910 /*BuildAndDiagnose*/true, CaptureType,
5911 DeclRefType, 0);
5912 }
5913 }
5914 }
5915
5916 if (CurrentLSI->hasPotentialThisCapture()) {
5917 unsigned FunctionScopeIndexOfCapturableLambda = 0;
David Blaikief84a1052013-11-07 05:52:35 +00005918 if (GetInnermostEnclosingCapturableLambda(
5919 S.FunctionScopes, FunctionScopeIndexOfCapturableLambda,
5920 S.CurContext, /*0 is 'this'*/ 0, S)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00005921 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
5922 /*Explicit*/false, /*BuildAndDiagnose*/true,
5923 &FunctionScopeIndexOfCapturableLambda);
5924 }
5925 }
5926 CurrentLSI->clearPotentialCaptures();
5927}
5928
5929
Richard Smith945f8d32013-01-14 22:39:08 +00005930ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005931 bool DiscardedValue,
5932 bool IsConstexpr) {
John Wiegley01296292011-04-08 18:41:53 +00005933 ExprResult FullExpr = Owned(FE);
5934
5935 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00005936 return ExprError();
John McCall34376a62010-12-04 03:47:34 +00005937
John Wiegley01296292011-04-08 18:41:53 +00005938 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00005939 return ExprError();
5940
Douglas Gregorb5af2e92013-03-07 22:57:58 +00005941 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00005942 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00005943 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Douglas Gregor95715f92011-12-15 00:53:32 +00005944 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
5945 if (FullExpr.isInvalid())
5946 return ExprError();
5947 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00005948
Richard Smith945f8d32013-01-14 22:39:08 +00005949 if (DiscardedValue) {
5950 FullExpr = CheckPlaceholderExpr(FullExpr.take());
5951 if (FullExpr.isInvalid())
5952 return ExprError();
5953
5954 FullExpr = IgnoredValueConversions(FullExpr.take());
5955 if (FullExpr.isInvalid())
5956 return ExprError();
5957 }
John Wiegley01296292011-04-08 18:41:53 +00005958
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005959 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00005960
Faisal Vali218e94b2013-11-12 03:56:08 +00005961 // At the end of this full expression (which could be a deeply nested
5962 // lambda), if there is a potential capture within the nested lambda,
5963 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00005964 // Consider the following code:
5965 // void f(int, int);
5966 // void f(const int&, double);
5967 // void foo() {
5968 // const int x = 10, y = 20;
5969 // auto L = [=](auto a) {
5970 // auto M = [=](auto b) {
5971 // f(x, b); <-- requires x to be captured by L and M
5972 // f(y, a); <-- requires y to be captured by L, but not all Ms
5973 // };
5974 // };
5975 // }
5976
5977 // FIXME: Also consider what happens for something like this that involves
5978 // the gnu-extension statement-expressions or even lambda-init-captures:
5979 // void f() {
5980 // const int n = 0;
5981 // auto L = [&](auto a) {
5982 // +n + ({ 0; a; });
5983 // };
5984 // }
5985 //
Faisal Vali218e94b2013-11-12 03:56:08 +00005986 // Here, we see +n, and then the full-expression 0; ends, so we don't
5987 // capture n (and instead remove it from our list of potential captures),
5988 // and then the full-expression +n + ({ 0; }); ends, but it's too late
5989 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00005990
Faisal Vali8bc2bc72013-11-12 03:48:27 +00005991 LambdaScopeInfo *const CurrentLSI = getCurLambda();
5992 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
5993 // even if CurContext is not a lambda call operator. Refer to that Bug Report
5994 // for an example of the code that might cause this asynchrony.
5995 // By ensuring we are in the context of a lambda's call operator
5996 // we can fix the bug (we only need to check whether we need to capture
5997 // if we are within a lambda's body); but per the comments in that
5998 // PR, a proper fix would entail :
5999 // "Alternative suggestion:
6000 // - Add to Sema an integer holding the smallest (outermost) scope
6001 // index that we are *lexically* within, and save/restore/set to
6002 // FunctionScopes.size() in InstantiatingTemplate's
6003 // constructor/destructor.
6004 // - Teach the handful of places that iterate over FunctionScopes to
6005 // stop at the outermost enclosing lexical scope."
6006 const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
6007 if (IsInLambdaDeclContext && CurrentLSI &&
6008 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valia17d19f2013-11-07 05:17:06 +00006009 CheckLambdaCaptures(FE, CurrentLSI, *this);
John McCall5d413782010-12-06 08:20:24 +00006010 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00006011}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006012
6013StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
6014 if (!FullStmt) return StmtError();
6015
John McCall5d413782010-12-06 08:20:24 +00006016 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006017}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00006018
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006019Sema::IfExistsResult
6020Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
6021 CXXScopeSpec &SS,
6022 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00006023 DeclarationName TargetName = TargetNameInfo.getName();
6024 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00006025 return IER_DoesNotExist;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006026
Douglas Gregor43edb322011-10-24 22:31:10 +00006027 // If the name itself is dependent, then the result is dependent.
6028 if (TargetName.isDependentName())
6029 return IER_Dependent;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006030
Francois Pichet4a7de3e2011-05-06 20:48:22 +00006031 // Do the redeclaration lookup in the current scope.
6032 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
6033 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00006034 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00006035 R.suppressDiagnostics();
Douglas Gregor43edb322011-10-24 22:31:10 +00006036
6037 switch (R.getResultKind()) {
6038 case LookupResult::Found:
6039 case LookupResult::FoundOverloaded:
6040 case LookupResult::FoundUnresolvedValue:
6041 case LookupResult::Ambiguous:
6042 return IER_Exists;
6043
6044 case LookupResult::NotFound:
6045 return IER_DoesNotExist;
6046
6047 case LookupResult::NotFoundInCurrentInstantiation:
6048 return IER_Dependent;
6049 }
David Blaikie8a40f702012-01-17 06:56:22 +00006050
6051 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00006052}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006053
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00006054Sema::IfExistsResult
6055Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
6056 bool IsIfExists, CXXScopeSpec &SS,
6057 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006058 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00006059
6060 // Check for unexpanded parameter packs.
6061 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
6062 collectUnexpandedParameterPacks(SS, Unexpanded);
6063 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
6064 if (!Unexpanded.empty()) {
6065 DiagnoseUnexpandedParameterPacks(KeywordLoc,
6066 IsIfExists? UPPC_IfExists
6067 : UPPC_IfNotExists,
6068 Unexpanded);
6069 return IER_Error;
6070 }
6071
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006072 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
6073}