blob: 56f593439d7a99410cf9e8376f0bcce9111d552d [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"
Kaelyn Takata6c759512014-10-27 18:07:37 +000016#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "TypeLocBuilder.h"
Steve Naroffaac94152007-08-25 14:02:58 +000018#include "clang/AST/ASTContext.h"
Faisal Vali47d9ed42014-05-30 04:39:37 +000019#include "clang/AST/ASTLambda.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/CharUnits.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000036#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000038#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000040#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000041using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000042using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000043
Richard Smith7447af42013-03-26 01:15:19 +000044/// \brief Handle the result of the special case name lookup for inheriting
45/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46/// constructor names in member using declarations, even if 'X' is not the
47/// name of the corresponding type.
48ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49 SourceLocation NameLoc,
50 IdentifierInfo &Name) {
51 NestedNameSpecifier *NNS = SS.getScopeRep();
52
53 // Convert the nested-name-specifier into a type.
54 QualType Type;
55 switch (NNS->getKind()) {
56 case NestedNameSpecifier::TypeSpec:
57 case NestedNameSpecifier::TypeSpecWithTemplate:
58 Type = QualType(NNS->getAsType(), 0);
59 break;
60
61 case NestedNameSpecifier::Identifier:
62 // Strip off the last layer of the nested-name-specifier and build a
63 // typename type for it.
64 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66 NNS->getAsIdentifier());
67 break;
68
69 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000070 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000071 case NestedNameSpecifier::Namespace:
72 case NestedNameSpecifier::NamespaceAlias:
73 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
74 }
75
76 // This reference to the type is located entirely at the location of the
77 // final identifier in the qualified-id.
78 return CreateParsedType(Type,
79 Context.getTrivialTypeSourceInfo(Type, NameLoc));
80}
81
John McCallba7bf592010-08-24 05:47:05 +000082ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000083 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000084 SourceLocation NameLoc,
85 Scope *S, CXXScopeSpec &SS,
86 ParsedType ObjectTypePtr,
87 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000088 // Determine where to perform name lookup.
89
90 // FIXME: This area of the standard is very messy, and the current
91 // wording is rather unclear about which scopes we search for the
92 // destructor name; see core issues 399 and 555. Issue 399 in
93 // particular shows where the current description of destructor name
94 // lookup is completely out of line with existing practice, e.g.,
95 // this appears to be ill-formed:
96 //
97 // namespace N {
98 // template <typename T> struct S {
99 // ~S();
100 // };
101 // }
102 //
103 // void f(N::S<int>* s) {
104 // s->N::S<int>::~S();
105 // }
106 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000107 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000108 // For this reason, we're currently only doing the C++03 version of this
109 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000110 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000111 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000112 bool isDependent = false;
113 bool LookInScope = false;
114
Richard Smith64e033f2015-01-15 00:48:52 +0000115 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000116 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000117
Douglas Gregorfe17d252010-02-16 19:09:40 +0000118 // If we have an object type, it's because we are in a
119 // pseudo-destructor-expression or a member access expression, and
120 // we know what type we're looking for.
121 if (ObjectTypePtr)
122 SearchType = GetTypeFromParser(ObjectTypePtr);
123
124 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000125 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000126
Douglas Gregor46841e12010-02-23 00:15:22 +0000127 bool AlreadySearched = false;
128 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000129 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000130 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000131 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000132 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000133 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000134 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000135 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000136 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000137 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000138 // Here, we determine whether the code below is permitted to look at the
139 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000140 DeclContext *DC = computeDeclContext(SS, EnteringContext);
141 if (DC && DC->isFileContext()) {
142 AlreadySearched = true;
143 LookupCtx = DC;
144 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000145 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000146 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000147 LookInScope = true;
148 }
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.
Craig Topperc3ec1492014-05-26 06:22:03 +0000151 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000152 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 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000166 } else if (ObjectTypePtr) {
167 // C++ [basic.lookup.classref]p3:
168 // If the unqualified-id is ~type-name, the type-name is looked up
169 // in the context of the entire postfix-expression. If the type T
170 // of the object expression is of a class type C, the type-name is
171 // also looked up in the scope of class C. At least one of the
172 // lookups shall find a name that refers to (possibly
173 // cv-qualified) T.
174 LookupCtx = computeDeclContext(SearchType);
175 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000176 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000177 "Caller should have completed object type");
178
179 LookInScope = true;
180 } else {
181 // Perform lookup into the current scope (only).
182 LookInScope = true;
183 }
184
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000186 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
187 for (unsigned Step = 0; Step != 2; ++Step) {
188 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000189 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000190 // we're allowed to look there).
191 Found.clear();
192 if (Step == 0 && LookupCtx)
193 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000194 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000195 LookupName(Found, S);
196 else
197 continue;
198
199 // FIXME: Should we be suppressing ambiguities here?
200 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000201 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000202
203 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
204 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000205 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000206
207 if (SearchType.isNull() || SearchType->isDependentType() ||
208 Context.hasSameUnqualifiedType(T, SearchType)) {
209 // We found our type!
210
Richard Smithc278c002014-01-22 00:30:17 +0000211 return CreateParsedType(T,
212 Context.getTrivialTypeSourceInfo(T, NameLoc));
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())
Richard Smithc278c002014-01-22 00:30:17 +0000248 return CreateParsedType(
249 MemberOfType,
250 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000251 }
252
253 continue;
254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000255
Douglas Gregorfe17d252010-02-16 19:09:40 +0000256 // We're referring to an unresolved class template
257 // specialization. Determine whether we class template we found
258 // is the same as the template being specialized or, if we don't
259 // know which template is being specialized, that it at least
260 // has the same name.
261 if (const TemplateSpecializationType *SpecType
262 = MemberOfType->getAs<TemplateSpecializationType>()) {
263 TemplateName SpecName = SpecType->getTemplateName();
264
265 // The class template we found is the same template being
266 // specialized.
267 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
268 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000269 return CreateParsedType(
270 MemberOfType,
271 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000272
273 continue;
274 }
275
276 // The class template we found has the same name as the
277 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000279 = SpecName.getAsDependentTemplateName()) {
280 if (DepTemplate->isIdentifier() &&
281 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000282 return CreateParsedType(
283 MemberOfType,
284 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000285
286 continue;
287 }
288 }
289 }
290 }
291
292 if (isDependent) {
293 // We didn't find our type, but that's okay: it's dependent
294 // anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000295
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000296 // FIXME: What if we have no nested-name-specifier?
297 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
298 SS.getWithLocInContext(Context),
299 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000300 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000301 }
302
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000303 if (NonMatchingTypeDecl) {
304 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
305 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
306 << T << SearchType;
307 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
308 << T;
309 } else if (ObjectTypePtr)
310 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000311 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000312 else {
313 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
314 diag::err_destructor_class_name);
315 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000316 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000317 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
318 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
319 Class->getNameAsString());
320 }
321 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000322
David Blaikieefdccaa2016-01-15 23:43:34 +0000323 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000324}
325
David Blaikieecd8a942011-12-08 16:13:53 +0000326ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie08608f62011-12-12 04:13:55 +0000327 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikieefdccaa2016-01-15 23:43:34 +0000328 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000329 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
David Blaikieecd8a942011-12-08 16:13:53 +0000330 && "only get destructor types from declspecs");
331 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
332 QualType SearchType = GetTypeFromParser(ObjectType);
333 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
334 return ParsedType::make(T);
335 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000336
David Blaikieecd8a942011-12-08 16:13:53 +0000337 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
338 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000339 return nullptr;
David Blaikieecd8a942011-12-08 16:13:53 +0000340}
341
Richard Smithd091dc12013-12-05 00:58:33 +0000342bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
343 const UnqualifiedId &Name) {
344 assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
345
346 if (!SS.isValid())
347 return false;
348
349 switch (SS.getScopeRep()->getKind()) {
350 case NestedNameSpecifier::Identifier:
351 case NestedNameSpecifier::TypeSpec:
352 case NestedNameSpecifier::TypeSpecWithTemplate:
353 // Per C++11 [over.literal]p2, literal operators can only be declared at
354 // namespace scope. Therefore, this unqualified-id cannot name anything.
355 // Reject it early, because we have no AST representation for this in the
356 // case where the scope is dependent.
357 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
358 << SS.getScopeRep();
359 return true;
360
361 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000362 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000363 case NestedNameSpecifier::Namespace:
364 case NestedNameSpecifier::NamespaceAlias:
365 return false;
366 }
367
368 llvm_unreachable("unknown nested name specifier kind");
369}
370
Douglas Gregor9da64192010-04-26 22:37:10 +0000371/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000372ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000373 SourceLocation TypeidLoc,
374 TypeSourceInfo *Operand,
375 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000376 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000377 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000378 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000379 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000380 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000381 Qualifiers Quals;
382 QualType T
383 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
384 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000385 if (T->getAs<RecordType>() &&
386 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
387 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388
David Majnemer6f3150a2014-11-21 21:09:12 +0000389 if (T->isVariablyModifiedType())
390 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
391
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000392 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
393 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000394}
395
396/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000397ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000398 SourceLocation TypeidLoc,
399 Expr *E,
400 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000401 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000402 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000403 if (E->getType()->isPlaceholderType()) {
404 ExprResult result = CheckPlaceholderExpr(E);
405 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000406 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000407 }
408
Douglas Gregor9da64192010-04-26 22:37:10 +0000409 QualType T = E->getType();
410 if (const RecordType *RecordT = T->getAs<RecordType>()) {
411 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
412 // C++ [expr.typeid]p3:
413 // [...] If the type of the expression is a class type, the class
414 // shall be completely-defined.
415 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
416 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417
Douglas Gregor9da64192010-04-26 22:37:10 +0000418 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000419 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000420 // polymorphic class type [...] [the] expression is an unevaluated
421 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000422 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000423 // The subexpression is potentially evaluated; switch the context
424 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000425 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000426 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000427 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000428
429 // We require a vtable to query the type at run time.
430 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000431 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000432 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000433 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000434
Douglas Gregor9da64192010-04-26 22:37:10 +0000435 // C++ [expr.typeid]p4:
436 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000437 // cv-qualified type, the result of the typeid expression refers to a
438 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000439 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000440 Qualifiers Quals;
441 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
442 if (!Context.hasSameType(T, UnqualT)) {
443 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000444 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000445 }
446 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000447
David Majnemer6f3150a2014-11-21 21:09:12 +0000448 if (E->getType()->isVariablyModifiedType())
449 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
450 << E->getType());
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000451 else if (ActiveTemplateInstantiations.empty() &&
452 E->HasSideEffects(Context, WasEvaluated)) {
453 // The expression operand for typeid is in an unevaluated expression
454 // context, so side effects could result in unintended consequences.
455 Diag(E->getExprLoc(), WasEvaluated
456 ? diag::warn_side_effects_typeid
457 : diag::warn_side_effects_unevaluated_context);
458 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000459
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000460 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
461 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000462}
463
464/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000465ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000466Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
467 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000468 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000469 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000470 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000471
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000472 if (!CXXTypeInfoDecl) {
473 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
474 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
475 LookupQualifiedName(R, getStdNamespace());
476 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000477 // Microsoft's typeinfo doesn't have type_info in std but in the global
478 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000479 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000480 LookupQualifiedName(R, Context.getTranslationUnitDecl());
481 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
482 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000483 if (!CXXTypeInfoDecl)
484 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000486
Nico Weber1b7f39d2012-05-20 01:27:21 +0000487 if (!getLangOpts().RTTI) {
488 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
489 }
490
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000491 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000492
Douglas Gregor9da64192010-04-26 22:37:10 +0000493 if (isType) {
494 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000495 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000496 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
497 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000498 if (T.isNull())
499 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
Douglas Gregor9da64192010-04-26 22:37:10 +0000501 if (!TInfo)
502 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000503
Douglas Gregor9da64192010-04-26 22:37:10 +0000504 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000505 }
Mike Stump11289f42009-09-09 15:08:12 +0000506
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000508 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000509}
510
David Majnemer1dbc7a72016-03-27 04:46:07 +0000511/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
512/// a single GUID.
513static void
514getUuidAttrOfType(Sema &SemaRef, QualType QT,
515 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
516 // Optionally remove one level of pointer, reference or array indirection.
517 const Type *Ty = QT.getTypePtr();
518 if (QT->isPointerType() || QT->isReferenceType())
519 Ty = QT->getPointeeType().getTypePtr();
520 else if (QT->isArrayType())
521 Ty = Ty->getBaseElementTypeUnsafe();
522
523 const auto *RD = Ty->getAsCXXRecordDecl();
524 if (!RD)
525 return;
526
527 if (const auto *Uuid = RD->getMostRecentDecl()->getAttr<UuidAttr>()) {
528 UuidAttrs.insert(Uuid);
529 return;
530 }
531
532 // __uuidof can grab UUIDs from template arguments.
533 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
534 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
535 for (const TemplateArgument &TA : TAL.asArray()) {
536 const UuidAttr *UuidForTA = nullptr;
537 if (TA.getKind() == TemplateArgument::Type)
538 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
539 else if (TA.getKind() == TemplateArgument::Declaration)
540 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
541
542 if (UuidForTA)
543 UuidAttrs.insert(UuidForTA);
544 }
545 }
546}
547
Francois Pichet9f4f2072010-09-08 12:20:18 +0000548/// \brief Build a Microsoft __uuidof expression with a type operand.
549ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
550 SourceLocation TypeidLoc,
551 TypeSourceInfo *Operand,
552 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000553 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000554 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000555 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
556 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
557 if (UuidAttrs.empty())
558 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
559 if (UuidAttrs.size() > 1)
560 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000561 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000562 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
David Majnemer2041b462016-03-28 03:19:50 +0000564 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000565 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000566}
567
568/// \brief Build a Microsoft __uuidof expression with an expression operand.
569ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
570 SourceLocation TypeidLoc,
571 Expr *E,
572 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000573 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000574 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000575 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
576 UuidStr = "00000000-0000-0000-0000-000000000000";
577 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000578 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
579 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
580 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000581 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000582 if (UuidAttrs.size() > 1)
583 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000584 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000585 }
Francois Pichetb7577652010-12-27 01:32:00 +0000586 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000587
David Majnemer2041b462016-03-28 03:19:50 +0000588 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000589 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000590}
591
592/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
593ExprResult
594Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
595 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000596 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000597 if (!MSVCGuidDecl) {
598 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
599 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
600 LookupQualifiedName(R, Context.getTranslationUnitDecl());
601 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
602 if (!MSVCGuidDecl)
603 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604 }
605
Francois Pichet9f4f2072010-09-08 12:20:18 +0000606 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
Francois Pichet9f4f2072010-09-08 12:20:18 +0000608 if (isType) {
609 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000610 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000611 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
612 &TInfo);
613 if (T.isNull())
614 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000615
Francois Pichet9f4f2072010-09-08 12:20:18 +0000616 if (!TInfo)
617 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
618
619 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
620 }
621
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000623 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
624}
625
Steve Naroff66356bd2007-09-16 14:56:35 +0000626/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000627ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000628Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000629 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000630 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000631 return new (Context)
632 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000633}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000634
Sebastian Redl576fd422009-05-10 18:38:11 +0000635/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000636ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000637Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000638 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000639}
640
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000641/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000642ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000643Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
644 bool IsThrownVarInScope = false;
645 if (Ex) {
646 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000647 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000648 // copy/move construction of a class object [...]
649 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000650 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000651 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000652 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000653 // innermost enclosing try-block (if there is one), the copy/move
654 // operation from the operand to the exception object (15.1) can be
655 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000656 // exception object
657 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
658 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
659 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
660 for( ; S; S = S->getParent()) {
661 if (S->isDeclScope(Var)) {
662 IsThrownVarInScope = true;
663 break;
664 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000665
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000666 if (S->getFlags() &
667 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
668 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
669 Scope::TryScope))
670 break;
671 }
672 }
673 }
674 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000675
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000676 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
677}
678
Simon Pilgrim75c26882016-09-30 14:25:09 +0000679ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000680 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000681 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000682 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000683 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000684 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000685
Justin Lebar2a8db342016-09-28 22:45:54 +0000686 // Exceptions aren't allowed in CUDA device code.
687 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000688 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
689 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000690
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000691 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
692 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
693
John Wiegley01296292011-04-08 18:41:53 +0000694 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000695 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
696 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000697 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000698
699 // Initialize the exception result. This implicitly weeds out
700 // abstract types or types with inaccessible copy constructors.
701
702 // C++0x [class.copymove]p31:
703 // When certain criteria are met, an implementation is allowed to omit the
704 // copy/move construction of a class object [...]
705 //
706 // - in a throw-expression, when the operand is the name of a
707 // non-volatile automatic object (other than a function or
708 // catch-clause
709 // parameter) whose scope does not extend beyond the end of the
710 // innermost enclosing try-block (if there is one), the copy/move
711 // operation from the operand to the exception object (15.1) can be
712 // omitted by constructing the automatic object directly into the
713 // exception object
714 const VarDecl *NRVOVariable = nullptr;
715 if (IsThrownVarInScope)
716 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
717
718 InitializedEntity Entity = InitializedEntity::InitializeException(
719 OpLoc, ExceptionObjectTy,
720 /*NRVO=*/NRVOVariable != nullptr);
721 ExprResult Res = PerformMoveOrCopyInitialization(
722 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
723 if (Res.isInvalid())
724 return ExprError();
725 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000726 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000727
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000728 return new (Context)
729 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000730}
731
David Majnemere7a818f2015-03-06 18:53:55 +0000732static void
733collectPublicBases(CXXRecordDecl *RD,
734 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
735 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
736 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
737 bool ParentIsPublic) {
738 for (const CXXBaseSpecifier &BS : RD->bases()) {
739 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
740 bool NewSubobject;
741 // Virtual bases constitute the same subobject. Non-virtual bases are
742 // always distinct subobjects.
743 if (BS.isVirtual())
744 NewSubobject = VBases.insert(BaseDecl).second;
745 else
746 NewSubobject = true;
747
748 if (NewSubobject)
749 ++SubobjectsSeen[BaseDecl];
750
751 // Only add subobjects which have public access throughout the entire chain.
752 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
753 if (PublicPath)
754 PublicSubobjectsSeen.insert(BaseDecl);
755
756 // Recurse on to each base subobject.
757 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
758 PublicPath);
759 }
760}
761
762static void getUnambiguousPublicSubobjects(
763 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
764 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
765 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
766 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
767 SubobjectsSeen[RD] = 1;
768 PublicSubobjectsSeen.insert(RD);
769 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
770 /*ParentIsPublic=*/true);
771
772 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
773 // Skip ambiguous objects.
774 if (SubobjectsSeen[PublicSubobject] > 1)
775 continue;
776
777 Objects.push_back(PublicSubobject);
778 }
779}
780
Sebastian Redl4de47b42009-04-27 20:27:31 +0000781/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000782bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
783 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000784 // If the type of the exception would be an incomplete type or a pointer
785 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000786 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000787 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000788 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000789 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000790 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000791 }
792 if (!isPointer || !Ty->isVoidType()) {
793 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000794 isPointer ? diag::err_throw_incomplete_ptr
795 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000796 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000797 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000798
David Majnemerd09a51c2015-03-03 01:50:05 +0000799 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000800 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000801 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000802 }
803
Eli Friedman91a3d272010-06-03 20:39:03 +0000804 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000805 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
806 if (!RD)
807 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000808
Douglas Gregor88d292c2010-05-13 16:44:06 +0000809 // If we are throwing a polymorphic class type or pointer thereof,
810 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000811 MarkVTableUsed(ThrowLoc, RD);
812
Eli Friedman36ebbec2010-10-12 20:32:36 +0000813 // If a pointer is thrown, the referenced object will not be destroyed.
814 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000815 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000816
Richard Smitheec915d62012-02-18 04:13:32 +0000817 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000818 if (!RD->hasIrrelevantDestructor()) {
819 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
820 MarkFunctionReferenced(E->getExprLoc(), Destructor);
821 CheckDestructorAccess(E->getExprLoc(), Destructor,
822 PDiag(diag::err_access_dtor_exception) << Ty);
823 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000824 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000825 }
826 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000827
David Majnemerdfa6d202015-03-11 18:36:39 +0000828 // The MSVC ABI creates a list of all types which can catch the exception
829 // object. This list also references the appropriate copy constructor to call
830 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000831 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000832 // We are only interested in the public, unambiguous bases contained within
833 // the exception object. Bases which are ambiguous or otherwise
834 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000835 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
836 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000837
David Majnemere7a818f2015-03-06 18:53:55 +0000838 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000839 // Attempt to lookup the copy constructor. Various pieces of machinery
840 // will spring into action, like template instantiation, which means this
841 // cannot be a simple walk of the class's decls. Instead, we must perform
842 // lookup and overload resolution.
843 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
844 if (!CD)
845 continue;
846
847 // Mark the constructor referenced as it is used by this throw expression.
848 MarkFunctionReferenced(E->getExprLoc(), CD);
849
850 // Skip this copy constructor if it is trivial, we don't need to record it
851 // in the catchable type data.
852 if (CD->isTrivial())
853 continue;
854
855 // The copy constructor is non-trivial, create a mapping from this class
856 // type to this constructor.
857 // N.B. The selection of copy constructor is not sensitive to this
858 // particular throw-site. Lookup will be performed at the catch-site to
859 // ensure that the copy constructor is, in fact, accessible (via
860 // friendship or any other means).
861 Context.addCopyConstructorForExceptionObject(Subobject, CD);
862
863 // We don't keep the instantiated default argument expressions around so
864 // we must rebuild them here.
865 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
866 // Skip any default arguments that we've already instantiated.
867 if (Context.getDefaultArgExprForConstructor(CD, I))
868 continue;
869
870 Expr *DefaultArg =
871 BuildCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)).get();
872 Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
David Majnemere7a818f2015-03-06 18:53:55 +0000873 }
874 }
875 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000876
David Majnemerba3e5ec2015-03-13 18:26:17 +0000877 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000878}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000879
Faisal Vali67b04462016-06-11 16:41:54 +0000880static QualType adjustCVQualifiersForCXXThisWithinLambda(
881 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
882 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
883
884 QualType ClassType = ThisTy->getPointeeType();
885 LambdaScopeInfo *CurLSI = nullptr;
886 DeclContext *CurDC = CurSemaContext;
887
888 // Iterate through the stack of lambdas starting from the innermost lambda to
889 // the outermost lambda, checking if '*this' is ever captured by copy - since
890 // that could change the cv-qualifiers of the '*this' object.
891 // The object referred to by '*this' starts out with the cv-qualifiers of its
892 // member function. We then start with the innermost lambda and iterate
893 // outward checking to see if any lambda performs a by-copy capture of '*this'
894 // - and if so, any nested lambda must respect the 'constness' of that
895 // capturing lamdbda's call operator.
896 //
897
898 // The issue is that we cannot rely entirely on the FunctionScopeInfo stack
899 // since ScopeInfos are pushed on during parsing and treetransforming. But
900 // since a generic lambda's call operator can be instantiated anywhere (even
901 // end of the TU) we need to be able to examine its enclosing lambdas and so
902 // we use the DeclContext to get a hold of the closure-class and query it for
903 // capture information. The reason we don't just resort to always using the
904 // DeclContext chain is that it is only mature for lambda expressions
905 // enclosing generic lambda's call operators that are being instantiated.
906
907 for (int I = FunctionScopes.size();
908 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]);
909 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
910 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000911
912 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +0000913 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000914
Faisal Vali67b04462016-06-11 16:41:54 +0000915 auto C = CurLSI->getCXXThisCapture();
916
917 if (C.isCopyCapture()) {
918 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
919 if (CurLSI->CallOperator->isConst())
920 ClassType.addConst();
921 return ASTCtx.getPointerType(ClassType);
922 }
923 }
924 // We've run out of ScopeInfos but check if CurDC is a lambda (which can
925 // happen during instantiation of generic lambdas)
926 if (isLambdaCallOperator(CurDC)) {
927 assert(CurLSI);
928 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator));
929 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +0000930
Faisal Vali67b04462016-06-11 16:41:54 +0000931 auto IsThisCaptured =
932 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
933 IsConst = false;
934 IsByCopy = false;
935 for (auto &&C : Closure->captures()) {
936 if (C.capturesThis()) {
937 if (C.getCaptureKind() == LCK_StarThis)
938 IsByCopy = true;
939 if (Closure->getLambdaCallOperator()->isConst())
940 IsConst = true;
941 return true;
942 }
943 }
944 return false;
945 };
946
947 bool IsByCopyCapture = false;
948 bool IsConstCapture = false;
949 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
950 while (Closure &&
951 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
952 if (IsByCopyCapture) {
953 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
954 if (IsConstCapture)
955 ClassType.addConst();
956 return ASTCtx.getPointerType(ClassType);
957 }
958 Closure = isLambdaCallOperator(Closure->getParent())
959 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
960 : nullptr;
961 }
962 }
963 return ASTCtx.getPointerType(ClassType);
964}
965
Eli Friedman73a04092012-01-07 04:59:52 +0000966QualType Sema::getCurrentThisType() {
967 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +0000968 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000969
Richard Smith938f40b2011-06-11 17:19:42 +0000970 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
971 if (method && method->isInstance())
972 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000973 }
Faisal Validc6b5962016-03-21 09:25:37 +0000974
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000975 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
976 !ActiveTemplateInstantiations.empty()) {
Faisal Validc6b5962016-03-21 09:25:37 +0000977
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000978 assert(isa<CXXRecordDecl>(DC) &&
979 "Trying to get 'this' type from static method?");
980
981 // This is a lambda call operator that is being instantiated as a default
982 // initializer. DC must point to the enclosing class type, so we can recover
983 // the 'this' type from it.
984
985 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
986 // There are no cv-qualifiers for 'this' within default initializers,
987 // per [expr.prim.general]p4.
988 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +0000989 }
Faisal Vali67b04462016-06-11 16:41:54 +0000990
991 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
992 // might need to be adjusted if the lambda or any of its enclosing lambda's
993 // captures '*this' by copy.
994 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
995 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
996 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000997 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +0000998}
999
Simon Pilgrim75c26882016-09-30 14:25:09 +00001000Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001001 Decl *ContextDecl,
1002 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001003 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001004 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1005{
1006 if (!Enabled || !ContextDecl)
1007 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001008
1009 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001010 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1011 Record = Template->getTemplatedDecl();
1012 else
1013 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001014
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001015 // We care only for CVR qualifiers here, so cut everything else.
1016 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001017 S.CXXThisTypeOverride
1018 = S.Context.getPointerType(
1019 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001020
Douglas Gregor3024f072012-04-16 07:05:22 +00001021 this->Enabled = true;
1022}
1023
1024
1025Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1026 if (Enabled) {
1027 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1028 }
1029}
1030
Faisal Validc6b5962016-03-21 09:25:37 +00001031static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1032 QualType ThisTy, SourceLocation Loc,
1033 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001034
Faisal Vali67b04462016-06-11 16:41:54 +00001035 QualType AdjustedThisTy = ThisTy;
1036 // The type of the corresponding data member (not a 'this' pointer if 'by
1037 // copy').
1038 QualType CaptureThisFieldTy = ThisTy;
1039 if (ByCopy) {
1040 // If we are capturing the object referred to by '*this' by copy, ignore any
1041 // cv qualifiers inherited from the type of the member function for the type
1042 // of the closure-type's corresponding data member and any use of 'this'.
1043 CaptureThisFieldTy = ThisTy->getPointeeType();
1044 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1045 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1046 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001047
Faisal Vali67b04462016-06-11 16:41:54 +00001048 FieldDecl *Field = FieldDecl::Create(
1049 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1050 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1051 ICIS_NoInit);
1052
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001053 Field->setImplicit(true);
1054 Field->setAccess(AS_private);
1055 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001056 Expr *This =
1057 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001058 if (ByCopy) {
1059 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1060 UO_Deref,
1061 This).get();
1062 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001063 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001064 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1065 InitializationSequence Init(S, Entity, InitKind, StarThis);
1066 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1067 if (ER.isInvalid()) return nullptr;
1068 return ER.get();
1069 }
1070 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001071}
1072
Simon Pilgrim75c26882016-09-30 14:25:09 +00001073bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001074 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1075 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001076 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001077 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001078 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001079
Faisal Validc6b5962016-03-21 09:25:37 +00001080 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001081
Faisal Valia17d19f2013-11-07 05:17:06 +00001082 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
Faisal Validc6b5962016-03-21 09:25:37 +00001083 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001084
Simon Pilgrim75c26882016-09-30 14:25:09 +00001085 // Check that we can capture the *enclosing object* (referred to by '*this')
1086 // by the capturing-entity/closure (lambda/block/etc) at
1087 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1088
1089 // Note: The *enclosing object* can only be captured by-value by a
1090 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001091 // [*this] { ... }.
1092 // Every other capture of the *enclosing object* results in its by-reference
1093 // capture.
1094
1095 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1096 // stack), we can capture the *enclosing object* only if:
1097 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1098 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001099 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001100 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001101 // -- or, there is some enclosing closure 'E' that has already captured the
1102 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001103 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001104 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001105 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001106
1107
Faisal Validc6b5962016-03-21 09:25:37 +00001108 unsigned NumCapturingClosures = 0;
Faisal Valia17d19f2013-11-07 05:17:06 +00001109 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001110 if (CapturingScopeInfo *CSI =
1111 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1112 if (CSI->CXXThisCaptureIndex != 0) {
1113 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman73a04092012-01-07 04:59:52 +00001114 break;
1115 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001116 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1117 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1118 // This context can't implicitly capture 'this'; fail out.
1119 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001120 Diag(Loc, diag::err_this_capture)
1121 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001122 return true;
1123 }
Eli Friedman20139d32012-01-11 02:36:31 +00001124 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001125 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001126 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001127 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001128 (Explicit && idx == MaxFunctionScopesIndex)) {
1129 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1130 // iteration through can be an explicit capture, all enclosing closures,
1131 // if any, must perform implicit captures.
1132
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001133 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001134 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001135 continue;
1136 }
Eli Friedman20139d32012-01-11 02:36:31 +00001137 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001138 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001139 Diag(Loc, diag::err_this_capture)
1140 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001141 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001142 }
Eli Friedman73a04092012-01-07 04:59:52 +00001143 break;
1144 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001145 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001146
1147 // If we got here, then the closure at MaxFunctionScopesIndex on the
1148 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1149 // (including implicit by-reference captures in any enclosing closures).
1150
1151 // In the loop below, respect the ByCopy flag only for the closure requesting
1152 // the capture (i.e. first iteration through the loop below). Ignore it for
1153 // all enclosing closure's upto NumCapturingClosures (since they must be
1154 // implicitly capturing the *enclosing object* by reference (see loop
1155 // above)).
1156 assert((!ByCopy ||
1157 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1158 "Only a lambda can capture the enclosing object (referred to by "
1159 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001160 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1161 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001162 QualType ThisTy = getCurrentThisType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00001163 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
Faisal Validc6b5962016-03-21 09:25:37 +00001164 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001165 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001166 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001167
Faisal Validc6b5962016-03-21 09:25:37 +00001168 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1169 // For lambda expressions, build a field and an initializing expression,
1170 // and capture the *enclosing object* by copy only if this is the first
1171 // iteration.
1172 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1173 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001174
Faisal Validc6b5962016-03-21 09:25:37 +00001175 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001176 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001177 ThisExpr =
1178 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1179 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001180
Faisal Validc6b5962016-03-21 09:25:37 +00001181 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001182 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001183 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001184 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001185}
1186
Richard Smith938f40b2011-06-11 17:19:42 +00001187ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001188 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1189 /// is a non-lvalue expression whose value is the address of the object for
1190 /// which the function is called.
1191
Douglas Gregor09deffa2011-10-18 16:47:30 +00001192 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001193 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001194
Eli Friedman73a04092012-01-07 04:59:52 +00001195 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001196 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001197}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001198
Douglas Gregor3024f072012-04-16 07:05:22 +00001199bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1200 // If we're outside the body of a member function, then we'll have a specified
1201 // type for 'this'.
1202 if (CXXThisTypeOverride.isNull())
1203 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001204
Douglas Gregor3024f072012-04-16 07:05:22 +00001205 // Determine whether we're looking into a class that's currently being
1206 // defined.
1207 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1208 return Class && Class->isBeingDefined();
1209}
1210
John McCalldadc5752010-08-24 06:29:42 +00001211ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001212Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001213 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001214 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001215 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001216 if (!TypeRep)
1217 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001218
John McCall97513962010-01-15 18:39:57 +00001219 TypeSourceInfo *TInfo;
1220 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1221 if (!TInfo)
1222 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001223
Richard Smithb8c414c2016-06-30 20:24:30 +00001224 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1225 // Avoid creating a non-type-dependent expression that contains typos.
1226 // Non-type-dependent expressions are liable to be discarded without
1227 // checking for embedded typos.
1228 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1229 !Result.get()->isTypeDependent())
1230 Result = CorrectDelayedTyposInExpr(Result.get());
1231 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001232}
1233
1234/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1235/// Can be interpreted either as function-style casting ("int(x)")
1236/// or class type construction ("ClassType(x,y,z)")
1237/// or creation of a value-initialized type ("int()").
1238ExprResult
1239Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1240 SourceLocation LParenLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001241 MultiExprArg Exprs,
Douglas Gregor2b88c112010-09-08 00:15:04 +00001242 SourceLocation RParenLoc) {
1243 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001244 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001245
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001246 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001247 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1248 RParenLoc);
Douglas Gregor0950e412009-03-13 21:01:28 +00001249 }
1250
Sebastian Redld74dd492012-02-12 18:41:05 +00001251 bool ListInitialization = LParenLoc.isInvalid();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001252 assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
Sebastian Redld74dd492012-02-12 18:41:05 +00001253 && "List initialization must have initializer list as expression.");
1254 SourceRange FullRange = SourceRange(TyBeginLoc,
1255 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1256
Douglas Gregordd04d332009-01-16 18:33:17 +00001257 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001258 // If the expression list is a single expression, the type conversion
1259 // expression is equivalent (in definedness, and if defined in meaning) to the
1260 // corresponding cast expression.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001261 if (Exprs.size() == 1 && !ListInitialization) {
John McCallb50451a2011-10-05 07:41:44 +00001262 Expr *Arg = Exprs[0];
John McCallb50451a2011-10-05 07:41:44 +00001263 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001264 }
1265
David Majnemer7eddcff2015-09-14 07:05:00 +00001266 // C++14 [expr.type.conv]p2: The expression T(), where T is a
1267 // simple-type-specifier or typename-specifier for a non-array complete
1268 // object type or the (possibly cv-qualified) void type, creates a prvalue
1269 // of the specified type, whose value is that produced by value-initializing
1270 // an object of type T.
Eli Friedman576cbd02012-02-29 00:00:28 +00001271 QualType ElemTy = Ty;
1272 if (Ty->isArrayType()) {
1273 if (!ListInitialization)
1274 return ExprError(Diag(TyBeginLoc,
1275 diag::err_value_init_for_array_type) << FullRange);
1276 ElemTy = Context.getBaseElementType(Ty);
1277 }
1278
David Majnemer7eddcff2015-09-14 07:05:00 +00001279 if (!ListInitialization && Ty->isFunctionType())
1280 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_function_type)
1281 << FullRange);
1282
Eli Friedman576cbd02012-02-29 00:00:28 +00001283 if (!Ty->isVoidType() &&
1284 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001285 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001286 return ExprError();
1287
1288 if (RequireNonAbstractType(TyBeginLoc, Ty,
1289 diag::err_allocation_of_abstract_type))
1290 return ExprError();
1291
Douglas Gregor8ec51732010-09-08 21:40:08 +00001292 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001293 InitializationKind Kind =
1294 Exprs.size() ? ListInitialization
1295 ? InitializationKind::CreateDirectList(TyBeginLoc)
1296 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
1297 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1298 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1299 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001300
Richard Smith90061902013-09-23 02:20:00 +00001301 if (Result.isInvalid() || !ListInitialization)
1302 return Result;
1303
1304 Expr *Inner = Result.get();
1305 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1306 Inner = BTE->getSubExpr();
Richard Smith1ae689c2015-01-28 22:06:01 +00001307 if (!isa<CXXTemporaryObjectExpr>(Inner)) {
1308 // If we created a CXXTemporaryObjectExpr, that node also represents the
1309 // functional cast. Otherwise, create an explicit cast to represent
1310 // the syntactic form of a functional-style cast that was used here.
1311 //
1312 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1313 // would give a more consistent AST representation than using a
1314 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1315 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001316 QualType ResultType = Result.get()->getType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001317 Result = CXXFunctionalCastExpr::Create(
Richard Smith90061902013-09-23 02:20:00 +00001318 Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001319 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
Sebastian Redl2b80af42012-02-13 19:55:43 +00001320 }
1321
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001322 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001323}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001324
Richard Smithb2f0f052016-10-10 18:54:32 +00001325/// \brief Determine whether the given function is a non-placement
1326/// deallocation function.
1327static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1328 if (FD->isInvalidDecl())
1329 return false;
1330
1331 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1332 return Method->isUsualDeallocationFunction();
1333
1334 if (FD->getOverloadedOperator() != OO_Delete &&
1335 FD->getOverloadedOperator() != OO_Array_Delete)
1336 return false;
1337
1338 unsigned UsualParams = 1;
1339
1340 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1341 S.Context.hasSameUnqualifiedType(
1342 FD->getParamDecl(UsualParams)->getType(),
1343 S.Context.getSizeType()))
1344 ++UsualParams;
1345
1346 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1347 S.Context.hasSameUnqualifiedType(
1348 FD->getParamDecl(UsualParams)->getType(),
1349 S.Context.getTypeDeclType(S.getStdAlignValT())))
1350 ++UsualParams;
1351
1352 return UsualParams == FD->getNumParams();
1353}
1354
1355namespace {
1356 struct UsualDeallocFnInfo {
1357 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001358 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001359 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smithf75dcbe2016-10-11 00:21:10 +00001360 HasSizeT(false), HasAlignValT(false), CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001361 // A function template declaration is never a usual deallocation function.
1362 if (!FD)
1363 return;
1364 if (FD->getNumParams() == 3)
1365 HasAlignValT = HasSizeT = true;
1366 else if (FD->getNumParams() == 2) {
1367 HasSizeT = FD->getParamDecl(1)->getType()->isIntegerType();
1368 HasAlignValT = !HasSizeT;
1369 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001370
1371 // In CUDA, determine how much we'd like / dislike to call this.
1372 if (S.getLangOpts().CUDA)
1373 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1374 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001375 }
1376
1377 operator bool() const { return FD; }
1378
Richard Smithf75dcbe2016-10-11 00:21:10 +00001379 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1380 bool WantAlign) const {
1381 // C++17 [expr.delete]p10:
1382 // If the type has new-extended alignment, a function with a parameter
1383 // of type std::align_val_t is preferred; otherwise a function without
1384 // such a parameter is preferred
1385 if (HasAlignValT != Other.HasAlignValT)
1386 return HasAlignValT == WantAlign;
1387
1388 if (HasSizeT != Other.HasSizeT)
1389 return HasSizeT == WantSize;
1390
1391 // Use CUDA call preference as a tiebreaker.
1392 return CUDAPref > Other.CUDAPref;
1393 }
1394
Richard Smithb2f0f052016-10-10 18:54:32 +00001395 DeclAccessPair Found;
1396 FunctionDecl *FD;
1397 bool HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001398 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001399 };
1400}
1401
1402/// Determine whether a type has new-extended alignment. This may be called when
1403/// the type is incomplete (for a delete-expression with an incomplete pointee
1404/// type), in which case it will conservatively return false if the alignment is
1405/// not known.
1406static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1407 return S.getLangOpts().AlignedAllocation &&
1408 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1409 S.getASTContext().getTargetInfo().getNewAlign();
1410}
1411
1412/// Select the correct "usual" deallocation function to use from a selection of
1413/// deallocation functions (either global or class-scope).
1414static UsualDeallocFnInfo resolveDeallocationOverload(
1415 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1416 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1417 UsualDeallocFnInfo Best;
1418
Richard Smithb2f0f052016-10-10 18:54:32 +00001419 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001420 UsualDeallocFnInfo Info(S, I.getPair());
1421 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1422 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001423 continue;
1424
1425 if (!Best) {
1426 Best = Info;
1427 if (BestFns)
1428 BestFns->push_back(Info);
1429 continue;
1430 }
1431
Richard Smithf75dcbe2016-10-11 00:21:10 +00001432 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001433 continue;
1434
1435 // If more than one preferred function is found, all non-preferred
1436 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001437 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001438 BestFns->clear();
1439
1440 Best = Info;
1441 if (BestFns)
1442 BestFns->push_back(Info);
1443 }
1444
1445 return Best;
1446}
1447
1448/// Determine whether a given type is a class for which 'delete[]' would call
1449/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1450/// we need to store the array size (even if the type is
1451/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001452static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1453 QualType allocType) {
1454 const RecordType *record =
1455 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1456 if (!record) return false;
1457
1458 // Try to find an operator delete[] in class scope.
1459
1460 DeclarationName deleteName =
1461 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1462 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1463 S.LookupQualifiedName(ops, record->getDecl());
1464
1465 // We're just doing this for information.
1466 ops.suppressDiagnostics();
1467
1468 // Very likely: there's no operator delete[].
1469 if (ops.empty()) return false;
1470
1471 // If it's ambiguous, it should be illegal to call operator delete[]
1472 // on this thing, so it doesn't matter if we allocate extra space or not.
1473 if (ops.isAmbiguous()) return false;
1474
Richard Smithb2f0f052016-10-10 18:54:32 +00001475 // C++17 [expr.delete]p10:
1476 // If the deallocation functions have class scope, the one without a
1477 // parameter of type std::size_t is selected.
1478 auto Best = resolveDeallocationOverload(
1479 S, ops, /*WantSize*/false,
1480 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1481 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001482}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001483
Sebastian Redld74dd492012-02-12 18:41:05 +00001484/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001485///
Sebastian Redld74dd492012-02-12 18:41:05 +00001486/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001487/// @code new (memory) int[size][4] @endcode
1488/// or
1489/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001490///
1491/// \param StartLoc The first location of the expression.
1492/// \param UseGlobal True if 'new' was prefixed with '::'.
1493/// \param PlacementLParen Opening paren of the placement arguments.
1494/// \param PlacementArgs Placement new arguments.
1495/// \param PlacementRParen Closing paren of the placement arguments.
1496/// \param TypeIdParens If the type is in parens, the source range.
1497/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001498/// \param Initializer The initializing expression or initializer-list, or null
1499/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001500ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001501Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001502 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001503 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001504 Declarator &D, Expr *Initializer) {
Richard Smith74aeef52013-04-26 16:15:35 +00001505 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
Richard Smith30482bc2011-02-20 03:19:35 +00001506
Craig Topperc3ec1492014-05-26 06:22:03 +00001507 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001508 // If the specified type is an array, unwrap it and save the expression.
1509 if (D.getNumTypeObjects() > 0 &&
1510 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
James Dennettf14a6e52012-06-15 22:23:43 +00001511 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith30482bc2011-02-20 03:19:35 +00001512 if (TypeContainsAuto)
1513 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1514 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001515 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001516 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1517 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001518 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001519 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1520 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001521
Sebastian Redl351bb782008-12-02 14:43:59 +00001522 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001523 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001524 }
1525
Douglas Gregor73341c42009-09-11 00:18:58 +00001526 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001527 if (ArraySize) {
1528 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001529 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1530 break;
1531
1532 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1533 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001534 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001535 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001536 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1537 // shall be a converted constant expression (5.19) of type std::size_t
1538 // and shall evaluate to a strictly positive value.
1539 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1540 assert(IntWidth && "Builtin type of size 0?");
1541 llvm::APSInt Value(IntWidth);
1542 Array.NumElts
1543 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1544 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001545 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001546 } else {
1547 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001548 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001549 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001550 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001551 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001552 if (!Array.NumElts)
1553 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001554 }
1555 }
1556 }
1557 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001558
Craig Topperc3ec1492014-05-26 06:22:03 +00001559 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001560 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001561 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001562 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001563
Sebastian Redl6047f072012-02-16 12:22:20 +00001564 SourceRange DirectInitRange;
1565 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1566 DirectInitRange = List->getSourceRange();
1567
David Blaikie7b97aef2012-11-07 00:12:38 +00001568 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001569 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001570 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001571 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001572 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001573 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001574 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001575 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001576 DirectInitRange,
1577 Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001578 TypeContainsAuto);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001579}
1580
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001581static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1582 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001583 if (!Init)
1584 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001585 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1586 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001587 if (isa<ImplicitValueInitExpr>(Init))
1588 return true;
1589 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1590 return !CCE->isListInitialization() &&
1591 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001592 else if (Style == CXXNewExpr::ListInit) {
1593 assert(isa<InitListExpr>(Init) &&
1594 "Shouldn't create list CXXConstructExprs for arrays.");
1595 return true;
1596 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001597 return false;
1598}
1599
John McCalldadc5752010-08-24 06:29:42 +00001600ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001601Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001602 SourceLocation PlacementLParen,
1603 MultiExprArg PlacementArgs,
1604 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001605 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001606 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001607 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001608 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001609 SourceRange DirectInitRange,
1610 Expr *Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001611 bool TypeMayContainAuto) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001612 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001613 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001614
Sebastian Redl6047f072012-02-16 12:22:20 +00001615 CXXNewExpr::InitializationStyle initStyle;
1616 if (DirectInitRange.isValid()) {
1617 assert(Initializer && "Have parens but no initializer.");
1618 initStyle = CXXNewExpr::CallInit;
1619 } else if (Initializer && isa<InitListExpr>(Initializer))
1620 initStyle = CXXNewExpr::ListInit;
1621 else {
1622 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1623 isa<CXXConstructExpr>(Initializer)) &&
1624 "Initializer expression that cannot have been implicitly created.");
1625 initStyle = CXXNewExpr::NoInit;
1626 }
1627
1628 Expr **Inits = &Initializer;
1629 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001630 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1631 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1632 Inits = List->getExprs();
1633 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001634 }
1635
Richard Smith66204ec2014-03-12 17:42:45 +00001636 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00001637 if (TypeMayContainAuto && AllocType->isUndeducedType()) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001638 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001639 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1640 << AllocType << TypeRange);
Richard Smith66204ec2014-03-12 17:42:45 +00001641 if (initStyle == CXXNewExpr::ListInit ||
1642 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001643 return ExprError(Diag(Inits[0]->getLocStart(),
Richard Smith66204ec2014-03-12 17:42:45 +00001644 diag::err_auto_new_list_init)
Sebastian Redl6047f072012-02-16 12:22:20 +00001645 << AllocType << TypeRange);
1646 if (NumInits > 1) {
1647 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001648 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001649 diag::err_auto_new_ctor_multiple_expressions)
1650 << AllocType << TypeRange);
1651 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001652 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001653 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001654 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001655 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001656 << AllocType << Deduce->getType()
1657 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001658 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001659 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001660 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001661 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001662
Douglas Gregorcda95f42010-05-16 16:01:03 +00001663 // Per C++0x [expr.new]p5, the type being constructed may be a
1664 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001665 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001666 if (const ConstantArrayType *Array
1667 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001668 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1669 Context.getSizeType(),
1670 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001671 AllocType = Array->getElementType();
1672 }
1673 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001674
Douglas Gregor3999e152010-10-06 16:00:31 +00001675 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1676 return ExprError();
1677
Craig Topperc3ec1492014-05-26 06:22:03 +00001678 if (initStyle == CXXNewExpr::ListInit &&
1679 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001680 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1681 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001682 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001683 }
1684
Simon Pilgrim75c26882016-09-30 14:25:09 +00001685 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001686 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001687 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1688 AllocType->isObjCLifetimeType()) {
1689 AllocType = Context.getLifetimeQualifiedType(AllocType,
1690 AllocType->getObjCARCImplicitLifetime());
1691 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001692
John McCall31168b02011-06-15 23:02:42 +00001693 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001694
John McCall5e77d762013-04-16 07:28:30 +00001695 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1696 ExprResult result = CheckPlaceholderExpr(ArraySize);
1697 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001698 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001699 }
Richard Smith8dd34252012-02-04 07:07:42 +00001700 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1701 // integral or enumeration type with a non-negative value."
1702 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1703 // enumeration type, or a class type for which a single non-explicit
1704 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001705 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001706 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001707 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001708 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001709 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001710 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001711 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1712
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001713 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1714 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001715
Simon Pilgrim75c26882016-09-30 14:25:09 +00001716 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001717 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001718 // Diagnose the compatibility of this conversion.
1719 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1720 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001721 } else {
1722 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1723 protected:
1724 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001725
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001726 public:
1727 SizeConvertDiagnoser(Expr *ArraySize)
1728 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1729 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001730
1731 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1732 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001733 return S.Diag(Loc, diag::err_array_size_not_integral)
1734 << S.getLangOpts().CPlusPlus11 << T;
1735 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001736
1737 SemaDiagnosticBuilder diagnoseIncomplete(
1738 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001739 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1740 << T << ArraySize->getSourceRange();
1741 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001742
1743 SemaDiagnosticBuilder diagnoseExplicitConv(
1744 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001745 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1746 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001747
1748 SemaDiagnosticBuilder noteExplicitConv(
1749 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001750 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1751 << ConvTy->isEnumeralType() << ConvTy;
1752 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001753
1754 SemaDiagnosticBuilder diagnoseAmbiguous(
1755 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001756 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1757 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001758
1759 SemaDiagnosticBuilder noteAmbiguous(
1760 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001761 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1762 << ConvTy->isEnumeralType() << ConvTy;
1763 }
Richard Smithccc11812013-05-21 19:05:48 +00001764
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001765 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1766 QualType T,
1767 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001768 return S.Diag(Loc,
1769 S.getLangOpts().CPlusPlus11
1770 ? diag::warn_cxx98_compat_array_size_conversion
1771 : diag::ext_array_size_conversion)
1772 << T << ConvTy->isEnumeralType() << ConvTy;
1773 }
1774 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001775
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001776 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1777 SizeDiagnoser);
1778 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001779 if (ConvertedSize.isInvalid())
1780 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001781
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001782 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001783 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001784
Douglas Gregor0bf31402010-10-08 23:50:27 +00001785 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001786 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001787
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001788 // C++98 [expr.new]p7:
1789 // The expression in a direct-new-declarator shall have integral type
1790 // with a non-negative value.
1791 //
Richard Smith0511d232016-10-05 22:41:02 +00001792 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1793 // per CWG1464. Otherwise, if it's not a constant, we must have an
1794 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001795 if (!ArraySize->isValueDependent()) {
1796 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001797 // We've already performed any required implicit conversion to integer or
1798 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001799 // FIXME: Per CWG1464, we are required to check the value prior to
1800 // converting to size_t. This will never find a negative array size in
1801 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001802 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001803 if (Value.isSigned() && Value.isNegative()) {
1804 return ExprError(Diag(ArraySize->getLocStart(),
1805 diag::err_typecheck_negative_array_size)
1806 << ArraySize->getSourceRange());
1807 }
1808
1809 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001810 unsigned ActiveSizeBits =
1811 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00001812 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1813 return ExprError(Diag(ArraySize->getLocStart(),
1814 diag::err_array_too_large)
1815 << Value.toString(10)
1816 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001817 }
Richard Smith0511d232016-10-05 22:41:02 +00001818
1819 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00001820 } else if (TypeIdParens.isValid()) {
1821 // Can't have dynamic array size when the type-id is in parentheses.
1822 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1823 << ArraySize->getSourceRange()
1824 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1825 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001826
Douglas Gregorf2753b32010-07-13 15:54:32 +00001827 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001828 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001829 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001830
John McCall036f2f62011-05-15 07:14:44 +00001831 // Note that we do *not* convert the argument in any way. It can
1832 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001833 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001834
Craig Topperc3ec1492014-05-26 06:22:03 +00001835 FunctionDecl *OperatorNew = nullptr;
1836 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00001837 unsigned Alignment =
1838 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1839 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1840 bool PassAlignment = getLangOpts().AlignedAllocation &&
1841 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001842
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001843 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001844 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001845 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001846 SourceRange(PlacementLParen, PlacementRParen),
Richard Smithb2f0f052016-10-10 18:54:32 +00001847 UseGlobal, AllocType, ArraySize, PassAlignment,
1848 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001849 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001850
1851 // If this is an array allocation, compute whether the usual array
1852 // deallocation function for the type has a size_t parameter.
1853 bool UsualArrayDeleteWantsSize = false;
1854 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00001855 UsualArrayDeleteWantsSize =
1856 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00001857
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001858 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001859 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001860 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00001861 OperatorNew->getType()->getAs<FunctionProtoType>();
1862 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1863 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001864
Richard Smithd6f9e732014-05-13 19:56:21 +00001865 // We've already converted the placement args, just fill in any default
1866 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00001867 // argument. Skip the second parameter too if we're passing in the
1868 // alignment; we've already filled it in.
1869 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
1870 PassAlignment ? 2 : 1, PlacementArgs,
1871 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001872 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001873
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001874 if (!AllPlaceArgs.empty())
1875 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00001876
Richard Smithd6f9e732014-05-13 19:56:21 +00001877 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001878 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00001879
1880 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001881
Richard Smithb2f0f052016-10-10 18:54:32 +00001882 // Warn if the type is over-aligned and is being allocated by (unaligned)
1883 // global operator new.
1884 if (PlacementArgs.empty() && !PassAlignment &&
1885 (OperatorNew->isImplicit() ||
1886 (OperatorNew->getLocStart().isValid() &&
1887 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
1888 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00001889 Diag(StartLoc, diag::warn_overaligned_type)
1890 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00001891 << unsigned(Alignment / Context.getCharWidth())
1892 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00001893 }
1894 }
1895
Sebastian Redl6047f072012-02-16 12:22:20 +00001896 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001897 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1898 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00001899 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
1900 SourceRange InitRange(Inits[0]->getLocStart(),
1901 Inits[NumInits - 1]->getLocEnd());
1902 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1903 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001904 }
1905
Richard Smithdd2ca572012-11-26 08:32:48 +00001906 // If we can perform the initialization, and we've not already done so,
1907 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00001908 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001909 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00001910 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00001911 // The type we initialize is the complete type, including the array bound.
1912 QualType InitType;
1913 if (KnownArraySize)
1914 InitType = Context.getConstantArrayType(
1915 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
1916 *KnownArraySize),
1917 ArrayType::Normal, 0);
1918 else if (ArraySize)
1919 InitType =
1920 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
1921 else
1922 InitType = AllocType;
1923
Sebastian Redld74dd492012-02-12 18:41:05 +00001924 // C++11 [expr.new]p15:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001925 // A new-expression that creates an object of type T initializes that
1926 // object as follows:
1927 InitializationKind Kind
1928 // - If the new-initializer is omitted, the object is default-
1929 // initialized (8.5); if no initialization is performed,
1930 // the object has indeterminate value
Sebastian Redl6047f072012-02-16 12:22:20 +00001931 = initStyle == CXXNewExpr::NoInit
1932 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001933 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001934 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +00001935 : initStyle == CXXNewExpr::ListInit
1936 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1937 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1938 DirectInitRange.getBegin(),
1939 DirectInitRange.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001940
Douglas Gregor85dabae2009-12-16 01:38:02 +00001941 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001942 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00001943 InitializationSequence InitSeq(*this, Entity, Kind,
1944 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00001946 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00001947 if (FullInit.isInvalid())
1948 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001949
Sebastian Redl6047f072012-02-16 12:22:20 +00001950 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1951 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00001952 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00001953 if (CXXBindTemporaryExpr *Binder =
1954 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001955 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001956
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001957 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001958 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959
Douglas Gregor6642ca22010-02-26 05:06:18 +00001960 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00001961 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00001962 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1963 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001964 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00001965 }
1966 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00001967 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1968 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001969 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00001970 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00001971
John McCall928a2572011-07-13 20:12:57 +00001972 // C++0x [expr.new]p17:
1973 // If the new expression creates an array of objects of class type,
1974 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00001975 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1976 if (ArraySize && !BaseAllocType->isDependentType()) {
1977 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1978 if (CXXDestructorDecl *dtor = LookupDestructor(
1979 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1980 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001981 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00001982 PDiag(diag::err_access_dtor)
1983 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00001984 if (DiagnoseUseOfDecl(dtor, StartLoc))
1985 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00001986 }
John McCall928a2572011-07-13 20:12:57 +00001987 }
1988 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001989
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001990 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00001991 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001992 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
1993 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
1994 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00001995}
1996
Sebastian Redl6047f072012-02-16 12:22:20 +00001997/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00001998/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00001999bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002000 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002001 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2002 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002003 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002004 return Diag(Loc, diag::err_bad_new_type)
2005 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002006 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002007 return Diag(Loc, diag::err_bad_new_type)
2008 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002009 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002010 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002011 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002012 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002013 diag::err_allocation_of_abstract_type))
2014 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002015 else if (AllocType->isVariablyModifiedType())
2016 return Diag(Loc, diag::err_variably_modified_new_type)
2017 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00002018 else if (unsigned AddressSpace = AllocType.getAddressSpace())
2019 return Diag(Loc, diag::err_address_space_qualified_new)
2020 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002021 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002022 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2023 QualType BaseAllocType = Context.getBaseElementType(AT);
2024 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2025 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002026 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002027 << BaseAllocType;
2028 }
2029 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002030
Sebastian Redlbd150f42008-11-21 19:14:01 +00002031 return false;
2032}
2033
Richard Smithb2f0f052016-10-10 18:54:32 +00002034static bool
2035resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2036 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2037 FunctionDecl *&Operator,
2038 OverloadCandidateSet *AlignedCandidates = nullptr,
2039 Expr *AlignArg = nullptr) {
2040 OverloadCandidateSet Candidates(R.getNameLoc(),
2041 OverloadCandidateSet::CSK_Normal);
2042 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2043 Alloc != AllocEnd; ++Alloc) {
2044 // Even member operator new/delete are implicitly treated as
2045 // static, so don't use AddMemberCandidate.
2046 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2047
2048 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2049 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2050 /*ExplicitTemplateArgs=*/nullptr, Args,
2051 Candidates,
2052 /*SuppressUserConversions=*/false);
2053 continue;
2054 }
2055
2056 FunctionDecl *Fn = cast<FunctionDecl>(D);
2057 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2058 /*SuppressUserConversions=*/false);
2059 }
2060
2061 // Do the resolution.
2062 OverloadCandidateSet::iterator Best;
2063 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2064 case OR_Success: {
2065 // Got one!
2066 FunctionDecl *FnDecl = Best->Function;
2067 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2068 Best->FoundDecl) == Sema::AR_inaccessible)
2069 return true;
2070
2071 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002072 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002073 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002074
Richard Smithb2f0f052016-10-10 18:54:32 +00002075 case OR_No_Viable_Function:
2076 // C++17 [expr.new]p13:
2077 // If no matching function is found and the allocated object type has
2078 // new-extended alignment, the alignment argument is removed from the
2079 // argument list, and overload resolution is performed again.
2080 if (PassAlignment) {
2081 PassAlignment = false;
2082 AlignArg = Args[1];
2083 Args.erase(Args.begin() + 1);
2084 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2085 Operator, &Candidates, AlignArg);
2086 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002087
Richard Smithb2f0f052016-10-10 18:54:32 +00002088 // MSVC will fall back on trying to find a matching global operator new
2089 // if operator new[] cannot be found. Also, MSVC will leak by not
2090 // generating a call to operator delete or operator delete[], but we
2091 // will not replicate that bug.
2092 // FIXME: Find out how this interacts with the std::align_val_t fallback
2093 // once MSVC implements it.
2094 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2095 S.Context.getLangOpts().MSVCCompat) {
2096 R.clear();
2097 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2098 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2099 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2100 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2101 Operator, nullptr);
2102 }
Richard Smith1cdec012013-09-29 04:40:38 +00002103
Richard Smithb2f0f052016-10-10 18:54:32 +00002104 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2105 << R.getLookupName() << Range;
2106
2107 // If we have aligned candidates, only note the align_val_t candidates
2108 // from AlignedCandidates and the non-align_val_t candidates from
2109 // Candidates.
2110 if (AlignedCandidates) {
2111 auto IsAligned = [](OverloadCandidate &C) {
2112 return C.Function->getNumParams() > 1 &&
2113 C.Function->getParamDecl(1)->getType()->isAlignValT();
2114 };
2115 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2116
2117 // This was an overaligned allocation, so list the aligned candidates
2118 // first.
2119 Args.insert(Args.begin() + 1, AlignArg);
2120 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2121 R.getNameLoc(), IsAligned);
2122 Args.erase(Args.begin() + 1);
2123 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2124 IsUnaligned);
2125 } else {
2126 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2127 }
Richard Smith1cdec012013-09-29 04:40:38 +00002128 return true;
2129
Richard Smithb2f0f052016-10-10 18:54:32 +00002130 case OR_Ambiguous:
2131 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2132 << R.getLookupName() << Range;
2133 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2134 return true;
2135
2136 case OR_Deleted: {
2137 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2138 << Best->Function->isDeleted()
2139 << R.getLookupName()
2140 << S.getDeletedOrUnavailableSuffix(Best->Function)
2141 << Range;
2142 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2143 return true;
2144 }
2145 }
2146 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002147}
2148
Richard Smithb2f0f052016-10-10 18:54:32 +00002149
Sebastian Redlfaf68082008-12-03 20:26:15 +00002150/// FindAllocationFunctions - Finds the overloads of operator new and delete
2151/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002152bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2153 bool UseGlobal, QualType AllocType,
Richard Smithb2f0f052016-10-10 18:54:32 +00002154 bool IsArray, bool &PassAlignment,
2155 MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002156 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00002157 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002158 // --- Choosing an allocation function ---
2159 // C++ 5.3.4p8 - 14 & 18
2160 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2161 // in the scope of the allocated class.
2162 // 2) If an array size is given, look for operator new[], else look for
2163 // operator new.
2164 // 3) The first argument is always size_t. Append the arguments from the
2165 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002166
Richard Smithb2f0f052016-10-10 18:54:32 +00002167 SmallVector<Expr*, 8> AllocArgs;
2168 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2169
2170 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002171 // FIXME: Should the Sema create the expression and embed it in the syntax
2172 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002173 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002174 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002175 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002176 Context.getSizeType(),
2177 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002178 AllocArgs.push_back(&Size);
2179
2180 QualType AlignValT = Context.VoidTy;
2181 if (PassAlignment) {
2182 DeclareGlobalNewDelete();
2183 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2184 }
2185 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2186 if (PassAlignment)
2187 AllocArgs.push_back(&Align);
2188
2189 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002190
Douglas Gregor6642ca22010-02-26 05:06:18 +00002191 // C++ [expr.new]p8:
2192 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002193 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002194 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002195 // type, the allocation function's name is operator new[] and the
2196 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002197 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002198 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002199
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002200 QualType AllocElemType = Context.getBaseElementType(AllocType);
2201
Richard Smithb2f0f052016-10-10 18:54:32 +00002202 // Find the allocation function.
2203 {
2204 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2205
2206 // C++1z [expr.new]p9:
2207 // If the new-expression begins with a unary :: operator, the allocation
2208 // function's name is looked up in the global scope. Otherwise, if the
2209 // allocated type is a class type T or array thereof, the allocation
2210 // function's name is looked up in the scope of T.
2211 if (AllocElemType->isRecordType() && !UseGlobal)
2212 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2213
2214 // We can see ambiguity here if the allocation function is found in
2215 // multiple base classes.
2216 if (R.isAmbiguous())
2217 return true;
2218
2219 // If this lookup fails to find the name, or if the allocated type is not
2220 // a class type, the allocation function's name is looked up in the
2221 // global scope.
2222 if (R.empty())
2223 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2224
2225 assert(!R.empty() && "implicitly declared allocation functions not found");
2226 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2227
2228 // We do our own custom access checks below.
2229 R.suppressDiagnostics();
2230
2231 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2232 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002233 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002234 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002235
Richard Smithb2f0f052016-10-10 18:54:32 +00002236 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002237 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002238 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002239 return false;
2240 }
2241
Richard Smithb2f0f052016-10-10 18:54:32 +00002242 // Note, the name of OperatorNew might have been changed from array to
2243 // non-array by resolveAllocationOverload.
2244 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2245 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2246 ? OO_Array_Delete
2247 : OO_Delete);
2248
Douglas Gregor6642ca22010-02-26 05:06:18 +00002249 // C++ [expr.new]p19:
2250 //
2251 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002252 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002253 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002254 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002255 // the scope of T. If this lookup fails to find the name, or if
2256 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002257 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002258 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002259 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002260 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002261 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002262 LookupQualifiedName(FoundDelete, RD);
2263 }
John McCallfb6f5262010-03-18 08:19:33 +00002264 if (FoundDelete.isAmbiguous())
2265 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002266
Richard Smithb2f0f052016-10-10 18:54:32 +00002267 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002268 if (FoundDelete.empty()) {
2269 DeclareGlobalNewDelete();
2270 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2271 }
2272
2273 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002274
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002275 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002276
John McCalld3be2c82010-09-14 21:34:24 +00002277 // Whether we're looking for a placement operator delete is dictated
2278 // by whether we selected a placement operator new, not by whether
2279 // we had explicit placement arguments. This matters for things like
2280 // struct A { void *operator new(size_t, int = 0); ... };
2281 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002282 //
2283 // We don't have any definition for what a "placement allocation function"
2284 // is, but we assume it's any allocation function whose
2285 // parameter-declaration-clause is anything other than (size_t).
2286 //
2287 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2288 // This affects whether an exception from the constructor of an overaligned
2289 // type uses the sized or non-sized form of aligned operator delete.
2290 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2291 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002292
2293 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002294 // C++ [expr.new]p20:
2295 // A declaration of a placement deallocation function matches the
2296 // declaration of a placement allocation function if it has the
2297 // same number of parameters and, after parameter transformations
2298 // (8.3.5), all parameter types except the first are
2299 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002300 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002301 // To perform this comparison, we compute the function type that
2302 // the deallocation function should have, and use that type both
2303 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00002304 //
2305 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002306 QualType ExpectedFunctionType;
2307 {
2308 const FunctionProtoType *Proto
2309 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002310
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002311 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002312 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002313 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2314 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002315
John McCalldb40c7f2010-12-14 08:05:40 +00002316 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002317 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002318 EPI.Variadic = Proto->isVariadic();
Richard Smithb2f0f052016-10-10 18:54:32 +00002319 EPI.ExceptionSpec.Type = EST_BasicNoexcept;
John McCalldb40c7f2010-12-14 08:05:40 +00002320
Douglas Gregor6642ca22010-02-26 05:06:18 +00002321 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002322 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002323 }
2324
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002325 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002326 DEnd = FoundDelete.end();
2327 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002328 FunctionDecl *Fn = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002329 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6642ca22010-02-26 05:06:18 +00002330 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2331 // Perform template argument deduction to try to match the
2332 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002333 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002334 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2335 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002336 continue;
2337 } else
2338 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2339
2340 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002341 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002342 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002343
Richard Smithb2f0f052016-10-10 18:54:32 +00002344 if (getLangOpts().CUDA)
2345 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2346 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002347 // C++1y [expr.new]p22:
2348 // For a non-placement allocation function, the normal deallocation
2349 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002350 //
2351 // Per [expr.delete]p10, this lookup prefers a member operator delete
2352 // without a size_t argument, but prefers a non-member operator delete
2353 // with a size_t where possible (which it always is in this case).
2354 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2355 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2356 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2357 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2358 &BestDeallocFns);
2359 if (Selected)
2360 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2361 else {
2362 // If we failed to select an operator, all remaining functions are viable
2363 // but ambiguous.
2364 for (auto Fn : BestDeallocFns)
2365 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002366 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002367 }
2368
2369 // C++ [expr.new]p20:
2370 // [...] If the lookup finds a single matching deallocation
2371 // function, that function will be called; otherwise, no
2372 // deallocation function will be called.
2373 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002374 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002375
Richard Smithb2f0f052016-10-10 18:54:32 +00002376 // C++1z [expr.new]p23:
2377 // If the lookup finds a usual deallocation function (3.7.4.2)
2378 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002379 // as a placement deallocation function, would have been
2380 // selected as a match for the allocation function, the program
2381 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002382 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002383 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002384 UsualDeallocFnInfo Info(*this,
2385 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002386 // Core issue, per mail to core reflector, 2016-10-09:
2387 // If this is a member operator delete, and there is a corresponding
2388 // non-sized member operator delete, this isn't /really/ a sized
2389 // deallocation function, it just happens to have a size_t parameter.
2390 bool IsSizedDelete = Info.HasSizeT;
2391 if (IsSizedDelete && !FoundGlobalDelete) {
2392 auto NonSizedDelete =
2393 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2394 /*WantAlign*/Info.HasAlignValT);
2395 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2396 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2397 IsSizedDelete = false;
2398 }
2399
2400 if (IsSizedDelete) {
2401 SourceRange R = PlaceArgs.empty()
2402 ? SourceRange()
2403 : SourceRange(PlaceArgs.front()->getLocStart(),
2404 PlaceArgs.back()->getLocEnd());
2405 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2406 if (!OperatorDelete->isImplicit())
2407 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2408 << DeleteName;
2409 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002410 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002411
2412 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2413 Matches[0].first);
2414 } else if (!Matches.empty()) {
2415 // We found multiple suitable operators. Per [expr.new]p20, that means we
2416 // call no 'operator delete' function, but we should at least warn the user.
2417 // FIXME: Suppress this warning if the construction cannot throw.
2418 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2419 << DeleteName << AllocElemType;
2420
2421 for (auto &Match : Matches)
2422 Diag(Match.second->getLocation(),
2423 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002424 }
2425
Sebastian Redlfaf68082008-12-03 20:26:15 +00002426 return false;
2427}
2428
2429/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2430/// delete. These are:
2431/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002432/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002433/// void* operator new(std::size_t) throw(std::bad_alloc);
2434/// void* operator new[](std::size_t) throw(std::bad_alloc);
2435/// void operator delete(void *) throw();
2436/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002437/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002438/// void* operator new(std::size_t);
2439/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002440/// void operator delete(void *) noexcept;
2441/// void operator delete[](void *) noexcept;
2442/// // C++1y:
2443/// void* operator new(std::size_t);
2444/// void* operator new[](std::size_t);
2445/// void operator delete(void *) noexcept;
2446/// void operator delete[](void *) noexcept;
2447/// void operator delete(void *, std::size_t) noexcept;
2448/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002449/// @endcode
2450/// Note that the placement and nothrow forms of new are *not* implicitly
2451/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002452void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002453 if (GlobalNewDeleteDeclared)
2454 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002455
Douglas Gregor87f54062009-09-15 22:30:29 +00002456 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002457 // [...] The following allocation and deallocation functions (18.4) are
2458 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002459 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002460 //
Sebastian Redl37588092011-03-14 18:08:30 +00002461 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002462 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002463 // void* operator new[](std::size_t) throw(std::bad_alloc);
2464 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002465 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002466 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002467 // void* operator new(std::size_t);
2468 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002469 // void operator delete(void*) noexcept;
2470 // void operator delete[](void*) noexcept;
2471 // C++1y:
2472 // void* operator new(std::size_t);
2473 // void* operator new[](std::size_t);
2474 // void operator delete(void*) noexcept;
2475 // void operator delete[](void*) noexcept;
2476 // void operator delete(void*, std::size_t) noexcept;
2477 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002478 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002479 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002480 // new, operator new[], operator delete, operator delete[].
2481 //
2482 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2483 // "std" or "bad_alloc" as necessary to form the exception specification.
2484 // However, we do not make these implicit declarations visible to name
2485 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002486 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002487 // The "std::bad_alloc" class has not yet been declared, so build it
2488 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002489 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2490 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002491 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002492 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002493 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002494 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002495 }
Richard Smith59139022016-09-30 22:41:36 +00002496 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002497 // The "std::align_val_t" enum class has not yet been declared, so build it
2498 // implicitly.
2499 auto *AlignValT = EnumDecl::Create(
2500 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2501 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2502 AlignValT->setIntegerType(Context.getSizeType());
2503 AlignValT->setPromotionType(Context.getSizeType());
2504 AlignValT->setImplicit(true);
2505 StdAlignValT = AlignValT;
2506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002507
Sebastian Redlfaf68082008-12-03 20:26:15 +00002508 GlobalNewDeleteDeclared = true;
2509
2510 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2511 QualType SizeT = Context.getSizeType();
2512
Richard Smith96269c52016-09-29 22:49:46 +00002513 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2514 QualType Return, QualType Param) {
2515 llvm::SmallVector<QualType, 3> Params;
2516 Params.push_back(Param);
2517
2518 // Create up to four variants of the function (sized/aligned).
2519 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2520 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002521 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002522
2523 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2524 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2525 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002526 if (Sized)
2527 Params.push_back(SizeT);
2528
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002529 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002530 if (Aligned)
2531 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2532
2533 DeclareGlobalAllocationFunction(
2534 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2535
2536 if (Aligned)
2537 Params.pop_back();
2538 }
2539 }
2540 };
2541
2542 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2543 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2544 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2545 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002546}
2547
2548/// DeclareGlobalAllocationFunction - Declares a single implicit global
2549/// allocation function if it doesn't already exist.
2550void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002551 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002552 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002553 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2554
2555 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002556 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2557 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2558 Alloc != AllocEnd; ++Alloc) {
2559 // Only look at non-template functions, as it is the predefined,
2560 // non-templated allocation function we are trying to declare here.
2561 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002562 if (Func->getNumParams() == Params.size()) {
2563 llvm::SmallVector<QualType, 3> FuncParams;
2564 for (auto *P : Func->parameters())
2565 FuncParams.push_back(
2566 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2567 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002568 // Make the function visible to name lookup, even if we found it in
2569 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002570 // allocation function, or is suppressing that function.
2571 Func->setHidden(false);
Chandler Carruth93538422010-02-03 11:02:14 +00002572 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002573 }
Chandler Carruth93538422010-02-03 11:02:14 +00002574 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002575 }
2576 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002577
Richard Smithc015bc22014-02-07 22:39:53 +00002578 FunctionProtoType::ExtProtoInfo EPI;
2579
Richard Smithf8b417c2014-02-08 00:42:45 +00002580 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002581 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002582 = (Name.getCXXOverloadedOperator() == OO_New ||
2583 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002584 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002585 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002586 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002587 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002588 EPI.ExceptionSpec.Type = EST_Dynamic;
2589 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002590 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002591 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002592 EPI.ExceptionSpec =
2593 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002595
Richard Smith96269c52016-09-29 22:49:46 +00002596 QualType FnType = Context.getFunctionType(Return, Params, EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002597 FunctionDecl *Alloc =
Abramo Bagnaradff19302011-03-08 08:55:46 +00002598 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
2599 SourceLocation(), Name,
Craig Topperc3ec1492014-05-26 06:22:03 +00002600 FnType, /*TInfo=*/nullptr, SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002601 Alloc->setImplicit();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002602
Larisse Voufo404e1422015-02-04 02:34:32 +00002603 // Implicit sized deallocation functions always have default visibility.
2604 Alloc->addAttr(VisibilityAttr::CreateImplicit(Context,
2605 VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002606
Richard Smith96269c52016-09-29 22:49:46 +00002607 llvm::SmallVector<ParmVarDecl*, 3> ParamDecls;
2608 for (QualType T : Params) {
2609 ParamDecls.push_back(
2610 ParmVarDecl::Create(Context, Alloc, SourceLocation(), SourceLocation(),
2611 nullptr, T, /*TInfo=*/nullptr, SC_None, nullptr));
2612 ParamDecls.back()->setImplicit();
Richard Smithbdd14642014-02-04 01:14:30 +00002613 }
Richard Smith96269c52016-09-29 22:49:46 +00002614 Alloc->setParams(ParamDecls);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002615
John McCallcc14d1f2010-08-24 08:50:51 +00002616 Context.getTranslationUnitDecl()->addDecl(Alloc);
Richard Smithdebcd502014-05-16 02:14:42 +00002617 IdResolver.tryAddTopLevelDecl(Alloc, Name);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002618}
2619
Richard Smith1cdec012013-09-29 04:40:38 +00002620FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2621 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002622 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002623 DeclarationName Name) {
2624 DeclareGlobalNewDelete();
2625
2626 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2627 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2628
Richard Smithb2f0f052016-10-10 18:54:32 +00002629 // FIXME: It's possible for this to result in ambiguity, through a
2630 // user-declared variadic operator delete or the enable_if attribute. We
2631 // should probably not consider those cases to be usual deallocation
2632 // functions. But for now we just make an arbitrary choice in that case.
2633 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2634 Overaligned);
2635 assert(Result.FD && "operator delete missing from global scope?");
2636 return Result.FD;
2637}
Richard Smith1cdec012013-09-29 04:40:38 +00002638
Richard Smithb2f0f052016-10-10 18:54:32 +00002639FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2640 CXXRecordDecl *RD) {
2641 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002642
Richard Smithb2f0f052016-10-10 18:54:32 +00002643 FunctionDecl *OperatorDelete = nullptr;
2644 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2645 return nullptr;
2646 if (OperatorDelete)
2647 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002648
Richard Smithb2f0f052016-10-10 18:54:32 +00002649 // If there's no class-specific operator delete, look up the global
2650 // non-array delete.
2651 return FindUsualDeallocationFunction(
2652 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2653 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002654}
2655
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002656bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2657 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002658 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002659 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002660 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002661 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002662
John McCall27b18f82009-11-17 02:14:36 +00002663 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002664 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002665
Chandler Carruthb6f99172010-06-28 00:30:51 +00002666 Found.suppressDiagnostics();
2667
Richard Smithb2f0f052016-10-10 18:54:32 +00002668 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002669
Richard Smithb2f0f052016-10-10 18:54:32 +00002670 // C++17 [expr.delete]p10:
2671 // If the deallocation functions have class scope, the one without a
2672 // parameter of type std::size_t is selected.
2673 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2674 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2675 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002676
Richard Smithb2f0f052016-10-10 18:54:32 +00002677 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002678 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002679 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002680
Richard Smithb2f0f052016-10-10 18:54:32 +00002681 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002682 if (Operator->isDeleted()) {
2683 if (Diagnose) {
2684 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002685 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002686 }
2687 return true;
2688 }
2689
Richard Smith921bd202012-02-26 09:11:52 +00002690 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002691 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002692 return true;
2693
John McCall66a87592010-08-04 00:31:26 +00002694 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002695 }
John McCall66a87592010-08-04 00:31:26 +00002696
Richard Smithb2f0f052016-10-10 18:54:32 +00002697 // We found multiple suitable operators; complain about the ambiguity.
2698 // FIXME: The standard doesn't say to do this; it appears that the intent
2699 // is that this should never happen.
2700 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002701 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002702 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2703 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002704 for (auto &Match : Matches)
2705 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002706 }
John McCall66a87592010-08-04 00:31:26 +00002707 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002708 }
2709
2710 // We did find operator delete/operator delete[] declarations, but
2711 // none of them were suitable.
2712 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002713 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002714 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2715 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002716
Richard Smithb2f0f052016-10-10 18:54:32 +00002717 for (NamedDecl *D : Found)
2718 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002719 diag::note_member_declared_here) << Name;
2720 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002721 return true;
2722 }
2723
Craig Topperc3ec1492014-05-26 06:22:03 +00002724 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002725 return false;
2726}
2727
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002728namespace {
2729/// \brief Checks whether delete-expression, and new-expression used for
2730/// initializing deletee have the same array form.
2731class MismatchingNewDeleteDetector {
2732public:
2733 enum MismatchResult {
2734 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2735 NoMismatch,
2736 /// Indicates that variable is initialized with mismatching form of \a new.
2737 VarInitMismatches,
2738 /// Indicates that member is initialized with mismatching form of \a new.
2739 MemberInitMismatches,
2740 /// Indicates that 1 or more constructors' definitions could not been
2741 /// analyzed, and they will be checked again at the end of translation unit.
2742 AnalyzeLater
2743 };
2744
2745 /// \param EndOfTU True, if this is the final analysis at the end of
2746 /// translation unit. False, if this is the initial analysis at the point
2747 /// delete-expression was encountered.
2748 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002749 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002750 HasUndefinedConstructors(false) {}
2751
2752 /// \brief Checks whether pointee of a delete-expression is initialized with
2753 /// matching form of new-expression.
2754 ///
2755 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2756 /// point where delete-expression is encountered, then a warning will be
2757 /// issued immediately. If return value is \c AnalyzeLater at the point where
2758 /// delete-expression is seen, then member will be analyzed at the end of
2759 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2760 /// couldn't be analyzed. If at least one constructor initializes the member
2761 /// with matching type of new, the return value is \c NoMismatch.
2762 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2763 /// \brief Analyzes a class member.
2764 /// \param Field Class member to analyze.
2765 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2766 /// for deleting the \p Field.
2767 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002768 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002769 /// List of mismatching new-expressions used for initialization of the pointee
2770 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2771 /// Indicates whether delete-expression was in array form.
2772 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002773
2774private:
2775 const bool EndOfTU;
2776 /// \brief Indicates that there is at least one constructor without body.
2777 bool HasUndefinedConstructors;
2778 /// \brief Returns \c CXXNewExpr from given initialization expression.
2779 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002780 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002781 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2782 /// \brief Returns whether member is initialized with mismatching form of
2783 /// \c new either by the member initializer or in-class initialization.
2784 ///
2785 /// If bodies of all constructors are not visible at the end of translation
2786 /// unit or at least one constructor initializes member with the matching
2787 /// form of \c new, mismatch cannot be proven, and this function will return
2788 /// \c NoMismatch.
2789 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2790 /// \brief Returns whether variable is initialized with mismatching form of
2791 /// \c new.
2792 ///
2793 /// If variable is initialized with matching form of \c new or variable is not
2794 /// initialized with a \c new expression, this function will return true.
2795 /// If variable is initialized with mismatching form of \c new, returns false.
2796 /// \param D Variable to analyze.
2797 bool hasMatchingVarInit(const DeclRefExpr *D);
2798 /// \brief Checks whether the constructor initializes pointee with mismatching
2799 /// form of \c new.
2800 ///
2801 /// Returns true, if member is initialized with matching form of \c new in
2802 /// member initializer list. Returns false, if member is initialized with the
2803 /// matching form of \c new in this constructor's initializer or given
2804 /// constructor isn't defined at the point where delete-expression is seen, or
2805 /// member isn't initialized by the constructor.
2806 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2807 /// \brief Checks whether member is initialized with matching form of
2808 /// \c new in member initializer list.
2809 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2810 /// Checks whether member is initialized with mismatching form of \c new by
2811 /// in-class initializer.
2812 MismatchResult analyzeInClassInitializer();
2813};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002814}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002815
2816MismatchingNewDeleteDetector::MismatchResult
2817MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2818 NewExprs.clear();
2819 assert(DE && "Expected delete-expression");
2820 IsArrayForm = DE->isArrayForm();
2821 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2822 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2823 return analyzeMemberExpr(ME);
2824 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2825 if (!hasMatchingVarInit(D))
2826 return VarInitMismatches;
2827 }
2828 return NoMismatch;
2829}
2830
2831const CXXNewExpr *
2832MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2833 assert(E != nullptr && "Expected a valid initializer expression");
2834 E = E->IgnoreParenImpCasts();
2835 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2836 if (ILE->getNumInits() == 1)
2837 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2838 }
2839
2840 return dyn_cast_or_null<const CXXNewExpr>(E);
2841}
2842
2843bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2844 const CXXCtorInitializer *CI) {
2845 const CXXNewExpr *NE = nullptr;
2846 if (Field == CI->getMember() &&
2847 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2848 if (NE->isArray() == IsArrayForm)
2849 return true;
2850 else
2851 NewExprs.push_back(NE);
2852 }
2853 return false;
2854}
2855
2856bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2857 const CXXConstructorDecl *CD) {
2858 if (CD->isImplicit())
2859 return false;
2860 const FunctionDecl *Definition = CD;
2861 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2862 HasUndefinedConstructors = true;
2863 return EndOfTU;
2864 }
2865 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2866 if (hasMatchingNewInCtorInit(CI))
2867 return true;
2868 }
2869 return false;
2870}
2871
2872MismatchingNewDeleteDetector::MismatchResult
2873MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2874 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00002875 const Expr *InitExpr = Field->getInClassInitializer();
2876 if (!InitExpr)
2877 return EndOfTU ? NoMismatch : AnalyzeLater;
2878 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002879 if (NE->isArray() != IsArrayForm) {
2880 NewExprs.push_back(NE);
2881 return MemberInitMismatches;
2882 }
2883 }
2884 return NoMismatch;
2885}
2886
2887MismatchingNewDeleteDetector::MismatchResult
2888MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2889 bool DeleteWasArrayForm) {
2890 assert(Field != nullptr && "Analysis requires a valid class member.");
2891 this->Field = Field;
2892 IsArrayForm = DeleteWasArrayForm;
2893 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2894 for (const auto *CD : RD->ctors()) {
2895 if (hasMatchingNewInCtor(CD))
2896 return NoMismatch;
2897 }
2898 if (HasUndefinedConstructors)
2899 return EndOfTU ? NoMismatch : AnalyzeLater;
2900 if (!NewExprs.empty())
2901 return MemberInitMismatches;
2902 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
2903 : NoMismatch;
2904}
2905
2906MismatchingNewDeleteDetector::MismatchResult
2907MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
2908 assert(ME != nullptr && "Expected a member expression");
2909 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2910 return analyzeField(F, IsArrayForm);
2911 return NoMismatch;
2912}
2913
2914bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
2915 const CXXNewExpr *NE = nullptr;
2916 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
2917 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
2918 NE->isArray() != IsArrayForm) {
2919 NewExprs.push_back(NE);
2920 }
2921 }
2922 return NewExprs.empty();
2923}
2924
2925static void
2926DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
2927 const MismatchingNewDeleteDetector &Detector) {
2928 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
2929 FixItHint H;
2930 if (!Detector.IsArrayForm)
2931 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
2932 else {
2933 SourceLocation RSquare = Lexer::findLocationAfterToken(
2934 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
2935 SemaRef.getLangOpts(), true);
2936 if (RSquare.isValid())
2937 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
2938 }
2939 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
2940 << Detector.IsArrayForm << H;
2941
2942 for (const auto *NE : Detector.NewExprs)
2943 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
2944 << Detector.IsArrayForm;
2945}
2946
2947void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
2948 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
2949 return;
2950 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
2951 switch (Detector.analyzeDeleteExpr(DE)) {
2952 case MismatchingNewDeleteDetector::VarInitMismatches:
2953 case MismatchingNewDeleteDetector::MemberInitMismatches: {
2954 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
2955 break;
2956 }
2957 case MismatchingNewDeleteDetector::AnalyzeLater: {
2958 DeleteExprs[Detector.Field].push_back(
2959 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
2960 break;
2961 }
2962 case MismatchingNewDeleteDetector::NoMismatch:
2963 break;
2964 }
2965}
2966
2967void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
2968 bool DeleteWasArrayForm) {
2969 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
2970 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
2971 case MismatchingNewDeleteDetector::VarInitMismatches:
2972 llvm_unreachable("This analysis should have been done for class members.");
2973 case MismatchingNewDeleteDetector::AnalyzeLater:
2974 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
2975 "translation unit.");
2976 case MismatchingNewDeleteDetector::MemberInitMismatches:
2977 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
2978 break;
2979 case MismatchingNewDeleteDetector::NoMismatch:
2980 break;
2981 }
2982}
2983
Sebastian Redlbd150f42008-11-21 19:14:01 +00002984/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2985/// @code ::delete ptr; @endcode
2986/// or
2987/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00002988ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00002989Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00002990 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002991 // C++ [expr.delete]p1:
2992 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00002993 // non-explicit conversion function to a pointer type. The result has type
2994 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002995 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00002996 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2997
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002998 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00002999 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003000 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003001 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003002
John Wiegley01296292011-04-08 18:41:53 +00003003 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003004 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003005 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003006 if (Ex.isInvalid())
3007 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003008
John Wiegley01296292011-04-08 18:41:53 +00003009 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003010
Richard Smithccc11812013-05-21 19:05:48 +00003011 class DeleteConverter : public ContextualImplicitConverter {
3012 public:
3013 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003014
Craig Toppere14c0f82014-03-12 04:55:44 +00003015 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003016 // FIXME: If we have an operator T* and an operator void*, we must pick
3017 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003018 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003019 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003020 return true;
3021 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003022 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003023
Richard Smithccc11812013-05-21 19:05:48 +00003024 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003025 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003026 return S.Diag(Loc, diag::err_delete_operand) << T;
3027 }
3028
3029 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003030 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003031 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3032 }
3033
3034 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003035 QualType T,
3036 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003037 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3038 }
3039
3040 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003041 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003042 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3043 << ConvTy;
3044 }
3045
3046 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003047 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003048 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3049 }
3050
3051 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003052 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003053 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3054 << ConvTy;
3055 }
3056
3057 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003058 QualType T,
3059 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003060 llvm_unreachable("conversion functions are permitted");
3061 }
3062 } Converter;
3063
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003064 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003065 if (Ex.isInvalid())
3066 return ExprError();
3067 Type = Ex.get()->getType();
3068 if (!Converter.match(Type))
3069 // FIXME: PerformContextualImplicitConversion should return ExprError
3070 // itself in this case.
3071 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003072
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003073 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003074 QualType PointeeElem = Context.getBaseElementType(Pointee);
3075
3076 if (unsigned AddressSpace = Pointee.getAddressSpace())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003077 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003078 diag::err_address_space_qualified_delete)
3079 << Pointee.getUnqualifiedType() << AddressSpace;
3080
Craig Topperc3ec1492014-05-26 06:22:03 +00003081 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003082 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003083 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003084 // effectively bans deletion of "void*". However, most compilers support
3085 // this, so we treat it as a warning unless we're in a SFINAE context.
3086 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003087 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003088 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003089 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003090 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003091 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003092 // FIXME: This can result in errors if the definition was imported from a
3093 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003094 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003095 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003096 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3097 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3098 }
3099 }
3100
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003101 if (Pointee->isArrayType() && !ArrayForm) {
3102 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003103 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003104 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003105 ArrayForm = true;
3106 }
3107
Anders Carlssona471db02009-08-16 20:29:29 +00003108 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3109 ArrayForm ? OO_Array_Delete : OO_Delete);
3110
Eli Friedmanae4280f2011-07-26 22:25:31 +00003111 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003112 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003113 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3114 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003115 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003116
John McCall284c48f2011-01-27 09:37:56 +00003117 // If we're allocating an array of records, check whether the
3118 // usual operator delete[] has a size_t parameter.
3119 if (ArrayForm) {
3120 // If the user specifically asked to use the global allocator,
3121 // we'll need to do the lookup into the class.
3122 if (UseGlobal)
3123 UsualArrayDeleteWantsSize =
3124 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3125
3126 // Otherwise, the usual operator delete[] should be the
3127 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003128 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003129 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003130 UsualDeallocFnInfo(*this,
3131 DeclAccessPair::make(OperatorDelete, AS_public))
3132 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003133 }
3134
Richard Smitheec915d62012-02-18 04:13:32 +00003135 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003136 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003137 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003138 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003139 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3140 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003141 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003142
Nico Weber5a9259c2016-01-15 21:45:31 +00003143 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3144 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3145 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3146 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003148
Richard Smithb2f0f052016-10-10 18:54:32 +00003149 if (!OperatorDelete) {
3150 bool IsComplete = isCompleteType(StartLoc, Pointee);
3151 bool CanProvideSize =
3152 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3153 Pointee.isDestructedType());
3154 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3155
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003156 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003157 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3158 Overaligned, DeleteName);
3159 }
Mike Stump11289f42009-09-09 15:08:12 +00003160
Eli Friedmanfa0df832012-02-02 03:46:19 +00003161 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003162
Douglas Gregorfa778132011-02-01 15:50:11 +00003163 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003164 if (PointeeRD) {
3165 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00003166 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00003167 PDiag(diag::err_access_dtor) << PointeeElem);
3168 }
3169 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003170 }
3171
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003172 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003173 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3174 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003175 AnalyzeDeleteExprMismatch(Result);
3176 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003177}
3178
Nico Weber5a9259c2016-01-15 21:45:31 +00003179void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3180 bool IsDelete, bool CallCanBeVirtual,
3181 bool WarnOnNonAbstractTypes,
3182 SourceLocation DtorLoc) {
3183 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
3184 return;
3185
3186 // C++ [expr.delete]p3:
3187 // In the first alternative (delete object), if the static type of the
3188 // object to be deleted is different from its dynamic type, the static
3189 // type shall be a base class of the dynamic type of the object to be
3190 // deleted and the static type shall have a virtual destructor or the
3191 // behavior is undefined.
3192 //
3193 const CXXRecordDecl *PointeeRD = dtor->getParent();
3194 // Note: a final class cannot be derived from, no issue there
3195 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3196 return;
3197
3198 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3199 if (PointeeRD->isAbstract()) {
3200 // If the class is abstract, we warn by default, because we're
3201 // sure the code has undefined behavior.
3202 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3203 << ClassType;
3204 } else if (WarnOnNonAbstractTypes) {
3205 // Otherwise, if this is not an array delete, it's a bit suspect,
3206 // but not necessarily wrong.
3207 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3208 << ClassType;
3209 }
3210 if (!IsDelete) {
3211 std::string TypeStr;
3212 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3213 Diag(DtorLoc, diag::note_delete_non_virtual)
3214 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3215 }
3216}
3217
Richard Smith03a4aa32016-06-23 19:02:52 +00003218Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3219 SourceLocation StmtLoc,
3220 ConditionKind CK) {
3221 ExprResult E =
3222 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3223 if (E.isInvalid())
3224 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003225 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3226 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003227}
3228
Douglas Gregor633caca2009-11-23 23:44:04 +00003229/// \brief Check the use of the given variable as a C++ condition in an if,
3230/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003231ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003232 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003233 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003234 if (ConditionVar->isInvalidDecl())
3235 return ExprError();
3236
Douglas Gregor633caca2009-11-23 23:44:04 +00003237 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003238
Douglas Gregor633caca2009-11-23 23:44:04 +00003239 // C++ [stmt.select]p2:
3240 // The declarator shall not specify a function or an array.
3241 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003242 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003243 diag::err_invalid_use_of_function_type)
3244 << ConditionVar->getSourceRange());
3245 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003246 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003247 diag::err_invalid_use_of_array_type)
3248 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003249
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003250 ExprResult Condition = DeclRefExpr::Create(
3251 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3252 /*enclosing*/ false, ConditionVar->getLocation(),
3253 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003254
Eli Friedmanfa0df832012-02-02 03:46:19 +00003255 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003256
Richard Smith03a4aa32016-06-23 19:02:52 +00003257 switch (CK) {
3258 case ConditionKind::Boolean:
3259 return CheckBooleanCondition(StmtLoc, Condition.get());
3260
Richard Smithb130fe72016-06-23 19:16:49 +00003261 case ConditionKind::ConstexprIf:
3262 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3263
Richard Smith03a4aa32016-06-23 19:02:52 +00003264 case ConditionKind::Switch:
3265 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003266 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003267
Richard Smith03a4aa32016-06-23 19:02:52 +00003268 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003269}
3270
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003271/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003272ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003273 // C++ 6.4p4:
3274 // The value of a condition that is an initialized declaration in a statement
3275 // other than a switch statement is the value of the declared variable
3276 // implicitly converted to type bool. If that conversion is ill-formed, the
3277 // program is ill-formed.
3278 // The value of a condition that is an expression is the value of the
3279 // expression, implicitly converted to bool.
3280 //
Richard Smithb130fe72016-06-23 19:16:49 +00003281 // FIXME: Return this value to the caller so they don't need to recompute it.
3282 llvm::APSInt Value(/*BitWidth*/1);
3283 return (IsConstexpr && !CondExpr->isValueDependent())
3284 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3285 CCEK_ConstexprIf)
3286 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003287}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003288
3289/// Helper function to determine whether this is the (deprecated) C++
3290/// conversion from a string literal to a pointer to non-const char or
3291/// non-const wchar_t (for narrow and wide string literals,
3292/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003293bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003294Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3295 // Look inside the implicit cast, if it exists.
3296 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3297 From = Cast->getSubExpr();
3298
3299 // A string literal (2.13.4) that is not a wide string literal can
3300 // be converted to an rvalue of type "pointer to char"; a wide
3301 // string literal can be converted to an rvalue of type "pointer
3302 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003303 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003304 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003305 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003306 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003307 // This conversion is considered only when there is an
3308 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003309 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3310 switch (StrLit->getKind()) {
3311 case StringLiteral::UTF8:
3312 case StringLiteral::UTF16:
3313 case StringLiteral::UTF32:
3314 // We don't allow UTF literals to be implicitly converted
3315 break;
3316 case StringLiteral::Ascii:
3317 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3318 ToPointeeType->getKind() == BuiltinType::Char_S);
3319 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003320 return Context.typesAreCompatible(Context.getWideCharType(),
3321 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003322 }
3323 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003324 }
3325
3326 return false;
3327}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003328
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003329static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003330 SourceLocation CastLoc,
3331 QualType Ty,
3332 CastKind Kind,
3333 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003334 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003335 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003336 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003337 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003338 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003339 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003340 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003341 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003342
Richard Smith72d74052013-07-20 19:41:36 +00003343 if (S.RequireNonAbstractType(CastLoc, Ty,
3344 diag::err_allocation_of_abstract_type))
3345 return ExprError();
3346
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003347 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003348 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003349
Richard Smith5179eb72016-06-28 19:03:57 +00003350 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3351 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003352 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003353 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003354
Richard Smithf8adcdc2014-07-17 05:12:35 +00003355 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003356 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003357 ConstructorArgs, HadMultipleCandidates,
3358 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3359 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003360 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003361 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003362
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003363 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003365
John McCalle3027922010-08-25 11:45:40 +00003366 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003367 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003368
Richard Smithd3f2d322015-02-24 21:16:19 +00003369 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003370 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003371 return ExprError();
3372
Douglas Gregora4253922010-04-16 22:17:36 +00003373 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003374 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3375 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003376 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003377 if (Result.isInvalid())
3378 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003379 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003380 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3381 CK_UserDefinedConversion, Result.get(),
3382 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003383
Douglas Gregor668443e2011-01-20 00:18:04 +00003384 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003385 }
3386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003387}
Douglas Gregora4253922010-04-16 22:17:36 +00003388
Douglas Gregor5fb53972009-01-14 15:45:31 +00003389/// PerformImplicitConversion - Perform an implicit conversion of the
3390/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003391/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003392/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003393/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003394ExprResult
3395Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003396 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003397 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003398 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003399 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003400 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003401 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3402 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003403 if (Res.isInvalid())
3404 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003405 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003406 break;
John Wiegley01296292011-04-08 18:41:53 +00003407 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003408
Anders Carlsson110b07b2009-09-15 06:28:28 +00003409 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003410
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003411 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003412 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003413 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003414 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003415 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003416 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003417
Anders Carlsson110b07b2009-09-15 06:28:28 +00003418 // If the user-defined conversion is specified by a conversion function,
3419 // the initial standard conversion sequence converts the source type to
3420 // the implicit object parameter of the conversion function.
3421 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003422 } else {
3423 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003424 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003425 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003426 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003427 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003428 // initial standard conversion sequence converts the source type to
3429 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003430 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3431 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003432 }
Richard Smith72d74052013-07-20 19:41:36 +00003433 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003434 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003435 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003436 PerformImplicitConversion(From, BeforeToType,
3437 ICS.UserDefined.Before, AA_Converting,
3438 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003439 if (Res.isInvalid())
3440 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003441 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003442 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003443
3444 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003445 = BuildCXXCastArgument(*this,
3446 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003447 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003448 CastKind, cast<CXXMethodDecl>(FD),
3449 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003450 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003451 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003452
3453 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003454 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003455
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003456 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003457
Richard Smith507840d2011-11-29 22:48:16 +00003458 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3459 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003460 }
John McCall0d1da222010-01-12 00:44:57 +00003461
3462 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003463 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003464 PDiag(diag::err_typecheck_ambiguous_condition)
3465 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003466 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003467
Douglas Gregor39c16d42008-10-24 04:54:22 +00003468 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003469 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003470
3471 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003472 bool Diagnosed =
3473 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3474 From->getType(), From, Action);
3475 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003476 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003477 }
3478
3479 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003480 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003481}
3482
Richard Smith507840d2011-11-29 22:48:16 +00003483/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003484/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003485/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003486/// expression. Flavor is the context in which we're performing this
3487/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003488ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003489Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003490 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003491 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003492 CheckedConversionKind CCK) {
3493 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003494
Mike Stump87c57ac2009-05-16 07:39:55 +00003495 // Overall FIXME: we are recomputing too many types here and doing far too
3496 // much extra work. What this means is that we need to keep track of more
3497 // information that is computed when we try the implicit conversion initially,
3498 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003499 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003500
Douglas Gregor2fe98832008-11-03 19:09:14 +00003501 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003502 // FIXME: When can ToType be a reference type?
3503 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003504 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003505 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003506 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003507 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003508 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003509 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003510 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003511 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3512 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003513 ConstructorArgs, /*HadMultipleCandidates*/ false,
3514 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3515 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003516 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003517 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003518 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3519 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003520 From, /*HadMultipleCandidates*/ false,
3521 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3522 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003523 }
3524
Douglas Gregor980fb162010-04-29 18:24:40 +00003525 // Resolve overloaded function references.
3526 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3527 DeclAccessPair Found;
3528 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3529 true, Found);
3530 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003531 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003532
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003533 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003534 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535
Douglas Gregor980fb162010-04-29 18:24:40 +00003536 From = FixOverloadedFunctionReference(From, Found, Fn);
3537 FromType = From->getType();
3538 }
3539
Richard Smitha23ab512013-05-23 00:30:41 +00003540 // If we're converting to an atomic type, first convert to the corresponding
3541 // non-atomic type.
3542 QualType ToAtomicType;
3543 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3544 ToAtomicType = ToType;
3545 ToType = ToAtomic->getValueType();
3546 }
3547
George Burgess IV8d141e02015-12-14 22:00:49 +00003548 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003549 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003550 switch (SCS.First) {
3551 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003552 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3553 FromType = FromAtomic->getValueType().getUnqualifiedType();
3554 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3555 From, /*BasePath=*/nullptr, VK_RValue);
3556 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003557 break;
3558
Eli Friedman946b7b52012-01-24 22:51:26 +00003559 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003560 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003561 ExprResult FromRes = DefaultLvalueConversion(From);
3562 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003563 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003564 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003565 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003566 }
John McCall34376a62010-12-04 03:47:34 +00003567
Douglas Gregor39c16d42008-10-24 04:54:22 +00003568 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003569 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003570 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003571 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003572 break;
3573
3574 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003575 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003576 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003577 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003578 break;
3579
3580 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003581 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003582 }
3583
Richard Smith507840d2011-11-29 22:48:16 +00003584 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003585 switch (SCS.Second) {
3586 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003587 // C++ [except.spec]p5:
3588 // [For] assignment to and initialization of pointers to functions,
3589 // pointers to member functions, and references to functions: the
3590 // target entity shall allow at least the exceptions allowed by the
3591 // source value in the assignment or initialization.
3592 switch (Action) {
3593 case AA_Assigning:
3594 case AA_Initializing:
3595 // Note, function argument passing and returning are initialization.
3596 case AA_Passing:
3597 case AA_Returning:
3598 case AA_Sending:
3599 case AA_Passing_CFAudited:
3600 if (CheckExceptionSpecCompatibility(From, ToType))
3601 return ExprError();
3602 break;
3603
3604 case AA_Casting:
3605 case AA_Converting:
3606 // Casts and implicit conversions are not initialization, so are not
3607 // checked for exception specification mismatches.
3608 break;
3609 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003610 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003611 break;
3612
Richard Smith3c4f8d22016-10-16 17:54:23 +00003613 case ICK_Function_Conversion:
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00003614 // If both sides are functions (or pointers/references to them), there could
3615 // be incompatible exception declarations.
3616 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003617 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003618
Simon Pilgrim75c26882016-09-30 14:25:09 +00003619 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003620 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00003621 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003622
Douglas Gregor39c16d42008-10-24 04:54:22 +00003623 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003624 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003625 if (ToType->isBooleanType()) {
3626 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3627 SCS.Second == ICK_Integral_Promotion &&
3628 "only enums with fixed underlying type can promote to bool");
3629 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003630 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003631 } else {
3632 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003633 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003634 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003635 break;
3636
3637 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003638 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003639 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003640 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003641 break;
3642
3643 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003644 case ICK_Complex_Conversion: {
3645 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3646 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3647 CastKind CK;
3648 if (FromEl->isRealFloatingType()) {
3649 if (ToEl->isRealFloatingType())
3650 CK = CK_FloatingComplexCast;
3651 else
3652 CK = CK_FloatingComplexToIntegralComplex;
3653 } else if (ToEl->isRealFloatingType()) {
3654 CK = CK_IntegralComplexToFloatingComplex;
3655 } else {
3656 CK = CK_IntegralComplexCast;
3657 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003658 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003659 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003660 break;
John McCall8cb679e2010-11-15 09:13:47 +00003661 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003662
Douglas Gregor39c16d42008-10-24 04:54:22 +00003663 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003664 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003665 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003666 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003667 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00003668 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003669 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003670 break;
3671
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003672 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003673 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003674 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003675 break;
3676
John McCall31168b02011-06-15 23:02:42 +00003677 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003678 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003679 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003680 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00003681 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003682 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003683 diag::ext_typecheck_convert_incompatible_pointer)
3684 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003685 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003686 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003687 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003688 diag::ext_typecheck_convert_incompatible_pointer)
3689 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003690 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00003691
Douglas Gregor33823722011-06-11 01:09:30 +00003692 if (From->getType()->isObjCObjectPointerType() &&
3693 ToType->isObjCObjectPointerType())
3694 EmitRelatedResultTypeNote(From);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003695 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00003696 else if (getLangOpts().ObjCAutoRefCount &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00003697 !CheckObjCARCUnavailableWeakConversion(ToType,
Fariborz Jahanianf2913402011-07-08 17:41:42 +00003698 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00003699 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003700 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003701 diag::err_arc_weak_unavailable_assign);
3702 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003703 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00003704 diag::err_arc_convesion_of_weak_unavailable)
3705 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00003706 << From->getSourceRange();
3707 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003708
John McCall8cb679e2010-11-15 09:13:47 +00003709 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003710 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003711 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003712 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00003713
3714 // Make sure we extend blocks if necessary.
3715 // FIXME: doing this here is really ugly.
3716 if (Kind == CK_BlockPointerToObjCPointerCast) {
3717 ExprResult E = From;
3718 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003719 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00003720 }
Fariborz Jahanian374089e2013-07-31 17:12:26 +00003721 if (getLangOpts().ObjCAutoRefCount)
3722 CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00003723 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003724 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003725 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003727
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003728 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00003729 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003730 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003731 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003732 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00003733 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003734 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00003735
3736 // We may not have been able to figure out what this member pointer resolved
3737 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00003738 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003739 (void)isCompleteType(From->getExprLoc(), From->getType());
3740 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00003741 }
David Majnemerd96b9972014-08-08 00:10:39 +00003742
Richard Smith507840d2011-11-29 22:48:16 +00003743 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003744 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003745 break;
3746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003747
Abramo Bagnara7ccce982011-04-07 09:26:19 +00003748 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003749 // Perform half-to-boolean conversion via float.
3750 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003751 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003752 FromType = Context.FloatTy;
3753 }
3754
Richard Smith507840d2011-11-29 22:48:16 +00003755 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003756 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003757 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003758 break;
3759
Douglas Gregor88d292c2010-05-13 16:44:06 +00003760 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00003761 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003762 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003763 ToType.getNonReferenceType(),
3764 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003765 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003766 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00003767 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003768 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00003769
Richard Smith507840d2011-11-29 22:48:16 +00003770 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3771 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003772 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003773 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00003774 }
3775
Douglas Gregor46188682010-05-18 22:42:18 +00003776 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003777 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003778 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003779 break;
3780
George Burgess IVdf1ed002016-01-13 01:52:39 +00003781 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00003782 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00003783 Expr *Elem = prepareVectorSplat(ToType, From).get();
3784 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3785 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003786 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00003787 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003788
Douglas Gregor46188682010-05-18 22:42:18 +00003789 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00003790 // Case 1. x -> _Complex y
3791 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3792 QualType ElType = ToComplex->getElementType();
3793 bool isFloatingComplex = ElType->isRealFloatingType();
3794
3795 // x -> y
3796 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3797 // do nothing
3798 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003799 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003800 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00003801 } else {
3802 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003803 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003804 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00003805 }
3806 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00003807 From = ImpCastExprToType(From, ToType,
3808 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003809 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00003810
3811 // Case 2. _Complex x -> y
3812 } else {
3813 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3814 assert(FromComplex);
3815
3816 QualType ElType = FromComplex->getElementType();
3817 bool isFloatingComplex = ElType->isRealFloatingType();
3818
3819 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00003820 From = ImpCastExprToType(From, ElType,
3821 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00003822 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003823 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003824
3825 // x -> y
3826 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3827 // do nothing
3828 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003829 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003830 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003831 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003832 } else {
3833 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003834 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003835 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003836 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003837 }
3838 }
Douglas Gregor46188682010-05-18 22:42:18 +00003839 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00003840
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00003841 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003842 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003843 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00003844 break;
3845 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003846
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003847 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003848 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003849 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00003850 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3851 if (FromRes.isInvalid())
3852 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003853 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003854 assert ((ConvTy == Sema::Compatible) &&
3855 "Improper transparent union conversion");
3856 (void)ConvTy;
3857 break;
3858 }
3859
Guy Benyei259f9f42013-02-07 16:05:33 +00003860 case ICK_Zero_Event_Conversion:
3861 From = ImpCastExprToType(From, ToType,
3862 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003863 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00003864 break;
3865
Douglas Gregor46188682010-05-18 22:42:18 +00003866 case ICK_Lvalue_To_Rvalue:
3867 case ICK_Array_To_Pointer:
3868 case ICK_Function_To_Pointer:
3869 case ICK_Qualification:
3870 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00003871 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00003872 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003873 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003874 }
3875
3876 switch (SCS.Third) {
3877 case ICK_Identity:
3878 // Nothing to do.
3879 break;
3880
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003881 case ICK_Qualification: {
3882 // The qualification keeps the category of the inner expression, unless the
3883 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00003884 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003885 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00003886 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003887 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00003888
Douglas Gregore981bb02011-03-14 16:13:32 +00003889 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003890 !getLangOpts().WritableStrings) {
3891 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3892 ? diag::ext_deprecated_string_literal_conversion
3893 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00003894 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003895 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00003896
Douglas Gregor39c16d42008-10-24 04:54:22 +00003897 break;
Richard Smitha23ab512013-05-23 00:30:41 +00003898 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003899
Douglas Gregor39c16d42008-10-24 04:54:22 +00003900 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003901 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003902 }
3903
Douglas Gregor298f43d2012-04-12 20:42:30 +00003904 // If this conversion sequence involved a scalar -> atomic conversion, perform
3905 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00003906 if (!ToAtomicType.isNull()) {
3907 assert(Context.hasSameType(
3908 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3909 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003910 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00003911 }
3912
George Burgess IV8d141e02015-12-14 22:00:49 +00003913 // If this conversion sequence succeeded and involved implicitly converting a
3914 // _Nullable type to a _Nonnull one, complain.
3915 if (CCK == CCK_ImplicitConversion)
3916 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
3917 From->getLocStart());
3918
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003919 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003920}
3921
Chandler Carruth8e172c62011-05-01 06:51:22 +00003922/// \brief Check the completeness of a type in a unary type trait.
3923///
3924/// If the particular type trait requires a complete type, tries to complete
3925/// it. If completing the type fails, a diagnostic is emitted and false
3926/// returned. If completing the type succeeds or no completion was required,
3927/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00003928static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00003929 SourceLocation Loc,
3930 QualType ArgTy) {
3931 // C++0x [meta.unary.prop]p3:
3932 // For all of the class templates X declared in this Clause, instantiating
3933 // that template with a template argument that is a class template
3934 // specialization may result in the implicit instantiation of the template
3935 // argument if and only if the semantics of X require that the argument
3936 // must be a complete type.
3937 // We apply this rule to all the type trait expressions used to implement
3938 // these class templates. We also try to follow any GCC documented behavior
3939 // in these expressions to ensure portability of standard libraries.
3940 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00003941 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00003942 // is_complete_type somewhat obviously cannot require a complete type.
3943 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003944 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003945
3946 // These traits are modeled on the type predicates in C++0x
3947 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3948 // requiring a complete type, as whether or not they return true cannot be
3949 // impacted by the completeness of the type.
3950 case UTT_IsVoid:
3951 case UTT_IsIntegral:
3952 case UTT_IsFloatingPoint:
3953 case UTT_IsArray:
3954 case UTT_IsPointer:
3955 case UTT_IsLvalueReference:
3956 case UTT_IsRvalueReference:
3957 case UTT_IsMemberFunctionPointer:
3958 case UTT_IsMemberObjectPointer:
3959 case UTT_IsEnum:
3960 case UTT_IsUnion:
3961 case UTT_IsClass:
3962 case UTT_IsFunction:
3963 case UTT_IsReference:
3964 case UTT_IsArithmetic:
3965 case UTT_IsFundamental:
3966 case UTT_IsObject:
3967 case UTT_IsScalar:
3968 case UTT_IsCompound:
3969 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003970 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003971
3972 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
3973 // which requires some of its traits to have the complete type. However,
3974 // the completeness of the type cannot impact these traits' semantics, and
3975 // so they don't require it. This matches the comments on these traits in
3976 // Table 49.
3977 case UTT_IsConst:
3978 case UTT_IsVolatile:
3979 case UTT_IsSigned:
3980 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00003981
3982 // This type trait always returns false, checking the type is moot.
3983 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00003984 return true;
3985
David Majnemer213bea32015-11-16 06:58:51 +00003986 // C++14 [meta.unary.prop]:
3987 // If T is a non-union class type, T shall be a complete type.
3988 case UTT_IsEmpty:
3989 case UTT_IsPolymorphic:
3990 case UTT_IsAbstract:
3991 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
3992 if (!RD->isUnion())
3993 return !S.RequireCompleteType(
3994 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
3995 return true;
3996
3997 // C++14 [meta.unary.prop]:
3998 // If T is a class type, T shall be a complete type.
3999 case UTT_IsFinal:
4000 case UTT_IsSealed:
4001 if (ArgTy->getAsCXXRecordDecl())
4002 return !S.RequireCompleteType(
4003 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4004 return true;
4005
4006 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
4007 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004008 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004009 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004010 case UTT_IsStandardLayout:
4011 case UTT_IsPOD:
4012 case UTT_IsLiteral:
David Majnemer213bea32015-11-16 06:58:51 +00004013
Alp Toker73287bf2014-01-20 00:24:09 +00004014 case UTT_IsDestructible:
4015 case UTT_IsNothrowDestructible:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004016 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004017
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004018 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00004019 // [meta.unary.prop] despite not being named the same. They are specified
4020 // by both GCC and the Embarcadero C++ compiler, and require the complete
4021 // type due to the overarching C++0x type predicates being implemented
4022 // requiring the complete type.
4023 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004024 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004025 case UTT_HasNothrowConstructor:
4026 case UTT_HasNothrowCopy:
4027 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004028 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004029 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004030 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004031 case UTT_HasTrivialCopy:
4032 case UTT_HasTrivialDestructor:
4033 case UTT_HasVirtualDestructor:
4034 // Arrays of unknown bound are expressly allowed.
4035 QualType ElTy = ArgTy;
4036 if (ArgTy->isIncompleteArrayType())
4037 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
4038
4039 // The void type is expressly allowed.
4040 if (ElTy->isVoidType())
4041 return true;
4042
4043 return !S.RequireCompleteType(
4044 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004045 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004046}
4047
Joao Matosc9523d42013-03-27 01:34:16 +00004048static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4049 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004050 bool (CXXRecordDecl::*HasTrivial)() const,
4051 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004052 bool (CXXMethodDecl::*IsDesiredOp)() const)
4053{
4054 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4055 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4056 return true;
4057
4058 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4059 DeclarationNameInfo NameInfo(Name, KeyLoc);
4060 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4061 if (Self.LookupQualifiedName(Res, RD)) {
4062 bool FoundOperator = false;
4063 Res.suppressDiagnostics();
4064 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4065 Op != OpEnd; ++Op) {
4066 if (isa<FunctionTemplateDecl>(*Op))
4067 continue;
4068
4069 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4070 if((Operator->*IsDesiredOp)()) {
4071 FoundOperator = true;
4072 const FunctionProtoType *CPT =
4073 Operator->getType()->getAs<FunctionProtoType>();
4074 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Alp Toker73287bf2014-01-20 00:24:09 +00004075 if (!CPT || !CPT->isNothrow(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004076 return false;
4077 }
4078 }
4079 return FoundOperator;
4080 }
4081 return false;
4082}
4083
Alp Toker95e7ff22014-01-01 05:57:51 +00004084static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004085 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004086 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004087
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004088 ASTContext &C = Self.Context;
4089 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004090 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004091 // Type trait expressions corresponding to the primary type category
4092 // predicates in C++0x [meta.unary.cat].
4093 case UTT_IsVoid:
4094 return T->isVoidType();
4095 case UTT_IsIntegral:
4096 return T->isIntegralType(C);
4097 case UTT_IsFloatingPoint:
4098 return T->isFloatingType();
4099 case UTT_IsArray:
4100 return T->isArrayType();
4101 case UTT_IsPointer:
4102 return T->isPointerType();
4103 case UTT_IsLvalueReference:
4104 return T->isLValueReferenceType();
4105 case UTT_IsRvalueReference:
4106 return T->isRValueReferenceType();
4107 case UTT_IsMemberFunctionPointer:
4108 return T->isMemberFunctionPointerType();
4109 case UTT_IsMemberObjectPointer:
4110 return T->isMemberDataPointerType();
4111 case UTT_IsEnum:
4112 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004113 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004114 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004115 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004116 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004117 case UTT_IsFunction:
4118 return T->isFunctionType();
4119
4120 // Type trait expressions which correspond to the convenient composition
4121 // predicates in C++0x [meta.unary.comp].
4122 case UTT_IsReference:
4123 return T->isReferenceType();
4124 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004125 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004126 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004127 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004128 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004129 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004130 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004131 // Note: semantic analysis depends on Objective-C lifetime types to be
4132 // considered scalar types. However, such types do not actually behave
4133 // like scalar types at run time (since they may require retain/release
4134 // operations), so we report them as non-scalar.
4135 if (T->isObjCLifetimeType()) {
4136 switch (T.getObjCLifetime()) {
4137 case Qualifiers::OCL_None:
4138 case Qualifiers::OCL_ExplicitNone:
4139 return true;
4140
4141 case Qualifiers::OCL_Strong:
4142 case Qualifiers::OCL_Weak:
4143 case Qualifiers::OCL_Autoreleasing:
4144 return false;
4145 }
4146 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004147
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004148 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004149 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004150 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004151 case UTT_IsMemberPointer:
4152 return T->isMemberPointerType();
4153
4154 // Type trait expressions which correspond to the type property predicates
4155 // in C++0x [meta.unary.prop].
4156 case UTT_IsConst:
4157 return T.isConstQualified();
4158 case UTT_IsVolatile:
4159 return T.isVolatileQualified();
4160 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004161 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004162 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004163 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004164 case UTT_IsStandardLayout:
4165 return T->isStandardLayoutType();
4166 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004167 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004168 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004169 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004170 case UTT_IsEmpty:
4171 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4172 return !RD->isUnion() && RD->isEmpty();
4173 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004174 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004175 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004176 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004177 return false;
4178 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004179 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004180 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004181 return false;
David Majnemer213bea32015-11-16 06:58:51 +00004182 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4183 // even then only when it is used with the 'interface struct ...' syntax
4184 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004185 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004186 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004187 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004188 case UTT_IsSealed:
4189 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004190 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004191 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004192 case UTT_IsSigned:
4193 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004194 case UTT_IsUnsigned:
4195 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004196
4197 // Type trait expressions which query classes regarding their construction,
4198 // destruction, and copying. Rather than being based directly on the
4199 // related type predicates in the standard, they are specified by both
4200 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4201 // specifications.
4202 //
4203 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4204 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004205 //
4206 // Note that these builtins do not behave as documented in g++: if a class
4207 // has both a trivial and a non-trivial special member of a particular kind,
4208 // they return false! For now, we emulate this behavior.
4209 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4210 // does not correctly compute triviality in the presence of multiple special
4211 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004212 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004213 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4214 // If __is_pod (type) is true then the trait is true, else if type is
4215 // a cv class or union type (or array thereof) with a trivial default
4216 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004217 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004218 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004219 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4220 return RD->hasTrivialDefaultConstructor() &&
4221 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004222 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004223 case UTT_HasTrivialMoveConstructor:
4224 // This trait is implemented by MSVC 2012 and needed to parse the
4225 // standard library headers. Specifically this is used as the logic
4226 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004227 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004228 return true;
4229 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4230 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4231 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004232 case UTT_HasTrivialCopy:
4233 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4234 // If __is_pod (type) is true or type is a reference type then
4235 // the trait is true, else if type is a cv class or union type
4236 // with a trivial copy constructor ([class.copy]) then the trait
4237 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004238 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004239 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004240 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4241 return RD->hasTrivialCopyConstructor() &&
4242 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004243 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004244 case UTT_HasTrivialMoveAssign:
4245 // This trait is implemented by MSVC 2012 and needed to parse the
4246 // standard library headers. Specifically it is used as the logic
4247 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004248 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004249 return true;
4250 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4251 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4252 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004253 case UTT_HasTrivialAssign:
4254 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4255 // If type is const qualified or is a reference type then the
4256 // trait is false. Otherwise if __is_pod (type) is true then the
4257 // trait is true, else if type is a cv class or union type with
4258 // a trivial copy assignment ([class.copy]) then the trait is
4259 // true, else it is false.
4260 // Note: the const and reference restrictions are interesting,
4261 // given that const and reference members don't prevent a class
4262 // from having a trivial copy assignment operator (but do cause
4263 // errors if the copy assignment operator is actually used, q.v.
4264 // [class.copy]p12).
4265
Richard Smith92f241f2012-12-08 02:53:02 +00004266 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004267 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004268 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004269 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004270 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4271 return RD->hasTrivialCopyAssignment() &&
4272 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004273 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004274 case UTT_IsDestructible:
4275 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004276 // C++14 [meta.unary.prop]:
4277 // For reference types, is_destructible<T>::value is true.
4278 if (T->isReferenceType())
4279 return true;
4280
4281 // Objective-C++ ARC: autorelease types don't require destruction.
4282 if (T->isObjCLifetimeType() &&
4283 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4284 return true;
4285
4286 // C++14 [meta.unary.prop]:
4287 // For incomplete types and function types, is_destructible<T>::value is
4288 // false.
4289 if (T->isIncompleteType() || T->isFunctionType())
4290 return false;
4291
4292 // C++14 [meta.unary.prop]:
4293 // For object types and given U equal to remove_all_extents_t<T>, if the
4294 // expression std::declval<U&>().~U() is well-formed when treated as an
4295 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4296 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4297 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4298 if (!Destructor)
4299 return false;
4300 // C++14 [dcl.fct.def.delete]p2:
4301 // A program that refers to a deleted function implicitly or
4302 // explicitly, other than to declare it, is ill-formed.
4303 if (Destructor->isDeleted())
4304 return false;
4305 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4306 return false;
4307 if (UTT == UTT_IsNothrowDestructible) {
4308 const FunctionProtoType *CPT =
4309 Destructor->getType()->getAs<FunctionProtoType>();
4310 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4311 if (!CPT || !CPT->isNothrow(C))
4312 return false;
4313 }
4314 }
4315 return true;
4316
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004317 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004318 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004319 // If __is_pod (type) is true or type is a reference type
4320 // then the trait is true, else if type is a cv class or union
4321 // type (or array thereof) with a trivial destructor
4322 // ([class.dtor]) then the trait is true, else it is
4323 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004324 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004325 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004326
John McCall31168b02011-06-15 23:02:42 +00004327 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004328 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004329 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4330 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004331
Richard Smith92f241f2012-12-08 02:53:02 +00004332 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4333 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004334 return false;
4335 // TODO: Propagate nothrowness for implicitly declared special members.
4336 case UTT_HasNothrowAssign:
4337 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4338 // If type is const qualified or is a reference type then the
4339 // trait is false. Otherwise if __has_trivial_assign (type)
4340 // is true then the trait is true, else if type is a cv class
4341 // or union type with copy assignment operators that are known
4342 // not to throw an exception then the trait is true, else it is
4343 // false.
4344 if (C.getBaseElementType(T).isConstQualified())
4345 return false;
4346 if (T->isReferenceType())
4347 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004348 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004349 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004350
Joao Matosc9523d42013-03-27 01:34:16 +00004351 if (const RecordType *RT = T->getAs<RecordType>())
4352 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4353 &CXXRecordDecl::hasTrivialCopyAssignment,
4354 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4355 &CXXMethodDecl::isCopyAssignmentOperator);
4356 return false;
4357 case UTT_HasNothrowMoveAssign:
4358 // This trait is implemented by MSVC 2012 and needed to parse the
4359 // standard library headers. Specifically this is used as the logic
4360 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004361 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004362 return true;
4363
4364 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4365 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4366 &CXXRecordDecl::hasTrivialMoveAssignment,
4367 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4368 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004369 return false;
4370 case UTT_HasNothrowCopy:
4371 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4372 // If __has_trivial_copy (type) is true then the trait is true, else
4373 // if type is a cv class or union type with copy constructors that are
4374 // known not to throw an exception then the trait is true, else it is
4375 // false.
John McCall31168b02011-06-15 23:02:42 +00004376 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004377 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004378 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4379 if (RD->hasTrivialCopyConstructor() &&
4380 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004381 return true;
4382
4383 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004384 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004385 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004386 // A template constructor is never a copy constructor.
4387 // FIXME: However, it may actually be selected at the actual overload
4388 // resolution point.
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004389 if (isa<FunctionTemplateDecl>(ND))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004390 continue;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004391 const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004392 if (Constructor->isCopyConstructor(FoundTQs)) {
4393 FoundConstructor = true;
4394 const FunctionProtoType *CPT
4395 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004396 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4397 if (!CPT)
4398 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004399 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004400 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004401 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004402 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004403 }
4404 }
4405
Richard Smith938f40b2011-06-11 17:19:42 +00004406 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004407 }
4408 return false;
4409 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004410 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004411 // If __has_trivial_constructor (type) is true then the trait is
4412 // true, else if type is a cv class or union type (or array
4413 // thereof) with a default constructor that is known not to
4414 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004415 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004416 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004417 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4418 if (RD->hasTrivialDefaultConstructor() &&
4419 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004420 return true;
4421
Alp Tokerb4bca412014-01-20 00:23:47 +00004422 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004423 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004424 // FIXME: In C++0x, a constructor template can be a default constructor.
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004425 if (isa<FunctionTemplateDecl>(ND))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004426 continue;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004427 const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND);
Sebastian Redlc15c3262010-09-13 22:02:47 +00004428 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004429 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004430 const FunctionProtoType *CPT
4431 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004432 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4433 if (!CPT)
4434 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004435 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004436 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004437 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004438 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004439 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004440 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004441 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004442 }
4443 return false;
4444 case UTT_HasVirtualDestructor:
4445 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4446 // If type is a class type with a virtual destructor ([class.dtor])
4447 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004448 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004449 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004450 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004451 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004452
4453 // These type trait expressions are modeled on the specifications for the
4454 // Embarcadero C++0x type trait functions:
4455 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4456 case UTT_IsCompleteType:
4457 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4458 // Returns True if and only if T is a complete type at the point of the
4459 // function call.
4460 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004461 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004462}
Sebastian Redl5822f082009-02-07 20:10:22 +00004463
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004464/// \brief Determine whether T has a non-trivial Objective-C lifetime in
4465/// ARC mode.
4466static bool hasNontrivialObjCLifetime(QualType T) {
4467 switch (T.getObjCLifetime()) {
4468 case Qualifiers::OCL_ExplicitNone:
4469 return false;
4470
4471 case Qualifiers::OCL_Strong:
4472 case Qualifiers::OCL_Weak:
4473 case Qualifiers::OCL_Autoreleasing:
4474 return true;
4475
4476 case Qualifiers::OCL_None:
4477 return T->isObjCLifetimeType();
4478 }
4479
4480 llvm_unreachable("Unknown ObjC lifetime qualifier");
4481}
4482
Alp Tokercbb90342013-12-13 20:49:58 +00004483static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4484 QualType RhsT, SourceLocation KeyLoc);
4485
Douglas Gregor29c42f22012-02-24 07:38:34 +00004486static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4487 ArrayRef<TypeSourceInfo *> Args,
4488 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004489 if (Kind <= UTT_Last)
4490 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4491
Alp Tokercbb90342013-12-13 20:49:58 +00004492 if (Kind <= BTT_Last)
4493 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4494 Args[1]->getType(), RParenLoc);
4495
Douglas Gregor29c42f22012-02-24 07:38:34 +00004496 switch (Kind) {
Alp Toker73287bf2014-01-20 00:24:09 +00004497 case clang::TT_IsConstructible:
4498 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004499 case clang::TT_IsTriviallyConstructible: {
4500 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004501 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004502 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004503 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004504 // definition for is_constructible, as defined below, is known to call
4505 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004506 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004507 // The predicate condition for a template specialization
4508 // is_constructible<T, Args...> shall be satisfied if and only if the
4509 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004510 // variable t:
4511 //
4512 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004513 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004514
4515 // Precondition: T and all types in the parameter pack Args shall be
4516 // complete types, (possibly cv-qualified) void, or arrays of
4517 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004518 for (const auto *TSI : Args) {
4519 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004520 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004521 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004522
Simon Pilgrim75c26882016-09-30 14:25:09 +00004523 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004524 diag::err_incomplete_type_used_in_type_trait_expr))
4525 return false;
4526 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004527
David Majnemer9658ecc2015-11-13 05:32:43 +00004528 // Make sure the first argument is not incomplete nor a function type.
4529 QualType T = Args[0]->getType();
4530 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004531 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004532
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004533 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004534 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004535 if (RD && RD->isAbstract())
4536 return false;
4537
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004538 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4539 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004540 ArgExprs.reserve(Args.size() - 1);
4541 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004542 QualType ArgTy = Args[I]->getType();
4543 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4544 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004545 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004546 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4547 ArgTy.getNonLValueExprType(S.Context),
4548 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004549 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004550 for (Expr &E : OpaqueArgExprs)
4551 ArgExprs.push_back(&E);
4552
Simon Pilgrim75c26882016-09-30 14:25:09 +00004553 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004554 // trap at translation unit scope.
4555 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
4556 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4557 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4558 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4559 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4560 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004561 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004562 if (Init.Failed())
4563 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004564
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004565 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004566 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4567 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004568
Alp Toker73287bf2014-01-20 00:24:09 +00004569 if (Kind == clang::TT_IsConstructible)
4570 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004571
Alp Toker73287bf2014-01-20 00:24:09 +00004572 if (Kind == clang::TT_IsNothrowConstructible)
4573 return S.canThrow(Result.get()) == CT_Cannot;
4574
4575 if (Kind == clang::TT_IsTriviallyConstructible) {
4576 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4577 // lifetime, this is a non-trivial construction.
4578 if (S.getLangOpts().ObjCAutoRefCount &&
David Majnemer9658ecc2015-11-13 05:32:43 +00004579 hasNontrivialObjCLifetime(T.getNonReferenceType()))
Alp Toker73287bf2014-01-20 00:24:09 +00004580 return false;
4581
4582 // The initialization succeeded; now make sure there are no non-trivial
4583 // calls.
4584 return !Result.get()->hasNonTrivialCall(S.Context);
4585 }
4586
4587 llvm_unreachable("unhandled type trait");
4588 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004589 }
Alp Tokercbb90342013-12-13 20:49:58 +00004590 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004591 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004592
Douglas Gregor29c42f22012-02-24 07:38:34 +00004593 return false;
4594}
4595
Simon Pilgrim75c26882016-09-30 14:25:09 +00004596ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4597 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004598 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004599 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004600
Alp Toker95e7ff22014-01-01 05:57:51 +00004601 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4602 *this, Kind, KWLoc, Args[0]->getType()))
4603 return ExprError();
4604
Douglas Gregor29c42f22012-02-24 07:38:34 +00004605 bool Dependent = false;
4606 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4607 if (Args[I]->getType()->isDependentType()) {
4608 Dependent = true;
4609 break;
4610 }
4611 }
Alp Tokercbb90342013-12-13 20:49:58 +00004612
4613 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004614 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004615 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4616
4617 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4618 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004619}
4620
Alp Toker88f64e62013-12-13 21:19:30 +00004621ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4622 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004623 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004624 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004625 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00004626
Douglas Gregor29c42f22012-02-24 07:38:34 +00004627 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4628 TypeSourceInfo *TInfo;
4629 QualType T = GetTypeFromParser(Args[I], &TInfo);
4630 if (!TInfo)
4631 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004632
4633 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004634 }
Alp Tokercbb90342013-12-13 20:49:58 +00004635
Douglas Gregor29c42f22012-02-24 07:38:34 +00004636 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4637}
4638
Alp Tokercbb90342013-12-13 20:49:58 +00004639static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4640 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004641 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4642 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004643
4644 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004645 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004646 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004647 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004648 // Base and Derived are not unions and name the same class type without
4649 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004650
John McCall388ef532011-01-28 22:02:36 +00004651 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4652 if (!lhsRecord) return false;
4653
4654 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4655 if (!rhsRecord) return false;
4656
4657 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4658 == (lhsRecord == rhsRecord));
4659
4660 if (lhsRecord == rhsRecord)
4661 return !lhsRecord->getDecl()->isUnion();
4662
4663 // C++0x [meta.rel]p2:
4664 // If Base and Derived are class types and are different types
4665 // (ignoring possible cv-qualifiers) then Derived shall be a
4666 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004667 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00004668 diag::err_incomplete_type_used_in_type_trait_expr))
4669 return false;
4670
4671 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4672 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4673 }
John Wiegley65497cc2011-04-27 23:09:49 +00004674 case BTT_IsSame:
4675 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00004676 case BTT_TypeCompatible:
4677 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4678 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00004679 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00004680 case BTT_IsConvertibleTo: {
4681 // C++0x [meta.rel]p4:
4682 // Given the following function prototype:
4683 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004684 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00004685 // typename add_rvalue_reference<T>::type create();
4686 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004687 // the predicate condition for a template specialization
4688 // is_convertible<From, To> shall be satisfied if and only if
4689 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00004690 // well-formed, including any implicit conversions to the return
4691 // type of the function:
4692 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004693 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00004694 // return create<From>();
4695 // }
4696 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004697 // Access checking is performed as if in a context unrelated to To and
4698 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00004699 // of the return-statement (including conversions to the return type)
4700 // is considered.
4701 //
4702 // We model the initialization as a copy-initialization of a temporary
4703 // of the appropriate type, which for this expression is identical to the
4704 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004705
4706 // Functions aren't allowed to return function or array types.
4707 if (RhsT->isFunctionType() || RhsT->isArrayType())
4708 return false;
4709
4710 // A return statement in a void function must have void type.
4711 if (RhsT->isVoidType())
4712 return LhsT->isVoidType();
4713
4714 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00004715 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004716 return false;
4717
4718 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00004719 if (LhsT->isObjectType() || LhsT->isFunctionType())
4720 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004721
4722 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00004723 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00004724 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00004725 Expr::getValueKindForType(LhsT));
4726 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004727 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00004728 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004729
4730 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00004731 // trap at translation unit scope.
4732 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00004733 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4734 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004735 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004736 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00004737 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00004738
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004739 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00004740 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4741 }
Alp Toker73287bf2014-01-20 00:24:09 +00004742
David Majnemerb3d96882016-05-23 17:21:55 +00004743 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00004744 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00004745 case BTT_IsTriviallyAssignable: {
4746 // C++11 [meta.unary.prop]p3:
4747 // is_trivially_assignable is defined as:
4748 // is_assignable<T, U>::value is true and the assignment, as defined by
4749 // is_assignable, is known to call no operation that is not trivial
4750 //
4751 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004752 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00004753 // treated as an unevaluated operand (Clause 5).
4754 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004755 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00004756 // void, or arrays of unknown bound.
4757 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004758 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004759 diag::err_incomplete_type_used_in_type_trait_expr))
4760 return false;
4761 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004762 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004763 diag::err_incomplete_type_used_in_type_trait_expr))
4764 return false;
4765
4766 // cv void is never assignable.
4767 if (LhsT->isVoidType() || RhsT->isVoidType())
4768 return false;
4769
Simon Pilgrim75c26882016-09-30 14:25:09 +00004770 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00004771 // declval<U>().
4772 if (LhsT->isObjectType() || LhsT->isFunctionType())
4773 LhsT = Self.Context.getRValueReferenceType(LhsT);
4774 if (RhsT->isObjectType() || RhsT->isFunctionType())
4775 RhsT = Self.Context.getRValueReferenceType(RhsT);
4776 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4777 Expr::getValueKindForType(LhsT));
4778 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4779 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004780
4781 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00004782 // trap at translation unit scope.
4783 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
4784 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4785 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004786 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4787 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004788 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4789 return false;
4790
David Majnemerb3d96882016-05-23 17:21:55 +00004791 if (BTT == BTT_IsAssignable)
4792 return true;
4793
Alp Toker73287bf2014-01-20 00:24:09 +00004794 if (BTT == BTT_IsNothrowAssignable)
4795 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004796
Alp Toker73287bf2014-01-20 00:24:09 +00004797 if (BTT == BTT_IsTriviallyAssignable) {
4798 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4799 // lifetime, this is a non-trivial assignment.
4800 if (Self.getLangOpts().ObjCAutoRefCount &&
4801 hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
4802 return false;
4803
4804 return !Result.get()->hasNonTrivialCall(Self.Context);
4805 }
4806
4807 llvm_unreachable("unhandled type trait");
4808 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00004809 }
Alp Tokercbb90342013-12-13 20:49:58 +00004810 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004811 }
4812 llvm_unreachable("Unknown type trait or not implemented");
4813}
4814
John Wiegley6242b6a2011-04-28 00:16:57 +00004815ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4816 SourceLocation KWLoc,
4817 ParsedType Ty,
4818 Expr* DimExpr,
4819 SourceLocation RParen) {
4820 TypeSourceInfo *TSInfo;
4821 QualType T = GetTypeFromParser(Ty, &TSInfo);
4822 if (!TSInfo)
4823 TSInfo = Context.getTrivialTypeSourceInfo(T);
4824
4825 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4826}
4827
4828static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4829 QualType T, Expr *DimExpr,
4830 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004831 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00004832
4833 switch(ATT) {
4834 case ATT_ArrayRank:
4835 if (T->isArrayType()) {
4836 unsigned Dim = 0;
4837 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4838 ++Dim;
4839 T = AT->getElementType();
4840 }
4841 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00004842 }
John Wiegleyd3522222011-04-28 02:06:46 +00004843 return 0;
4844
John Wiegley6242b6a2011-04-28 00:16:57 +00004845 case ATT_ArrayExtent: {
4846 llvm::APSInt Value;
4847 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00004848 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00004849 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00004850 false).isInvalid())
4851 return 0;
4852 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00004853 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4854 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00004855 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00004856 }
Richard Smithf4c51d92012-02-04 09:53:13 +00004857 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00004858
4859 if (T->isArrayType()) {
4860 unsigned D = 0;
4861 bool Matched = false;
4862 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4863 if (Dim == D) {
4864 Matched = true;
4865 break;
4866 }
4867 ++D;
4868 T = AT->getElementType();
4869 }
4870
John Wiegleyd3522222011-04-28 02:06:46 +00004871 if (Matched && T->isArrayType()) {
4872 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4873 return CAT->getSize().getLimitedValue();
4874 }
John Wiegley6242b6a2011-04-28 00:16:57 +00004875 }
John Wiegleyd3522222011-04-28 02:06:46 +00004876 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00004877 }
4878 }
4879 llvm_unreachable("Unknown type trait or not implemented");
4880}
4881
4882ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4883 SourceLocation KWLoc,
4884 TypeSourceInfo *TSInfo,
4885 Expr* DimExpr,
4886 SourceLocation RParen) {
4887 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00004888
Chandler Carruthc5276e52011-05-01 08:48:21 +00004889 // FIXME: This should likely be tracked as an APInt to remove any host
4890 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004891 uint64_t Value = 0;
4892 if (!T->isDependentType())
4893 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4894
Chandler Carruthc5276e52011-05-01 08:48:21 +00004895 // While the specification for these traits from the Embarcadero C++
4896 // compiler's documentation says the return type is 'unsigned int', Clang
4897 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4898 // compiler, there is no difference. On several other platforms this is an
4899 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004900 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4901 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00004902}
4903
John Wiegleyf9f65842011-04-25 06:54:41 +00004904ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004905 SourceLocation KWLoc,
4906 Expr *Queried,
4907 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004908 // If error parsing the expression, ignore.
4909 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004910 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00004911
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004912 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004913
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004914 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00004915}
4916
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004917static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4918 switch (ET) {
4919 case ET_IsLValueExpr: return E->isLValue();
4920 case ET_IsRValueExpr: return E->isRValue();
4921 }
4922 llvm_unreachable("Expression trait not covered by switch");
4923}
4924
John Wiegleyf9f65842011-04-25 06:54:41 +00004925ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004926 SourceLocation KWLoc,
4927 Expr *Queried,
4928 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004929 if (Queried->isTypeDependent()) {
4930 // Delay type-checking for type-dependent expressions.
4931 } else if (Queried->getType()->isPlaceholderType()) {
4932 ExprResult PE = CheckPlaceholderExpr(Queried);
4933 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004934 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004935 }
4936
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004937 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00004938
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004939 return new (Context)
4940 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00004941}
4942
Richard Trieu82402a02011-09-15 21:56:47 +00004943QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004944 ExprValueKind &VK,
4945 SourceLocation Loc,
4946 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004947 assert(!LHS.get()->getType()->isPlaceholderType() &&
4948 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00004949 "placeholders should have been weeded out by now");
4950
4951 // The LHS undergoes lvalue conversions if this is ->*.
4952 if (isIndirect) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004953 LHS = DefaultLvalueConversion(LHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00004954 if (LHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004955 }
4956
4957 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004958 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00004959 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004960
Sebastian Redl5822f082009-02-07 20:10:22 +00004961 const char *OpSpelling = isIndirect ? "->*" : ".*";
4962 // C++ 5.5p2
4963 // The binary operator .* [p3: ->*] binds its second operand, which shall
4964 // be of type "pointer to member of T" (where T is a completely-defined
4965 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00004966 QualType RHSType = RHS.get()->getType();
4967 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004968 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00004969 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00004970 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00004971 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004972 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004973
Sebastian Redl5822f082009-02-07 20:10:22 +00004974 QualType Class(MemPtr->getClass(), 0);
4975
Douglas Gregord07ba342010-10-13 20:41:14 +00004976 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
4977 // member pointer points must be completely-defined. However, there is no
4978 // reason for this semantic distinction, and the rule is not enforced by
4979 // other compilers. Therefore, we do not check this property, as it is
4980 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00004981
Sebastian Redl5822f082009-02-07 20:10:22 +00004982 // C++ 5.5p2
4983 // [...] to its first operand, which shall be of class T or of a class of
4984 // which T is an unambiguous and accessible base class. [p3: a pointer to
4985 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00004986 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00004987 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004988 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
4989 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00004990 else {
4991 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00004992 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00004993 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00004994 return QualType();
4995 }
4996 }
4997
Richard Trieu82402a02011-09-15 21:56:47 +00004998 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00004999 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005000 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5001 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005002 return QualType();
5003 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005004
Richard Smith0f59cb32015-12-18 21:45:41 +00005005 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005006 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005007 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005008 return QualType();
5009 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005010
5011 CXXCastPath BasePath;
5012 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5013 SourceRange(LHS.get()->getLocStart(),
5014 RHS.get()->getLocEnd()),
5015 &BasePath))
5016 return QualType();
5017
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005018 // Cast LHS to type of use.
5019 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005020 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005021 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005022 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005023 }
5024
Richard Trieu82402a02011-09-15 21:56:47 +00005025 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005026 // Diagnose use of pointer-to-member type which when used as
5027 // the functional cast in a pointer-to-member expression.
5028 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5029 return QualType();
5030 }
John McCall7decc9e2010-11-18 06:31:45 +00005031
Sebastian Redl5822f082009-02-07 20:10:22 +00005032 // C++ 5.5p2
5033 // The result is an object or a function of the type specified by the
5034 // second operand.
5035 // The cv qualifiers are the union of those in the pointer and the left side,
5036 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005037 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005038 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005039
Douglas Gregor1d042092011-01-26 16:40:18 +00005040 // C++0x [expr.mptr.oper]p6:
5041 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005042 // ill-formed if the second operand is a pointer to member function with
5043 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5044 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005045 // is a pointer to member function with ref-qualifier &&.
5046 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5047 switch (Proto->getRefQualifier()) {
5048 case RQ_None:
5049 // Do nothing
5050 break;
5051
5052 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005053 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005054 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005055 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005056 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005057
Douglas Gregor1d042092011-01-26 16:40:18 +00005058 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005059 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005060 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005061 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005062 break;
5063 }
5064 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005065
John McCall7decc9e2010-11-18 06:31:45 +00005066 // C++ [expr.mptr.oper]p6:
5067 // The result of a .* expression whose second operand is a pointer
5068 // to a data member is of the same value category as its
5069 // first operand. The result of a .* expression whose second
5070 // operand is a pointer to a member function is a prvalue. The
5071 // result of an ->* expression is an lvalue if its second operand
5072 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005073 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005074 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005075 return Context.BoundMemberTy;
5076 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005077 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005078 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005079 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005080 }
John McCall7decc9e2010-11-18 06:31:45 +00005081
Sebastian Redl5822f082009-02-07 20:10:22 +00005082 return Result;
5083}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005084
Richard Smith2414bca2016-04-25 19:30:37 +00005085/// \brief Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005086///
5087/// This is part of the parameter validation for the ? operator. If either
5088/// value operand is a class type, the two operands are attempted to be
5089/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005090/// It returns true if the program is ill-formed and has already been diagnosed
5091/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005092static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5093 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005094 bool &HaveConversion,
5095 QualType &ToType) {
5096 HaveConversion = false;
5097 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005098
5099 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005100 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005101 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005102 // The process for determining whether an operand expression E1 of type T1
5103 // can be converted to match an operand expression E2 of type T2 is defined
5104 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005105 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5106 // implicitly converted to type "lvalue reference to T2", subject to the
5107 // constraint that in the conversion the reference must bind directly to
5108 // an lvalue.
5109 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5110 // implicitly conveted to the type "rvalue reference to R2", subject to
5111 // the constraint that the reference must bind directly.
5112 if (To->isLValue() || To->isXValue()) {
5113 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5114 : Self.Context.getRValueReferenceType(ToType);
5115
Douglas Gregor838fcc32010-03-26 20:14:36 +00005116 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005117
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005118 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005119 if (InitSeq.isDirectReferenceBinding()) {
5120 ToType = T;
5121 HaveConversion = true;
5122 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005124
Douglas Gregor838fcc32010-03-26 20:14:36 +00005125 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005126 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005127 }
John McCall65eb8792010-02-25 01:37:24 +00005128
Sebastian Redl1a99f442009-04-16 17:51:27 +00005129 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5130 // -- if E1 and E2 have class type, and the underlying class types are
5131 // the same or one is a base class of the other:
5132 QualType FTy = From->getType();
5133 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005134 const RecordType *FRec = FTy->getAs<RecordType>();
5135 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005136 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005137 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5138 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5139 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005140 // E1 can be converted to match E2 if the class of T2 is the
5141 // same type as, or a base class of, the class of T1, and
5142 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005143 if (FRec == TRec || FDerivedFromT) {
5144 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005145 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005146 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005147 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005148 HaveConversion = true;
5149 return false;
5150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005151
Douglas Gregor838fcc32010-03-26 20:14:36 +00005152 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005153 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005154 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005155 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005156
Douglas Gregor838fcc32010-03-26 20:14:36 +00005157 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005158 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005159
Douglas Gregor838fcc32010-03-26 20:14:36 +00005160 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5161 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005162 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005163 // an rvalue).
5164 //
5165 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5166 // to the array-to-pointer or function-to-pointer conversions.
5167 if (!TTy->getAs<TagType>())
5168 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005169
Douglas Gregor838fcc32010-03-26 20:14:36 +00005170 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005171 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005172 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005173 ToType = TTy;
5174 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005175 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005176
Sebastian Redl1a99f442009-04-16 17:51:27 +00005177 return false;
5178}
5179
5180/// \brief Try to find a common type for two according to C++0x 5.16p5.
5181///
5182/// This is part of the parameter validation for the ? operator. If either
5183/// value operand is a class type, overload resolution is used to find a
5184/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005185static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005186 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005187 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005188 OverloadCandidateSet CandidateSet(QuestionLoc,
5189 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005190 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005191 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005192
5193 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005194 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005195 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005196 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00005197 ExprResult LHSRes =
5198 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
5199 Best->Conversions[0], Sema::AA_Converting);
5200 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005201 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005202 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005203
5204 ExprResult RHSRes =
5205 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
5206 Best->Conversions[1], Sema::AA_Converting);
5207 if (RHSRes.isInvalid())
5208 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005209 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005210 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005211 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005212 return false;
John Wiegley01296292011-04-08 18:41:53 +00005213 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005214
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005215 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005216
5217 // Emit a better diagnostic if one of the expressions is a null pointer
5218 // constant and the other is a pointer type. In this case, the user most
5219 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005220 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005221 return true;
5222
5223 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005224 << LHS.get()->getType() << RHS.get()->getType()
5225 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005226 return true;
5227
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005228 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005229 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005230 << LHS.get()->getType() << RHS.get()->getType()
5231 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005232 // FIXME: Print the possible common types by printing the return types of
5233 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005234 break;
5235
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005236 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005237 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005238 }
5239 return true;
5240}
5241
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005242/// \brief Perform an "extended" implicit conversion as returned by
5243/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005244static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005245 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005246 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005247 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005248 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005249 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005250 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005251 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005252 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005253
John Wiegley01296292011-04-08 18:41:53 +00005254 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005255 return false;
5256}
5257
Sebastian Redl1a99f442009-04-16 17:51:27 +00005258/// \brief Check the operands of ?: under C++ semantics.
5259///
5260/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5261/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005262QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5263 ExprResult &RHS, ExprValueKind &VK,
5264 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005265 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005266 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5267 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005268
Richard Smith45edb702012-08-07 22:06:48 +00005269 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005270 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00005271 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005272 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005273 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005274 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005275 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005276 }
5277
John McCall7decc9e2010-11-18 06:31:45 +00005278 // Assume r-value.
5279 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005280 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005281
Sebastian Redl1a99f442009-04-16 17:51:27 +00005282 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005283 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005284 return Context.DependentTy;
5285
Richard Smith45edb702012-08-07 22:06:48 +00005286 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005287 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005288 QualType LTy = LHS.get()->getType();
5289 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005290 bool LVoid = LTy->isVoidType();
5291 bool RVoid = RTy->isVoidType();
5292 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005293 // ... one of the following shall hold:
5294 // -- The second or the third operand (but not both) is a (possibly
5295 // parenthesized) throw-expression; the result is of the type
5296 // and value category of the other.
5297 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5298 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5299 if (LThrow != RThrow) {
5300 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5301 VK = NonThrow->getValueKind();
5302 // DR (no number yet): the result is a bit-field if the
5303 // non-throw-expression operand is a bit-field.
5304 OK = NonThrow->getObjectKind();
5305 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005306 }
5307
Sebastian Redl1a99f442009-04-16 17:51:27 +00005308 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005309 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005310 if (LVoid && RVoid)
5311 return Context.VoidTy;
5312
5313 // Neither holds, error.
5314 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5315 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005316 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005317 return QualType();
5318 }
5319
5320 // Neither is void.
5321
Richard Smithf2b084f2012-08-08 06:13:49 +00005322 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005323 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005324 // either has (cv) class type [...] an attempt is made to convert each of
5325 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005326 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005327 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005328 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005329 QualType L2RType, R2LType;
5330 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005331 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005332 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005333 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005334 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005335
Sebastian Redl1a99f442009-04-16 17:51:27 +00005336 // If both can be converted, [...] the program is ill-formed.
5337 if (HaveL2R && HaveR2L) {
5338 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005339 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005340 return QualType();
5341 }
5342
5343 // If exactly one conversion is possible, that conversion is applied to
5344 // the chosen operand and the converted operands are used in place of the
5345 // original operands for the remainder of this section.
5346 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005347 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005348 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005349 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005350 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005351 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005352 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005353 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005354 }
5355 }
5356
Richard Smithf2b084f2012-08-08 06:13:49 +00005357 // C++11 [expr.cond]p3
5358 // if both are glvalues of the same value category and the same type except
5359 // for cv-qualification, an attempt is made to convert each of those
5360 // operands to the type of the other.
5361 ExprValueKind LVK = LHS.get()->getValueKind();
5362 ExprValueKind RVK = RHS.get()->getValueKind();
5363 if (!Context.hasSameType(LTy, RTy) &&
5364 Context.hasSameUnqualifiedType(LTy, RTy) &&
5365 LVK == RVK && LVK != VK_RValue) {
5366 // Since the unqualified types are reference-related and we require the
5367 // result to be as if a reference bound directly, the only conversion
5368 // we can perform is to add cv-qualifiers.
5369 Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
5370 Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
5371 if (RCVR.isStrictSupersetOf(LCVR)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005372 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005373 LTy = LHS.get()->getType();
5374 }
5375 else if (LCVR.isStrictSupersetOf(RCVR)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005376 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005377 RTy = RHS.get()->getType();
5378 }
5379 }
5380
5381 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005382 // If the second and third operands are glvalues of the same value
5383 // category and have the same type, the result is of that type and
5384 // value category and it is a bit-field if the second or the third
5385 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005386 // We only extend this to bitfields, not to the crazy other kinds of
5387 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005388 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005389 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005390 LHS.get()->isOrdinaryOrBitFieldObject() &&
5391 RHS.get()->isOrdinaryOrBitFieldObject()) {
5392 VK = LHS.get()->getValueKind();
5393 if (LHS.get()->getObjectKind() == OK_BitField ||
5394 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005395 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00005396 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005397 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005398
Richard Smithf2b084f2012-08-08 06:13:49 +00005399 // C++11 [expr.cond]p5
5400 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005401 // do not have the same type, and either has (cv) class type, ...
5402 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5403 // ... overload resolution is used to determine the conversions (if any)
5404 // to be applied to the operands. If the overload resolution fails, the
5405 // program is ill-formed.
5406 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5407 return QualType();
5408 }
5409
Richard Smithf2b084f2012-08-08 06:13:49 +00005410 // C++11 [expr.cond]p6
5411 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005412 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005413 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5414 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005415 if (LHS.isInvalid() || RHS.isInvalid())
5416 return QualType();
5417 LTy = LHS.get()->getType();
5418 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005419
5420 // After those conversions, one of the following shall hold:
5421 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005422 // is of that type. If the operands have class type, the result
5423 // is a prvalue temporary of the result type, which is
5424 // copy-initialized from either the second operand or the third
5425 // operand depending on the value of the first operand.
5426 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5427 if (LTy->isRecordType()) {
5428 // The operands have class type. Make a temporary copy.
David Blaikie6154ef92012-09-10 22:05:41 +00005429 if (RequireNonAbstractType(QuestionLoc, LTy,
5430 diag::err_allocation_of_abstract_type))
5431 return QualType();
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005432 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005433
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005434 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5435 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005436 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005437 if (LHSCopy.isInvalid())
5438 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005439
5440 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5441 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005442 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005443 if (RHSCopy.isInvalid())
5444 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005445
John Wiegley01296292011-04-08 18:41:53 +00005446 LHS = LHSCopy;
5447 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005448 }
5449
Sebastian Redl1a99f442009-04-16 17:51:27 +00005450 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005451 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005452
Douglas Gregor46188682010-05-18 22:42:18 +00005453 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005454 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005455 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5456 /*AllowBothBool*/true,
5457 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005458
Sebastian Redl1a99f442009-04-16 17:51:27 +00005459 // -- The second and third operands have arithmetic or enumeration type;
5460 // the usual arithmetic conversions are performed to bring them to a
5461 // common type, and the result is of that type.
5462 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005463 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005464 if (LHS.isInvalid() || RHS.isInvalid())
5465 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005466 if (ResTy.isNull()) {
5467 Diag(QuestionLoc,
5468 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5469 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5470 return QualType();
5471 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005472
5473 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5474 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5475
5476 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005477 }
5478
5479 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005480 // type and the other is a null pointer constant, or both are null
5481 // pointer constants, at least one of which is non-integral; pointer
5482 // conversions and qualification conversions are performed to bring them
5483 // to their composite pointer type. The result is of the composite
5484 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005485 // -- The second and third operands have pointer to member type, or one has
5486 // pointer to member type and the other is a null pointer constant;
5487 // pointer to member conversions and qualification conversions are
5488 // performed to bring them to a common type, whose cv-qualification
5489 // shall match the cv-qualification of either the second or the third
5490 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005491 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005492 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Craig Topperc3ec1492014-05-26 06:22:03 +00005493 isSFINAEContext() ? nullptr
5494 : &NonStandardCompositeType);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005495 if (!Composite.isNull()) {
5496 if (NonStandardCompositeType)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005497 Diag(QuestionLoc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005498 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
5499 << LTy << RTy << Composite
John Wiegley01296292011-04-08 18:41:53 +00005500 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005501
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005502 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005503 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005504
Douglas Gregor697a3912010-04-01 22:47:07 +00005505 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005506 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5507 if (!Composite.isNull())
5508 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005509
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005510 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005511 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005512 return QualType();
5513
Sebastian Redl1a99f442009-04-16 17:51:27 +00005514 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005515 << LHS.get()->getType() << RHS.get()->getType()
5516 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005517 return QualType();
5518}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005519
5520/// \brief Find a merged pointer type and convert the two expressions to it.
5521///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005522/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smithf2b084f2012-08-08 06:13:49 +00005523/// and @p E2 according to C++11 5.9p2. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005524/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005525/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005526///
Douglas Gregor19175ff2010-04-16 23:20:25 +00005527/// \param Loc The location of the operator requiring these two expressions to
5528/// be converted to the composite pointer type.
5529///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005530/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
5531/// a non-standard (but still sane) composite type to which both expressions
5532/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
5533/// will be set true.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005534QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00005535 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005536 bool *NonStandardCompositeType) {
5537 if (NonStandardCompositeType)
5538 *NonStandardCompositeType = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005539
David Blaikiebbafb8a2012-03-11 07:00:24 +00005540 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005541 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005542
Richard Smithf2b084f2012-08-08 06:13:49 +00005543 // C++11 5.9p2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005544 // Pointer conversions and qualification conversions are performed on
5545 // pointer operands to bring them to their composite pointer type. If
5546 // one operand is a null pointer constant, the composite pointer type is
Richard Smithf2b084f2012-08-08 06:13:49 +00005547 // std::nullptr_t if the other operand is also a null pointer constant or,
5548 // if the other operand is a pointer, the type of the other operand.
5549 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
5550 !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
5551 if (T1->isNullPtrType() &&
5552 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005553 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
Richard Smithf2b084f2012-08-08 06:13:49 +00005554 return T1;
5555 }
5556 if (T2->isNullPtrType() &&
5557 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005558 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
Richard Smithf2b084f2012-08-08 06:13:49 +00005559 return T2;
5560 }
5561 return QualType();
5562 }
5563
Douglas Gregor56751b52009-09-25 04:25:58 +00005564 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005565 if (T2->isMemberPointerType())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005566 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005567 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005568 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005569 return T2;
5570 }
Douglas Gregor56751b52009-09-25 04:25:58 +00005571 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005572 if (T1->isMemberPointerType())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005573 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005574 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005575 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005576 return T1;
5577 }
Mike Stump11289f42009-09-09 15:08:12 +00005578
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005579 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00005580 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
5581 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005582 return QualType();
5583
5584 // Otherwise, of one of the operands has type "pointer to cv1 void," then
5585 // the other has type "pointer to cv2 T" and the composite pointer type is
5586 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
5587 // Otherwise, the composite pointer type is a pointer type similar to the
5588 // type of one of the operands, with a cv-qualification signature that is
5589 // the union of the cv-qualification signatures of the operand types.
5590 // In practice, the first part here is redundant; it's subsumed by the second.
5591 // What we do here is, we build the two possible composite types, and try the
5592 // conversions in both directions. If only one works, or if the two composite
5593 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00005594 // FIXME: extended qualifiers?
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005595 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redl658262f2009-11-16 21:03:45 +00005596 QualifierVector QualifierUnion;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005597 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redl658262f2009-11-16 21:03:45 +00005598 ContainingClassVector;
5599 ContainingClassVector MemberOfClass;
5600 QualType Composite1 = Context.getCanonicalType(T1),
5601 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005602 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005603 do {
5604 const PointerType *Ptr1, *Ptr2;
5605 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5606 (Ptr2 = Composite2->getAs<PointerType>())) {
5607 Composite1 = Ptr1->getPointeeType();
5608 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005609
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005610 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005611 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005612 if (NonStandardCompositeType &&
5613 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5614 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005615
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005616 QualifierUnion.push_back(
5617 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00005618 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005619 continue;
5620 }
Mike Stump11289f42009-09-09 15:08:12 +00005621
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005622 const MemberPointerType *MemPtr1, *MemPtr2;
5623 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5624 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5625 Composite1 = MemPtr1->getPointeeType();
5626 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005627
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005628 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005629 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005630 if (NonStandardCompositeType &&
5631 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5632 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005633
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005634 QualifierUnion.push_back(
5635 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5636 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5637 MemPtr2->getClass()));
5638 continue;
5639 }
Mike Stump11289f42009-09-09 15:08:12 +00005640
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005641 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00005642
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005643 // Cannot unwrap any more types.
5644 break;
5645 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00005646
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005647 if (NeedConstBefore && NonStandardCompositeType) {
5648 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005649 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005650 // requirements of C++ [conv.qual]p4 bullet 3.
5651 for (unsigned I = 0; I != NeedConstBefore; ++I) {
5652 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
5653 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
5654 *NonStandardCompositeType = true;
5655 }
5656 }
5657 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005658
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005659 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00005660 ContainingClassVector::reverse_iterator MOC
5661 = MemberOfClass.rbegin();
5662 for (QualifierVector::reverse_iterator
5663 I = QualifierUnion.rbegin(),
5664 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005665 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00005666 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005667 if (MOC->first && MOC->second) {
5668 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005669 Composite1 = Context.getMemberPointerType(
5670 Context.getQualifiedType(Composite1, Quals),
5671 MOC->first);
5672 Composite2 = Context.getMemberPointerType(
5673 Context.getQualifiedType(Composite2, Quals),
5674 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005675 } else {
5676 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005677 Composite1
5678 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5679 Composite2
5680 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005681 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005682 }
5683
Douglas Gregor19175ff2010-04-16 23:20:25 +00005684 // Try to convert to the first composite pointer type.
5685 InitializedEntity Entity1
5686 = InitializedEntity::InitializeTemporary(Composite1);
5687 InitializationKind Kind
5688 = InitializationKind::CreateCopy(Loc, SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005689 InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
5690 InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
Mike Stump11289f42009-09-09 15:08:12 +00005691
Douglas Gregor19175ff2010-04-16 23:20:25 +00005692 if (E1ToC1 && E2ToC1) {
5693 // Conversion to Composite1 is viable.
5694 if (!Context.hasSameType(Composite1, Composite2)) {
5695 // Composite2 is a different type from Composite1. Check whether
5696 // Composite2 is also viable.
5697 InitializedEntity Entity2
5698 = InitializedEntity::InitializeTemporary(Composite2);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005699 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
5700 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005701 if (E1ToC2 && E2ToC2) {
5702 // Both Composite1 and Composite2 are viable and are different;
5703 // this is an ambiguity.
5704 return QualType();
5705 }
5706 }
5707
5708 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00005709 ExprResult E1Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005710 = E1ToC1.Perform(*this, Entity1, Kind, E1);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005711 if (E1Result.isInvalid())
5712 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005713 E1 = E1Result.getAs<Expr>();
Douglas Gregor19175ff2010-04-16 23:20:25 +00005714
5715 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00005716 ExprResult E2Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005717 = E2ToC1.Perform(*this, Entity1, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005718 if (E2Result.isInvalid())
5719 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005720 E2 = E2Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005721
Douglas Gregor19175ff2010-04-16 23:20:25 +00005722 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005723 }
5724
Douglas Gregor19175ff2010-04-16 23:20:25 +00005725 // Check whether Composite2 is viable.
5726 InitializedEntity Entity2
5727 = InitializedEntity::InitializeTemporary(Composite2);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005728 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
5729 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005730 if (!E1ToC2 || !E2ToC2)
5731 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005732
Douglas Gregor19175ff2010-04-16 23:20:25 +00005733 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00005734 ExprResult E1Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005735 = E1ToC2.Perform(*this, Entity2, Kind, E1);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005736 if (E1Result.isInvalid())
5737 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005738 E1 = E1Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005739
Douglas Gregor19175ff2010-04-16 23:20:25 +00005740 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00005741 ExprResult E2Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005742 = E2ToC2.Perform(*this, Entity2, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005743 if (E2Result.isInvalid())
5744 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005745 E2 = E2Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005746
Douglas Gregor19175ff2010-04-16 23:20:25 +00005747 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005748}
Anders Carlsson85a307d2009-05-17 18:41:29 +00005749
John McCalldadc5752010-08-24 06:29:42 +00005750ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00005751 if (!E)
5752 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005753
John McCall31168b02011-06-15 23:02:42 +00005754 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
5755
5756 // If the result is a glvalue, we shouldn't bind it.
5757 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005758 return E;
Mike Stump11289f42009-09-09 15:08:12 +00005759
John McCall31168b02011-06-15 23:02:42 +00005760 // In ARC, calls that return a retainable type can return retained,
5761 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005762 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00005763 E->getType()->isObjCRetainableType()) {
5764
5765 bool ReturnsRetained;
5766
5767 // For actual calls, we compute this by examining the type of the
5768 // called value.
5769 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5770 Expr *Callee = Call->getCallee()->IgnoreParens();
5771 QualType T = Callee->getType();
5772
5773 if (T == Context.BoundMemberTy) {
5774 // Handle pointer-to-members.
5775 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5776 T = BinOp->getRHS()->getType();
5777 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5778 T = Mem->getMemberDecl()->getType();
5779 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005780
John McCall31168b02011-06-15 23:02:42 +00005781 if (const PointerType *Ptr = T->getAs<PointerType>())
5782 T = Ptr->getPointeeType();
5783 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
5784 T = Ptr->getPointeeType();
5785 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
5786 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00005787
John McCall31168b02011-06-15 23:02:42 +00005788 const FunctionType *FTy = T->getAs<FunctionType>();
5789 assert(FTy && "call to value not of function type?");
5790 ReturnsRetained = FTy->getExtInfo().getProducesResult();
5791
5792 // ActOnStmtExpr arranges things so that StmtExprs of retainable
5793 // type always produce a +1 object.
5794 } else if (isa<StmtExpr>(E)) {
5795 ReturnsRetained = true;
5796
Ted Kremeneke65b0862012-03-06 20:05:56 +00005797 // We hit this case with the lambda conversion-to-block optimization;
5798 // we don't want any extra casts here.
5799 } else if (isa<CastExpr>(E) &&
5800 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005801 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005802
John McCall31168b02011-06-15 23:02:42 +00005803 // For message sends and property references, we try to find an
5804 // actual method. FIXME: we should infer retention by selector in
5805 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00005806 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00005807 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005808 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
5809 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00005810 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
5811 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00005812 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
5813 D = ArrayLit->getArrayWithObjectsMethod();
5814 } else if (ObjCDictionaryLiteral *DictLit
5815 = dyn_cast<ObjCDictionaryLiteral>(E)) {
5816 D = DictLit->getDictWithObjectsMethod();
5817 }
John McCall31168b02011-06-15 23:02:42 +00005818
5819 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00005820
5821 // Don't do reclaims on performSelector calls; despite their
5822 // return type, the invoked method doesn't necessarily actually
5823 // return an object.
5824 if (!ReturnsRetained &&
5825 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005826 return E;
John McCall31168b02011-06-15 23:02:42 +00005827 }
5828
John McCall16de4d22011-11-14 19:53:16 +00005829 // Don't reclaim an object of Class type.
5830 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005831 return E;
John McCall16de4d22011-11-14 19:53:16 +00005832
Tim Shen4a05bb82016-06-21 20:29:17 +00005833 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00005834
John McCall2d637d22011-09-10 06:18:15 +00005835 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
5836 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005837 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
5838 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00005839 }
5840
David Blaikiebbafb8a2012-03-11 07:00:24 +00005841 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005842 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00005843
Peter Collingbournec331a1e2012-01-26 03:33:51 +00005844 // Search for the base element type (cf. ASTContext::getBaseElementType) with
5845 // a fast path for the common case that the type is directly a RecordType.
5846 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00005847 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00005848 while (!RT) {
5849 switch (T->getTypeClass()) {
5850 case Type::Record:
5851 RT = cast<RecordType>(T);
5852 break;
5853 case Type::ConstantArray:
5854 case Type::IncompleteArray:
5855 case Type::VariableArray:
5856 case Type::DependentSizedArray:
5857 T = cast<ArrayType>(T)->getElementType().getTypePtr();
5858 break;
5859 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005860 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00005861 }
5862 }
Mike Stump11289f42009-09-09 15:08:12 +00005863
Richard Smithfd555f62012-02-22 02:04:18 +00005864 // That should be enough to guarantee that this type is complete, if we're
5865 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00005866 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00005867 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005868 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00005869
5870 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00005871 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00005872
John McCall31168b02011-06-15 23:02:42 +00005873 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00005874 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00005875 CheckDestructorAccess(E->getExprLoc(), Destructor,
5876 PDiag(diag::err_access_dtor_temp)
5877 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00005878 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
5879 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00005880
Richard Smithfd555f62012-02-22 02:04:18 +00005881 // If destructor is trivial, we can avoid the extra copy.
5882 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005883 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00005884
John McCall28fc7092011-11-10 05:35:25 +00005885 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00005886 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00005887 }
Richard Smitheec915d62012-02-18 04:13:32 +00005888
5889 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00005890 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
5891
5892 if (IsDecltype)
5893 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
5894
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005895 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00005896}
5897
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005898ExprResult
John McCall5d413782010-12-06 08:20:24 +00005899Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005900 if (SubExpr.isInvalid())
5901 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005902
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005903 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005904}
5905
John McCall28fc7092011-11-10 05:35:25 +00005906Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00005907 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00005908
Eli Friedman3bda6b12012-02-02 23:15:15 +00005909 CleanupVarDeclMarking();
5910
John McCall28fc7092011-11-10 05:35:25 +00005911 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
5912 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00005913 assert(Cleanup.exprNeedsCleanups() ||
5914 ExprCleanupObjects.size() == FirstCleanup);
5915 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00005916 return SubExpr;
5917
Craig Topper5fc8fc22014-08-27 06:28:36 +00005918 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
5919 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00005920
Tim Shen4a05bb82016-06-21 20:29:17 +00005921 auto *E = ExprWithCleanups::Create(
5922 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00005923 DiscardCleanupsInEvaluationContext();
5924
5925 return E;
5926}
5927
John McCall5d413782010-12-06 08:20:24 +00005928Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00005929 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005930
Eli Friedman3bda6b12012-02-02 23:15:15 +00005931 CleanupVarDeclMarking();
5932
Tim Shen4a05bb82016-06-21 20:29:17 +00005933 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005934 return SubStmt;
5935
5936 // FIXME: In order to attach the temporaries, wrap the statement into
5937 // a StmtExpr; currently this is only used for asm statements.
5938 // This is hacky, either create a new CXXStmtWithTemporaries statement or
5939 // a new AsmStmtWithTemporaries.
Nico Webera2a0eb92012-12-29 20:03:39 +00005940 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005941 SourceLocation(),
5942 SourceLocation());
5943 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
5944 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00005945 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005946}
5947
Richard Smithfd555f62012-02-22 02:04:18 +00005948/// Process the expression contained within a decltype. For such expressions,
5949/// certain semantic checks on temporaries are delayed until this point, and
5950/// are omitted for the 'topmost' call in the decltype expression. If the
5951/// topmost call bound a temporary, strip that temporary off the expression.
5952ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005953 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00005954
5955 // C++11 [expr.call]p11:
5956 // If a function call is a prvalue of object type,
5957 // -- if the function call is either
5958 // -- the operand of a decltype-specifier, or
5959 // -- the right operand of a comma operator that is the operand of a
5960 // decltype-specifier,
5961 // a temporary object is not introduced for the prvalue.
5962
5963 // Recursively rebuild ParenExprs and comma expressions to strip out the
5964 // outermost CXXBindTemporaryExpr, if any.
5965 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5966 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
5967 if (SubExpr.isInvalid())
5968 return ExprError();
5969 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005970 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005971 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00005972 }
5973 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5974 if (BO->getOpcode() == BO_Comma) {
5975 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
5976 if (RHS.isInvalid())
5977 return ExprError();
5978 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005979 return E;
5980 return new (Context) BinaryOperator(
5981 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
5982 BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
Richard Smithfd555f62012-02-22 02:04:18 +00005983 }
5984 }
5985
5986 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00005987 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
5988 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00005989 if (TopCall)
5990 E = TopCall;
5991 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005992 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00005993
5994 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005995 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00005996
Richard Smithf86b0ae2012-07-28 19:54:11 +00005997 // In MS mode, don't perform any extra checking of call return types within a
5998 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00005999 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006000 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006001
Richard Smithfd555f62012-02-22 02:04:18 +00006002 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006003 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6004 I != N; ++I) {
6005 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006006 if (Call == TopCall)
6007 continue;
6008
David Majnemerced8bdf2015-02-25 17:36:15 +00006009 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006010 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006011 Call, Call->getDirectCallee()))
6012 return ExprError();
6013 }
6014
6015 // Now all relevant types are complete, check the destructors are accessible
6016 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006017 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6018 I != N; ++I) {
6019 CXXBindTemporaryExpr *Bind =
6020 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006021 if (Bind == TopBind)
6022 continue;
6023
6024 CXXTemporary *Temp = Bind->getTemporary();
6025
6026 CXXRecordDecl *RD =
6027 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6028 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6029 Temp->setDestructor(Destructor);
6030
Richard Smith7d847b12012-05-11 22:20:10 +00006031 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6032 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006033 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006034 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006035 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6036 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006037
6038 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006039 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006040 }
6041
6042 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006043 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006044}
6045
Richard Smith79c927b2013-11-06 19:31:51 +00006046/// Note a set of 'operator->' functions that were used for a member access.
6047static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006048 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006049 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6050 // FIXME: Make this configurable?
6051 unsigned Limit = 9;
6052 if (OperatorArrows.size() > Limit) {
6053 // Produce Limit-1 normal notes and one 'skipping' note.
6054 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6055 SkipCount = OperatorArrows.size() - (Limit - 1);
6056 }
6057
6058 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6059 if (I == SkipStart) {
6060 S.Diag(OperatorArrows[I]->getLocation(),
6061 diag::note_operator_arrows_suppressed)
6062 << SkipCount;
6063 I += SkipCount;
6064 } else {
6065 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6066 << OperatorArrows[I]->getCallResultType();
6067 ++I;
6068 }
6069 }
6070}
6071
Nico Weber964d3322015-02-16 22:35:45 +00006072ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6073 SourceLocation OpLoc,
6074 tok::TokenKind OpKind,
6075 ParsedType &ObjectType,
6076 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006077 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006078 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006079 if (Result.isInvalid()) return ExprError();
6080 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006081
John McCall526ab472011-10-25 17:37:35 +00006082 Result = CheckPlaceholderExpr(Base);
6083 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006084 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006085
John McCallb268a282010-08-23 23:25:46 +00006086 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006087 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006088 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006089 // If we have a pointer to a dependent type and are using the -> operator,
6090 // the object type is the type that the pointer points to. We might still
6091 // have enough information about that type to do something useful.
6092 if (OpKind == tok::arrow)
6093 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6094 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006095
John McCallba7bf592010-08-24 05:47:05 +00006096 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006097 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006098 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006099 }
Mike Stump11289f42009-09-09 15:08:12 +00006100
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006101 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006102 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006103 // returned, with the original second operand.
6104 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006105 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006106 bool NoArrowOperatorFound = false;
6107 bool FirstIteration = true;
6108 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006109 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006110 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006111 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006112 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006113
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006114 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006115 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6116 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006117 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006118 noteOperatorArrows(*this, OperatorArrows);
6119 Diag(OpLoc, diag::note_operator_arrow_depth)
6120 << getLangOpts().ArrowDepth;
6121 return ExprError();
6122 }
6123
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006124 Result = BuildOverloadedArrowExpr(
6125 S, Base, OpLoc,
6126 // When in a template specialization and on the first loop iteration,
6127 // potentially give the default diagnostic (with the fixit in a
6128 // separate note) instead of having the error reported back to here
6129 // and giving a diagnostic with a fixit attached to the error itself.
6130 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006131 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006132 : &NoArrowOperatorFound);
6133 if (Result.isInvalid()) {
6134 if (NoArrowOperatorFound) {
6135 if (FirstIteration) {
6136 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006137 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006138 << FixItHint::CreateReplacement(OpLoc, ".");
6139 OpKind = tok::period;
6140 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006141 }
6142 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6143 << BaseType << Base->getSourceRange();
6144 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006145 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006146 Diag(CD->getLocStart(),
6147 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006148 }
6149 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006150 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006151 }
John McCallb268a282010-08-23 23:25:46 +00006152 Base = Result.get();
6153 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006154 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006155 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006156 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006157 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006158 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6159 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006160 return ExprError();
6161 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006162 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006163 }
Mike Stump11289f42009-09-09 15:08:12 +00006164
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006165 if (OpKind == tok::arrow &&
6166 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006167 BaseType = BaseType->getPointeeType();
6168 }
Mike Stump11289f42009-09-09 15:08:12 +00006169
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006170 // Objective-C properties allow "." access on Objective-C pointer types,
6171 // so adjust the base type to the object type itself.
6172 if (BaseType->isObjCObjectPointerType())
6173 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006174
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006175 // C++ [basic.lookup.classref]p2:
6176 // [...] If the type of the object expression is of pointer to scalar
6177 // type, the unqualified-id is looked up in the context of the complete
6178 // postfix-expression.
6179 //
6180 // This also indicates that we could be parsing a pseudo-destructor-name.
6181 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006182 // expressions or normal member (ivar or property) access expressions, and
6183 // it's legal for the type to be incomplete if this is a pseudo-destructor
6184 // call. We'll do more incomplete-type checks later in the lookup process,
6185 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006186 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006187 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006188 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006189 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006190 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006191 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006192 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006193 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006194 }
Mike Stump11289f42009-09-09 15:08:12 +00006195
Douglas Gregor3024f072012-04-16 07:05:22 +00006196 // The object type must be complete (or dependent), or
6197 // C++11 [expr.prim.general]p3:
6198 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006199 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006200 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006201 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006202 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006203 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006204 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006205
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006206 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006207 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006208 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006209 // type C (or of pointer to a class type C), the unqualified-id is looked
6210 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006211 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006212 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006213}
6214
Simon Pilgrim75c26882016-09-30 14:25:09 +00006215static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006216 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006217 if (Base->hasPlaceholderType()) {
6218 ExprResult result = S.CheckPlaceholderExpr(Base);
6219 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006220 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006221 }
6222 ObjectType = Base->getType();
6223
David Blaikie1d578782011-12-16 16:03:09 +00006224 // C++ [expr.pseudo]p2:
6225 // The left-hand side of the dot operator shall be of scalar type. The
6226 // left-hand side of the arrow operator shall be of pointer to scalar type.
6227 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006228 // Note that this is rather different from the normal handling for the
6229 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006230 if (OpKind == tok::arrow) {
6231 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6232 ObjectType = Ptr->getPointeeType();
6233 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006234 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006235 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6236 << ObjectType << true
6237 << FixItHint::CreateReplacement(OpLoc, ".");
6238 if (S.isSFINAEContext())
6239 return true;
6240
6241 OpKind = tok::period;
6242 }
6243 }
6244
6245 return false;
6246}
6247
John McCalldadc5752010-08-24 06:29:42 +00006248ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006249 SourceLocation OpLoc,
6250 tok::TokenKind OpKind,
6251 const CXXScopeSpec &SS,
6252 TypeSourceInfo *ScopeTypeInfo,
6253 SourceLocation CCLoc,
6254 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006255 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006256 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006257
Eli Friedman0ce4de42012-01-25 04:35:06 +00006258 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006259 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6260 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006261
Douglas Gregorc5c57342012-09-10 14:57:06 +00006262 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6263 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006264 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006265 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006266 else {
Nico Weber58829272012-01-23 05:50:57 +00006267 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6268 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006269 return ExprError();
6270 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006271 }
6272
6273 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006274 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006275 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006276 if (DestructedTypeInfo) {
6277 QualType DestructedType = DestructedTypeInfo->getType();
6278 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006279 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006280 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6281 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6282 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6283 << ObjectType << DestructedType << Base->getSourceRange()
6284 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006285
John McCall31168b02011-06-15 23:02:42 +00006286 // Recover by setting the destructed type to the object type.
6287 DestructedType = ObjectType;
6288 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregor678f90d2010-02-25 01:56:36 +00006289 DestructedTypeStart);
John McCall31168b02011-06-15 23:02:42 +00006290 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
Simon Pilgrim75c26882016-09-30 14:25:09 +00006291 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006292 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006293
John McCall31168b02011-06-15 23:02:42 +00006294 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6295 // Okay: just pretend that the user provided the correctly-qualified
6296 // type.
6297 } else {
6298 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6299 << ObjectType << DestructedType << Base->getSourceRange()
6300 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6301 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006302
John McCall31168b02011-06-15 23:02:42 +00006303 // Recover by setting the destructed type to the object type.
6304 DestructedType = ObjectType;
6305 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6306 DestructedTypeStart);
6307 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6308 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006309 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006311
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006312 // C++ [expr.pseudo]p2:
6313 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6314 // form
6315 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006316 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006317 //
6318 // shall designate the same scalar type.
6319 if (ScopeTypeInfo) {
6320 QualType ScopeType = ScopeTypeInfo->getType();
6321 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006322 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006323
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006324 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006325 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006326 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006327 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006328
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006329 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006330 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006331 }
6332 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006333
John McCallb268a282010-08-23 23:25:46 +00006334 Expr *Result
6335 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6336 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006337 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006338 ScopeTypeInfo,
6339 CCLoc,
6340 TildeLoc,
6341 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006342
David Majnemerced8bdf2015-02-25 17:36:15 +00006343 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006344}
6345
John McCalldadc5752010-08-24 06:29:42 +00006346ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006347 SourceLocation OpLoc,
6348 tok::TokenKind OpKind,
6349 CXXScopeSpec &SS,
6350 UnqualifiedId &FirstTypeName,
6351 SourceLocation CCLoc,
6352 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006353 UnqualifiedId &SecondTypeName) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006354 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6355 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6356 "Invalid first type name in pseudo-destructor");
6357 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6358 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6359 "Invalid second type name in pseudo-destructor");
6360
Eli Friedman0ce4de42012-01-25 04:35:06 +00006361 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006362 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6363 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006364
6365 // Compute the object type that we should use for name lookup purposes. Only
6366 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006367 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006368 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006369 if (ObjectType->isRecordType())
6370 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006371 else if (ObjectType->isDependentType())
6372 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006373 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006374
6375 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006376 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006377 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006378 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006379 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006380 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006381 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006382 SecondTypeName.StartLocation,
Fariborz Jahanian87967422011-02-08 18:05:59 +00006383 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006384 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006385 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6386 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006387 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006388 // couldn't find anything useful in scope. Just store the identifier and
6389 // it's location, and we'll perform (qualified) name lookup again at
6390 // template instantiation time.
6391 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6392 SecondTypeName.StartLocation);
6393 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006394 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006395 diag::err_pseudo_dtor_destructor_non_type)
6396 << SecondTypeName.Identifier << ObjectType;
6397 if (isSFINAEContext())
6398 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006399
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006400 // Recover by assuming we had the right type all along.
6401 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006402 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006403 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006404 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006405 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006406 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006407 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006408 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006409 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006410 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006411 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006412 TemplateId->TemplateNameLoc,
6413 TemplateId->LAngleLoc,
6414 TemplateArgsPtr,
6415 TemplateId->RAngleLoc);
6416 if (T.isInvalid() || !T.get()) {
6417 // Recover by assuming we had the right type all along.
6418 DestructedType = ObjectType;
6419 } else
6420 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006421 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006422
6423 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006424 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006425 if (!DestructedType.isNull()) {
6426 if (!DestructedTypeInfo)
6427 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006428 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006429 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006431
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006432 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006433 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006434 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006435 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006436 FirstTypeName.Identifier) {
6437 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006438 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006439 FirstTypeName.StartLocation,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006440 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006441 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006442 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006443 diag::err_pseudo_dtor_destructor_non_type)
6444 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006445
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006446 if (isSFINAEContext())
6447 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006448
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006449 // Just drop this type. It's unnecessary anyway.
6450 ScopeType = QualType();
6451 } else
6452 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006453 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006454 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006455 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006456 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006457 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006458 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006459 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006460 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006461 TemplateId->TemplateNameLoc,
6462 TemplateId->LAngleLoc,
6463 TemplateArgsPtr,
6464 TemplateId->RAngleLoc);
6465 if (T.isInvalid() || !T.get()) {
6466 // Recover by dropping this type.
6467 ScopeType = QualType();
6468 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006469 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006470 }
6471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006472
Douglas Gregor90ad9222010-02-24 23:02:30 +00006473 if (!ScopeType.isNull() && !ScopeTypeInfo)
6474 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6475 FirstTypeName.StartLocation);
6476
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006477
John McCallb268a282010-08-23 23:25:46 +00006478 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00006479 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006480 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00006481}
6482
David Blaikie1d578782011-12-16 16:03:09 +00006483ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6484 SourceLocation OpLoc,
6485 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006486 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006487 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00006488 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006489 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6490 return ExprError();
6491
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006492 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6493 false);
David Blaikie1d578782011-12-16 16:03:09 +00006494
6495 TypeLocBuilder TLB;
6496 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6497 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6498 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6499 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6500
6501 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006502 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006503 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00006504}
6505
John Wiegley01296292011-04-08 18:41:53 +00006506ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00006507 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006508 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00006509 if (Method->getParent()->isLambda() &&
6510 Method->getConversionType()->isBlockPointerType()) {
6511 // This is a lambda coversion to block pointer; check if the argument
6512 // is a LambdaExpr.
6513 Expr *SubE = E;
6514 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6515 if (CE && CE->getCastKind() == CK_NoOp)
6516 SubE = CE->getSubExpr();
6517 SubE = SubE->IgnoreParens();
6518 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6519 SubE = BE->getSubExpr();
6520 if (isa<LambdaExpr>(SubE)) {
6521 // For the conversion to block pointer on a lambda expression, we
6522 // construct a special BlockLiteral instead; this doesn't really make
6523 // a difference in ARC, but outside of ARC the resulting block literal
6524 // follows the normal lifetime rules for block literals instead of being
6525 // autoreleased.
6526 DiagnosticErrorTrap Trap(Diags);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006527 PushExpressionEvaluationContext(PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00006528 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6529 E->getExprLoc(),
6530 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006531 PopExpressionEvaluationContext();
6532
Eli Friedman98b01ed2012-03-01 04:01:32 +00006533 if (Exp.isInvalid())
6534 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6535 return Exp;
6536 }
6537 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00006538
Craig Topperc3ec1492014-05-26 06:22:03 +00006539 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006540 FoundDecl, Method);
6541 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00006542 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00006543
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00006544 MemberExpr *ME = new (Context) MemberExpr(
6545 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6546 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006547 if (HadMultipleCandidates)
6548 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00006549 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006550
Alp Toker314cc812014-01-25 16:55:45 +00006551 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00006552 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6553 ResultType = ResultType.getNonLValueExprType(Context);
6554
Douglas Gregor27381f32009-11-23 12:27:39 +00006555 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006556 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00006557 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006558 return CE;
6559}
6560
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006561ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6562 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00006563 // If the operand is an unresolved lookup expression, the expression is ill-
6564 // formed per [over.over]p1, because overloaded function names cannot be used
6565 // without arguments except in explicit contexts.
6566 ExprResult R = CheckPlaceholderExpr(Operand);
6567 if (R.isInvalid())
6568 return R;
6569
6570 // The operand may have been modified when checking the placeholder type.
6571 Operand = R.get();
6572
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006573 if (ActiveTemplateInstantiations.empty() &&
6574 Operand->HasSideEffects(Context, false)) {
6575 // The expression operand for noexcept is in an unevaluated expression
6576 // context, so side effects could result in unintended consequences.
6577 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6578 }
6579
Richard Smithf623c962012-04-17 00:58:00 +00006580 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006581 return new (Context)
6582 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006583}
6584
6585ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6586 Expr *Operand, SourceLocation RParen) {
6587 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00006588}
6589
Eli Friedmanf798f652012-05-24 22:04:19 +00006590static bool IsSpecialDiscardedValue(Expr *E) {
6591 // In C++11, discarded-value expressions of a certain form are special,
6592 // according to [expr]p10:
6593 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6594 // expression is an lvalue of volatile-qualified type and it has
6595 // one of the following forms:
6596 E = E->IgnoreParens();
6597
Eli Friedmanc49c2262012-05-24 22:36:31 +00006598 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006599 if (isa<DeclRefExpr>(E))
6600 return true;
6601
Eli Friedmanc49c2262012-05-24 22:36:31 +00006602 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006603 if (isa<ArraySubscriptExpr>(E))
6604 return true;
6605
Eli Friedmanc49c2262012-05-24 22:36:31 +00006606 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006607 if (isa<MemberExpr>(E))
6608 return true;
6609
Eli Friedmanc49c2262012-05-24 22:36:31 +00006610 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006611 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6612 if (UO->getOpcode() == UO_Deref)
6613 return true;
6614
6615 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00006616 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006617 if (BO->isPtrMemOp())
6618 return true;
6619
Eli Friedmanc49c2262012-05-24 22:36:31 +00006620 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00006621 if (BO->getOpcode() == BO_Comma)
6622 return IsSpecialDiscardedValue(BO->getRHS());
6623 }
6624
Eli Friedmanc49c2262012-05-24 22:36:31 +00006625 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00006626 // operands are one of the above, or
6627 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6628 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6629 IsSpecialDiscardedValue(CO->getFalseExpr());
6630 // The related edge case of "*x ?: *x".
6631 if (BinaryConditionalOperator *BCO =
6632 dyn_cast<BinaryConditionalOperator>(E)) {
6633 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6634 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6635 IsSpecialDiscardedValue(BCO->getFalseExpr());
6636 }
6637
6638 // Objective-C++ extensions to the rule.
6639 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6640 return true;
6641
6642 return false;
6643}
6644
John McCall34376a62010-12-04 03:47:34 +00006645/// Perform the conversions required for an expression used in a
6646/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00006647ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00006648 if (E->hasPlaceholderType()) {
6649 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006650 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006651 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00006652 }
6653
John McCallfee942d2010-12-02 02:07:15 +00006654 // C99 6.3.2.1:
6655 // [Except in specific positions,] an lvalue that does not have
6656 // array type is converted to the value stored in the
6657 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00006658 if (E->isRValue()) {
6659 // In C, function designators (i.e. expressions of function type)
6660 // are r-values, but we still want to do function-to-pointer decay
6661 // on them. This is both technically correct and convenient for
6662 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006663 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00006664 return DefaultFunctionArrayConversion(E);
6665
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006666 return E;
John McCalld68b2d02011-06-27 21:24:11 +00006667 }
John McCallfee942d2010-12-02 02:07:15 +00006668
Eli Friedmanf798f652012-05-24 22:04:19 +00006669 if (getLangOpts().CPlusPlus) {
6670 // The C++11 standard defines the notion of a discarded-value expression;
6671 // normally, we don't need to do anything to handle it, but if it is a
6672 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6673 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006674 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00006675 E->getType().isVolatileQualified() &&
6676 IsSpecialDiscardedValue(E)) {
6677 ExprResult Res = DefaultLvalueConversion(E);
6678 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006679 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006680 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006681 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006682 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00006683 }
John McCall34376a62010-12-04 03:47:34 +00006684
6685 // GCC seems to also exclude expressions of incomplete enum type.
6686 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6687 if (!T->getDecl()->isComplete()) {
6688 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006689 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006690 return E;
John McCall34376a62010-12-04 03:47:34 +00006691 }
6692 }
6693
John Wiegley01296292011-04-08 18:41:53 +00006694 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6695 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006696 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006697 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00006698
John McCallca61b652010-12-04 12:29:11 +00006699 if (!E->getType()->isVoidType())
6700 RequireCompleteType(E->getExprLoc(), E->getType(),
6701 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006702 return E;
John McCall34376a62010-12-04 03:47:34 +00006703}
6704
Faisal Valia17d19f2013-11-07 05:17:06 +00006705// If we can unambiguously determine whether Var can never be used
6706// in a constant expression, return true.
6707// - if the variable and its initializer are non-dependent, then
6708// we can unambiguously check if the variable is a constant expression.
6709// - if the initializer is not value dependent - we can determine whether
6710// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00006711// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00006712// never be a constant expression.
6713// - FXIME: if the initializer is dependent, we can still do some analysis and
6714// identify certain cases unambiguously as non-const by using a Visitor:
6715// - such as those that involve odr-use of a ParmVarDecl, involve a new
6716// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00006717static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00006718 ASTContext &Context) {
6719 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006720 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006721
6722 // If there is no initializer - this can not be a constant expression.
6723 if (!Var->getAnyInitializer(DefVD)) return true;
6724 assert(DefVD);
6725 if (DefVD->isWeak()) return false;
6726 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00006727
Faisal Valia17d19f2013-11-07 05:17:06 +00006728 Expr *Init = cast<Expr>(Eval->Value);
6729
6730 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00006731 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
6732 // of value-dependent expressions, and use it here to determine whether the
6733 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00006734 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00006735 }
6736
Simon Pilgrim75c26882016-09-30 14:25:09 +00006737 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00006738}
6739
Simon Pilgrim75c26882016-09-30 14:25:09 +00006740/// \brief Check if the current lambda has any potential captures
6741/// that must be captured by any of its enclosing lambdas that are ready to
6742/// capture. If there is a lambda that can capture a nested
6743/// potential-capture, go ahead and do so. Also, check to see if any
6744/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00006745/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00006746
Faisal Valiab3d6462013-12-07 20:22:44 +00006747static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
6748 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
6749
Simon Pilgrim75c26882016-09-30 14:25:09 +00006750 assert(!S.isUnevaluatedContext());
6751 assert(S.CurContext->isDependentContext());
6752 assert(CurrentLSI->CallOperator == S.CurContext &&
Faisal Valiab3d6462013-12-07 20:22:44 +00006753 "The current call operator must be synchronized with Sema's CurContext");
6754
6755 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
6756
6757 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
6758 S.FunctionScopes.data(), S.FunctionScopes.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00006759
Faisal Valiab3d6462013-12-07 20:22:44 +00006760 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00006761 // lambda (within a generic outer lambda), must be captured by an
6762 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00006763 const unsigned NumPotentialCaptures =
6764 CurrentLSI->getNumPotentialVariableCaptures();
6765 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006766 Expr *VarExpr = nullptr;
6767 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006768 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00006769 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00006770 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00006771 // need to check enclosing lambda's for speculative captures.
6772 // For e.g.:
6773 // Even though 'x' is not odr-used, it should be captured.
6774 // int test() {
6775 // const int x = 10;
6776 // auto L = [=](auto a) {
6777 // (void) +x + a;
6778 // };
6779 // }
6780 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00006781 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00006782 continue;
6783
6784 // If we have a capture-capable lambda for the variable, go ahead and
6785 // capture the variable in that lambda (and all its enclosing lambdas).
6786 if (const Optional<unsigned> Index =
6787 getStackIndexOfNearestEnclosingCaptureCapableLambda(
6788 FunctionScopesArrayRef, Var, S)) {
6789 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6790 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
6791 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00006792 }
6793 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00006794 VariableCanNeverBeAConstantExpression(Var, S.Context);
6795 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
6796 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00006797 // can not be used in a constant expression - which means
6798 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00006799 // capture violation early, if the variable is un-captureable.
6800 // This is purely for diagnosing errors early. Otherwise, this
6801 // error would get diagnosed when the lambda becomes capture ready.
6802 QualType CaptureType, DeclRefType;
6803 SourceLocation ExprLoc = VarExpr->getExprLoc();
6804 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006805 /*EllipsisLoc*/ SourceLocation(),
6806 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00006807 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00006808 // We will never be able to capture this variable, and we need
6809 // to be able to in any and all instantiations, so diagnose it.
6810 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006811 /*EllipsisLoc*/ SourceLocation(),
6812 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00006813 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00006814 }
6815 }
6816 }
6817
Faisal Valiab3d6462013-12-07 20:22:44 +00006818 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00006819 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00006820 // If we have a capture-capable lambda for 'this', go ahead and capture
6821 // 'this' in that lambda (and all its enclosing lambdas).
6822 if (const Optional<unsigned> Index =
6823 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Craig Topperc3ec1492014-05-26 06:22:03 +00006824 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00006825 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6826 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
6827 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
6828 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00006829 }
6830 }
Faisal Valiab3d6462013-12-07 20:22:44 +00006831
6832 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00006833 CurrentLSI->clearPotentialCaptures();
6834}
6835
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006836static ExprResult attemptRecovery(Sema &SemaRef,
6837 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00006838 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006839 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
6840 Consumer.getLookupResult().getLookupKind());
6841 const CXXScopeSpec *SS = Consumer.getSS();
6842 CXXScopeSpec NewSS;
6843
6844 // Use an approprate CXXScopeSpec for building the expr.
6845 if (auto *NNS = TC.getCorrectionSpecifier())
6846 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
6847 else if (SS && !TC.WillReplaceSpecifier())
6848 NewSS = *SS;
6849
Richard Smithde6d6c42015-12-29 19:43:10 +00006850 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00006851 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006852 R.addDecl(ND);
6853 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00006854 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006855 CXXRecordDecl *Record = nullptr;
6856 if (auto *NNS = TC.getCorrectionSpecifier())
6857 Record = NNS->getAsType()->getAsCXXRecordDecl();
6858 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00006859 Record =
6860 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
6861 if (Record)
6862 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006863
6864 // Detect and handle the case where the decl might be an implicit
6865 // member.
6866 bool MightBeImplicitMember;
6867 if (!Consumer.isAddressOfOperand())
6868 MightBeImplicitMember = true;
6869 else if (!NewSS.isEmpty())
6870 MightBeImplicitMember = false;
6871 else if (R.isOverloadedResult())
6872 MightBeImplicitMember = false;
6873 else if (R.isUnresolvableResult())
6874 MightBeImplicitMember = true;
6875 else
6876 MightBeImplicitMember = isa<FieldDecl>(ND) ||
6877 isa<IndirectFieldDecl>(ND) ||
6878 isa<MSPropertyDecl>(ND);
6879
6880 if (MightBeImplicitMember)
6881 return SemaRef.BuildPossibleImplicitMemberExpr(
6882 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00006883 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006884 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
6885 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
6886 Ivar->getIdentifier());
6887 }
6888 }
6889
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00006890 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
6891 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006892}
6893
Kaelyn Takata6c759512014-10-27 18:07:37 +00006894namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00006895class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
6896 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
6897
6898public:
6899 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
6900 : TypoExprs(TypoExprs) {}
6901 bool VisitTypoExpr(TypoExpr *TE) {
6902 TypoExprs.insert(TE);
6903 return true;
6904 }
6905};
6906
Kaelyn Takata6c759512014-10-27 18:07:37 +00006907class TransformTypos : public TreeTransform<TransformTypos> {
6908 typedef TreeTransform<TransformTypos> BaseTransform;
6909
Kaelyn Takatab8499f02015-05-05 19:17:03 +00006910 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
6911 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00006912 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006913 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00006914 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006915 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00006916
6917 /// \brief Emit diagnostics for all of the TypoExprs encountered.
6918 /// If the TypoExprs were successfully corrected, then the diagnostics should
6919 /// suggest the corrections. Otherwise the diagnostics will not suggest
6920 /// anything (having been passed an empty TypoCorrection).
6921 void EmitAllDiagnostics() {
6922 for (auto E : TypoExprs) {
6923 TypoExpr *TE = cast<TypoExpr>(E);
6924 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006925 if (State.DiagHandler) {
6926 TypoCorrection TC = State.Consumer->getCurrentCorrection();
6927 ExprResult Replacement = TransformCache[TE];
6928
6929 // Extract the NamedDecl from the transformed TypoExpr and add it to the
6930 // TypoCorrection, replacing the existing decls. This ensures the right
6931 // NamedDecl is used in diagnostics e.g. in the case where overload
6932 // resolution was used to select one from several possible decls that
6933 // had been stored in the TypoCorrection.
6934 if (auto *ND = getDeclFromExpr(
6935 Replacement.isInvalid() ? nullptr : Replacement.get()))
6936 TC.setCorrectionDecl(ND);
6937
6938 State.DiagHandler(TC);
6939 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00006940 SemaRef.clearDelayedTypo(TE);
6941 }
6942 }
6943
6944 /// \brief If corrections for the first TypoExpr have been exhausted for a
6945 /// given combination of the other TypoExprs, retry those corrections against
6946 /// the next combination of substitutions for the other TypoExprs by advancing
6947 /// to the next potential correction of the second TypoExpr. For the second
6948 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
6949 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
6950 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
6951 /// TransformCache). Returns true if there is still any untried combinations
6952 /// of corrections.
6953 bool CheckAndAdvanceTypoExprCorrectionStreams() {
6954 for (auto TE : TypoExprs) {
6955 auto &State = SemaRef.getTypoExprState(TE);
6956 TransformCache.erase(TE);
6957 if (!State.Consumer->finished())
6958 return true;
6959 State.Consumer->resetCorrectionStream();
6960 }
6961 return false;
6962 }
6963
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006964 NamedDecl *getDeclFromExpr(Expr *E) {
6965 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
6966 E = OverloadResolution[OE];
6967
6968 if (!E)
6969 return nullptr;
6970 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00006971 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006972 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00006973 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006974 // FIXME: Add any other expr types that could be be seen by the delayed typo
6975 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00006976 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006977 return nullptr;
6978 }
6979
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006980 ExprResult TryTransform(Expr *E) {
6981 Sema::SFINAETrap Trap(SemaRef);
6982 ExprResult Res = TransformExpr(E);
6983 if (Trap.hasErrorOccurred() || Res.isInvalid())
6984 return ExprError();
6985
6986 return ExprFilter(Res.get());
6987 }
6988
Kaelyn Takata6c759512014-10-27 18:07:37 +00006989public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00006990 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
6991 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00006992
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006993 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
6994 MultiExprArg Args,
6995 SourceLocation RParenLoc,
6996 Expr *ExecConfig = nullptr) {
6997 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
6998 RParenLoc, ExecConfig);
6999 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007000 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007001 Expr *ResultCall = Result.get();
7002 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7003 ResultCall = BE->getSubExpr();
7004 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7005 OverloadResolution[OE] = CE->getCallee();
7006 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007007 }
7008 return Result;
7009 }
7010
Kaelyn Takata6c759512014-10-27 18:07:37 +00007011 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7012
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007013 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7014
Saleem Abdulrasool407f36b2016-02-07 02:30:55 +00007015 ExprResult TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
7016 return Owned(E);
7017 }
7018
Saleem Abdulrasool02e19a12016-02-07 02:30:59 +00007019 ExprResult TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
7020 return Owned(E);
7021 }
7022
Kaelyn Takata6c759512014-10-27 18:07:37 +00007023 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007024 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007025 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007026 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007027
Kaelyn Takata6c759512014-10-27 18:07:37 +00007028 // Exit if either the transform was valid or if there were no TypoExprs
7029 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007030 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007031 !CheckAndAdvanceTypoExprCorrectionStreams())
7032 break;
7033 }
7034
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007035 // Ensure none of the TypoExprs have multiple typo correction candidates
7036 // with the same edit length that pass all the checks and filters.
7037 // TODO: Properly handle various permutations of possible corrections when
7038 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007039 // Also, disable typo correction while attempting the transform when
7040 // handling potentially ambiguous typo corrections as any new TypoExprs will
7041 // have been introduced by the application of one of the correction
7042 // candidates and add little to no value if corrected.
7043 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007044 while (!AmbiguousTypoExprs.empty()) {
7045 auto TE = AmbiguousTypoExprs.back();
7046 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007047 auto &State = SemaRef.getTypoExprState(TE);
7048 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007049 TransformCache.erase(TE);
7050 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007051 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007052 TransformCache.erase(TE);
7053 Res = ExprError();
7054 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007055 }
7056 AmbiguousTypoExprs.remove(TE);
7057 State.Consumer->restoreSavedPosition();
7058 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007059 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007060 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007061
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007062 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007063 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007064 FindTypoExprs(TypoExprs).TraverseStmt(E);
7065
Kaelyn Takata6c759512014-10-27 18:07:37 +00007066 EmitAllDiagnostics();
7067
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007068 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007069 }
7070
7071 ExprResult TransformTypoExpr(TypoExpr *E) {
7072 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7073 // cached transformation result if there is one and the TypoExpr isn't the
7074 // first one that was encountered.
7075 auto &CacheEntry = TransformCache[E];
7076 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7077 return CacheEntry;
7078 }
7079
7080 auto &State = SemaRef.getTypoExprState(E);
7081 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7082
7083 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7084 // typo correction and return it.
7085 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007086 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007087 continue;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007088 ExprResult NE = State.RecoveryHandler ?
7089 State.RecoveryHandler(SemaRef, E, TC) :
7090 attemptRecovery(SemaRef, *State.Consumer, TC);
7091 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007092 // Check whether there may be a second viable correction with the same
7093 // edit distance; if so, remember this TypoExpr may have an ambiguous
7094 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007095 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007096 if ((Next = State.Consumer->peekNextCorrection()) &&
7097 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7098 AmbiguousTypoExprs.insert(E);
7099 } else {
7100 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007101 }
7102 assert(!NE.isUnset() &&
7103 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007104 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007105 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007106 }
7107 return CacheEntry = ExprError();
7108 }
7109};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007110}
Faisal Valia17d19f2013-11-07 05:17:06 +00007111
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007112ExprResult
7113Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7114 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007115 // If the current evaluation context indicates there are uncorrected typos
7116 // and the current expression isn't guaranteed to not have typos, try to
7117 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007118 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007119 (E->isTypeDependent() || E->isValueDependent() ||
7120 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007121 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7122 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7123 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007124 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007125 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007126 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007127 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007128 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007129 ExprEvalContexts.back().NumTypos -= TyposResolved;
7130 return Result;
7131 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007132 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007133 }
7134 return E;
7135}
7136
Richard Smith945f8d32013-01-14 22:39:08 +00007137ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007138 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007139 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007140 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007141 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007142
7143 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007144 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007145
7146 // If we are an init-expression in a lambdas init-capture, we should not
7147 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007148 // containing full-expression is done).
7149 // template<class ... Ts> void test(Ts ... t) {
7150 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7151 // return a;
7152 // }() ...);
7153 // }
7154 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7155 // when we parse the lambda introducer, and teach capturing (but not
7156 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7157 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7158 // lambda where we've entered the introducer but not the body, or represent a
7159 // lambda where we've entered the body, depending on where the
7160 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007161 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007162 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007163 return ExprError();
7164
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007165 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007166 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007167 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007168 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007169 if (FullExpr.isInvalid())
7170 return ExprError();
7171 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007172
Richard Smith945f8d32013-01-14 22:39:08 +00007173 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007174 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007175 if (FullExpr.isInvalid())
7176 return ExprError();
7177
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007178 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007179 if (FullExpr.isInvalid())
7180 return ExprError();
7181 }
John Wiegley01296292011-04-08 18:41:53 +00007182
Kaelyn Takata49d84322014-11-11 23:26:56 +00007183 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7184 if (FullExpr.isInvalid())
7185 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007186
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007187 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007188
Simon Pilgrim75c26882016-09-30 14:25:09 +00007189 // At the end of this full expression (which could be a deeply nested
7190 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007191 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007192 // Consider the following code:
7193 // void f(int, int);
7194 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007195 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007196 // const int x = 10, y = 20;
7197 // auto L = [=](auto a) {
7198 // auto M = [=](auto b) {
7199 // f(x, b); <-- requires x to be captured by L and M
7200 // f(y, a); <-- requires y to be captured by L, but not all Ms
7201 // };
7202 // };
7203 // }
7204
Simon Pilgrim75c26882016-09-30 14:25:09 +00007205 // FIXME: Also consider what happens for something like this that involves
7206 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007207 // void f() {
7208 // const int n = 0;
7209 // auto L = [&](auto a) {
7210 // +n + ({ 0; a; });
7211 // };
7212 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007213 //
7214 // Here, we see +n, and then the full-expression 0; ends, so we don't
7215 // capture n (and instead remove it from our list of potential captures),
7216 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007217 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007218
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007219 LambdaScopeInfo *const CurrentLSI = getCurLambda();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007220 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007221 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007222 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007223 // By ensuring we are in the context of a lambda's call operator
7224 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007225 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007226 // PR, a proper fix would entail :
7227 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007228 // - Add to Sema an integer holding the smallest (outermost) scope
7229 // index that we are *lexically* within, and save/restore/set to
7230 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007231 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007232 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007233 // stop at the outermost enclosing lexical scope."
7234 const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
7235 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007236 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007237 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7238 *this);
John McCall5d413782010-12-06 08:20:24 +00007239 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007240}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007241
7242StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7243 if (!FullStmt) return StmtError();
7244
John McCall5d413782010-12-06 08:20:24 +00007245 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007246}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007247
Simon Pilgrim75c26882016-09-30 14:25:09 +00007248Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007249Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7250 CXXScopeSpec &SS,
7251 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007252 DeclarationName TargetName = TargetNameInfo.getName();
7253 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007254 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007255
Douglas Gregor43edb322011-10-24 22:31:10 +00007256 // If the name itself is dependent, then the result is dependent.
7257 if (TargetName.isDependentName())
7258 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007259
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007260 // Do the redeclaration lookup in the current scope.
7261 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7262 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007263 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007264 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007265
Douglas Gregor43edb322011-10-24 22:31:10 +00007266 switch (R.getResultKind()) {
7267 case LookupResult::Found:
7268 case LookupResult::FoundOverloaded:
7269 case LookupResult::FoundUnresolvedValue:
7270 case LookupResult::Ambiguous:
7271 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007272
Douglas Gregor43edb322011-10-24 22:31:10 +00007273 case LookupResult::NotFound:
7274 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007275
Douglas Gregor43edb322011-10-24 22:31:10 +00007276 case LookupResult::NotFoundInCurrentInstantiation:
7277 return IER_Dependent;
7278 }
David Blaikie8a40f702012-01-17 06:56:22 +00007279
7280 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007281}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007282
Simon Pilgrim75c26882016-09-30 14:25:09 +00007283Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007284Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7285 bool IsIfExists, CXXScopeSpec &SS,
7286 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007287 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007288
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007289 // Check for unexpanded parameter packs.
7290 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
7291 collectUnexpandedParameterPacks(SS, Unexpanded);
7292 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
7293 if (!Unexpanded.empty()) {
7294 DiagnoseUnexpandedParameterPacks(KeywordLoc,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007295 IsIfExists? UPPC_IfExists
7296 : UPPC_IfNotExists,
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007297 Unexpanded);
7298 return IER_Error;
7299 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007300
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007301 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7302}