blob: a87e3db590e3a8747c9e8200cee050bcc0aeaf30 [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)
688 CheckCUDAExceptionExpr(OpLoc, "throw");
689
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000690 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
691 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
692
John Wiegley01296292011-04-08 18:41:53 +0000693 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000694 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
695 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000696 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000697
698 // Initialize the exception result. This implicitly weeds out
699 // abstract types or types with inaccessible copy constructors.
700
701 // C++0x [class.copymove]p31:
702 // When certain criteria are met, an implementation is allowed to omit the
703 // copy/move construction of a class object [...]
704 //
705 // - in a throw-expression, when the operand is the name of a
706 // non-volatile automatic object (other than a function or
707 // catch-clause
708 // parameter) whose scope does not extend beyond the end of the
709 // innermost enclosing try-block (if there is one), the copy/move
710 // operation from the operand to the exception object (15.1) can be
711 // omitted by constructing the automatic object directly into the
712 // exception object
713 const VarDecl *NRVOVariable = nullptr;
714 if (IsThrownVarInScope)
715 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
716
717 InitializedEntity Entity = InitializedEntity::InitializeException(
718 OpLoc, ExceptionObjectTy,
719 /*NRVO=*/NRVOVariable != nullptr);
720 ExprResult Res = PerformMoveOrCopyInitialization(
721 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
722 if (Res.isInvalid())
723 return ExprError();
724 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000725 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000726
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000727 return new (Context)
728 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000729}
730
David Majnemere7a818f2015-03-06 18:53:55 +0000731static void
732collectPublicBases(CXXRecordDecl *RD,
733 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
734 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
735 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
736 bool ParentIsPublic) {
737 for (const CXXBaseSpecifier &BS : RD->bases()) {
738 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
739 bool NewSubobject;
740 // Virtual bases constitute the same subobject. Non-virtual bases are
741 // always distinct subobjects.
742 if (BS.isVirtual())
743 NewSubobject = VBases.insert(BaseDecl).second;
744 else
745 NewSubobject = true;
746
747 if (NewSubobject)
748 ++SubobjectsSeen[BaseDecl];
749
750 // Only add subobjects which have public access throughout the entire chain.
751 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
752 if (PublicPath)
753 PublicSubobjectsSeen.insert(BaseDecl);
754
755 // Recurse on to each base subobject.
756 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
757 PublicPath);
758 }
759}
760
761static void getUnambiguousPublicSubobjects(
762 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
763 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
764 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
765 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
766 SubobjectsSeen[RD] = 1;
767 PublicSubobjectsSeen.insert(RD);
768 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
769 /*ParentIsPublic=*/true);
770
771 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
772 // Skip ambiguous objects.
773 if (SubobjectsSeen[PublicSubobject] > 1)
774 continue;
775
776 Objects.push_back(PublicSubobject);
777 }
778}
779
Sebastian Redl4de47b42009-04-27 20:27:31 +0000780/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000781bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
782 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000783 // If the type of the exception would be an incomplete type or a pointer
784 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000785 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000786 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000787 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000788 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000789 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000790 }
791 if (!isPointer || !Ty->isVoidType()) {
792 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000793 isPointer ? diag::err_throw_incomplete_ptr
794 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000795 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000796 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000797
David Majnemerd09a51c2015-03-03 01:50:05 +0000798 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000799 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000800 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000801 }
802
Eli Friedman91a3d272010-06-03 20:39:03 +0000803 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000804 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
805 if (!RD)
806 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000807
Douglas Gregor88d292c2010-05-13 16:44:06 +0000808 // If we are throwing a polymorphic class type or pointer thereof,
809 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000810 MarkVTableUsed(ThrowLoc, RD);
811
Eli Friedman36ebbec2010-10-12 20:32:36 +0000812 // If a pointer is thrown, the referenced object will not be destroyed.
813 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000814 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000815
Richard Smitheec915d62012-02-18 04:13:32 +0000816 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000817 if (!RD->hasIrrelevantDestructor()) {
818 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
819 MarkFunctionReferenced(E->getExprLoc(), Destructor);
820 CheckDestructorAccess(E->getExprLoc(), Destructor,
821 PDiag(diag::err_access_dtor_exception) << Ty);
822 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000823 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000824 }
825 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000826
David Majnemerdfa6d202015-03-11 18:36:39 +0000827 // The MSVC ABI creates a list of all types which can catch the exception
828 // object. This list also references the appropriate copy constructor to call
829 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000830 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000831 // We are only interested in the public, unambiguous bases contained within
832 // the exception object. Bases which are ambiguous or otherwise
833 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000834 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
835 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000836
David Majnemere7a818f2015-03-06 18:53:55 +0000837 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000838 // Attempt to lookup the copy constructor. Various pieces of machinery
839 // will spring into action, like template instantiation, which means this
840 // cannot be a simple walk of the class's decls. Instead, we must perform
841 // lookup and overload resolution.
842 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
843 if (!CD)
844 continue;
845
846 // Mark the constructor referenced as it is used by this throw expression.
847 MarkFunctionReferenced(E->getExprLoc(), CD);
848
849 // Skip this copy constructor if it is trivial, we don't need to record it
850 // in the catchable type data.
851 if (CD->isTrivial())
852 continue;
853
854 // The copy constructor is non-trivial, create a mapping from this class
855 // type to this constructor.
856 // N.B. The selection of copy constructor is not sensitive to this
857 // particular throw-site. Lookup will be performed at the catch-site to
858 // ensure that the copy constructor is, in fact, accessible (via
859 // friendship or any other means).
860 Context.addCopyConstructorForExceptionObject(Subobject, CD);
861
862 // We don't keep the instantiated default argument expressions around so
863 // we must rebuild them here.
864 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
865 // Skip any default arguments that we've already instantiated.
866 if (Context.getDefaultArgExprForConstructor(CD, I))
867 continue;
868
869 Expr *DefaultArg =
870 BuildCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)).get();
871 Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
David Majnemere7a818f2015-03-06 18:53:55 +0000872 }
873 }
874 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000875
David Majnemerba3e5ec2015-03-13 18:26:17 +0000876 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000877}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000878
Faisal Vali67b04462016-06-11 16:41:54 +0000879static QualType adjustCVQualifiersForCXXThisWithinLambda(
880 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
881 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
882
883 QualType ClassType = ThisTy->getPointeeType();
884 LambdaScopeInfo *CurLSI = nullptr;
885 DeclContext *CurDC = CurSemaContext;
886
887 // Iterate through the stack of lambdas starting from the innermost lambda to
888 // the outermost lambda, checking if '*this' is ever captured by copy - since
889 // that could change the cv-qualifiers of the '*this' object.
890 // The object referred to by '*this' starts out with the cv-qualifiers of its
891 // member function. We then start with the innermost lambda and iterate
892 // outward checking to see if any lambda performs a by-copy capture of '*this'
893 // - and if so, any nested lambda must respect the 'constness' of that
894 // capturing lamdbda's call operator.
895 //
896
897 // The issue is that we cannot rely entirely on the FunctionScopeInfo stack
898 // since ScopeInfos are pushed on during parsing and treetransforming. But
899 // since a generic lambda's call operator can be instantiated anywhere (even
900 // end of the TU) we need to be able to examine its enclosing lambdas and so
901 // we use the DeclContext to get a hold of the closure-class and query it for
902 // capture information. The reason we don't just resort to always using the
903 // DeclContext chain is that it is only mature for lambda expressions
904 // enclosing generic lambda's call operators that are being instantiated.
905
906 for (int I = FunctionScopes.size();
907 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]);
908 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
909 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000910
911 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +0000912 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000913
Faisal Vali67b04462016-06-11 16:41:54 +0000914 auto C = CurLSI->getCXXThisCapture();
915
916 if (C.isCopyCapture()) {
917 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
918 if (CurLSI->CallOperator->isConst())
919 ClassType.addConst();
920 return ASTCtx.getPointerType(ClassType);
921 }
922 }
923 // We've run out of ScopeInfos but check if CurDC is a lambda (which can
924 // happen during instantiation of generic lambdas)
925 if (isLambdaCallOperator(CurDC)) {
926 assert(CurLSI);
927 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator));
928 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +0000929
Faisal Vali67b04462016-06-11 16:41:54 +0000930 auto IsThisCaptured =
931 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
932 IsConst = false;
933 IsByCopy = false;
934 for (auto &&C : Closure->captures()) {
935 if (C.capturesThis()) {
936 if (C.getCaptureKind() == LCK_StarThis)
937 IsByCopy = true;
938 if (Closure->getLambdaCallOperator()->isConst())
939 IsConst = true;
940 return true;
941 }
942 }
943 return false;
944 };
945
946 bool IsByCopyCapture = false;
947 bool IsConstCapture = false;
948 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
949 while (Closure &&
950 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
951 if (IsByCopyCapture) {
952 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
953 if (IsConstCapture)
954 ClassType.addConst();
955 return ASTCtx.getPointerType(ClassType);
956 }
957 Closure = isLambdaCallOperator(Closure->getParent())
958 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
959 : nullptr;
960 }
961 }
962 return ASTCtx.getPointerType(ClassType);
963}
964
Eli Friedman73a04092012-01-07 04:59:52 +0000965QualType Sema::getCurrentThisType() {
966 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +0000967 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000968
Richard Smith938f40b2011-06-11 17:19:42 +0000969 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
970 if (method && method->isInstance())
971 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000972 }
Faisal Validc6b5962016-03-21 09:25:37 +0000973
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000974 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
975 !ActiveTemplateInstantiations.empty()) {
Faisal Validc6b5962016-03-21 09:25:37 +0000976
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000977 assert(isa<CXXRecordDecl>(DC) &&
978 "Trying to get 'this' type from static method?");
979
980 // This is a lambda call operator that is being instantiated as a default
981 // initializer. DC must point to the enclosing class type, so we can recover
982 // the 'this' type from it.
983
984 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
985 // There are no cv-qualifiers for 'this' within default initializers,
986 // per [expr.prim.general]p4.
987 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +0000988 }
Faisal Vali67b04462016-06-11 16:41:54 +0000989
990 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
991 // might need to be adjusted if the lambda or any of its enclosing lambda's
992 // captures '*this' by copy.
993 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
994 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
995 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000996 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +0000997}
998
Simon Pilgrim75c26882016-09-30 14:25:09 +0000999Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001000 Decl *ContextDecl,
1001 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001002 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001003 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1004{
1005 if (!Enabled || !ContextDecl)
1006 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001007
1008 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001009 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1010 Record = Template->getTemplatedDecl();
1011 else
1012 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001013
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001014 // We care only for CVR qualifiers here, so cut everything else.
1015 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001016 S.CXXThisTypeOverride
1017 = S.Context.getPointerType(
1018 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001019
Douglas Gregor3024f072012-04-16 07:05:22 +00001020 this->Enabled = true;
1021}
1022
1023
1024Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1025 if (Enabled) {
1026 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1027 }
1028}
1029
Faisal Validc6b5962016-03-21 09:25:37 +00001030static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1031 QualType ThisTy, SourceLocation Loc,
1032 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001033
Faisal Vali67b04462016-06-11 16:41:54 +00001034 QualType AdjustedThisTy = ThisTy;
1035 // The type of the corresponding data member (not a 'this' pointer if 'by
1036 // copy').
1037 QualType CaptureThisFieldTy = ThisTy;
1038 if (ByCopy) {
1039 // If we are capturing the object referred to by '*this' by copy, ignore any
1040 // cv qualifiers inherited from the type of the member function for the type
1041 // of the closure-type's corresponding data member and any use of 'this'.
1042 CaptureThisFieldTy = ThisTy->getPointeeType();
1043 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1044 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1045 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001046
Faisal Vali67b04462016-06-11 16:41:54 +00001047 FieldDecl *Field = FieldDecl::Create(
1048 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1049 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1050 ICIS_NoInit);
1051
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001052 Field->setImplicit(true);
1053 Field->setAccess(AS_private);
1054 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001055 Expr *This =
1056 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001057 if (ByCopy) {
1058 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1059 UO_Deref,
1060 This).get();
1061 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001062 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001063 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1064 InitializationSequence Init(S, Entity, InitKind, StarThis);
1065 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1066 if (ER.isInvalid()) return nullptr;
1067 return ER.get();
1068 }
1069 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001070}
1071
Simon Pilgrim75c26882016-09-30 14:25:09 +00001072bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001073 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1074 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001075 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001076 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001077 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001078
Faisal Validc6b5962016-03-21 09:25:37 +00001079 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001080
Faisal Valia17d19f2013-11-07 05:17:06 +00001081 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
Faisal Validc6b5962016-03-21 09:25:37 +00001082 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001083
Simon Pilgrim75c26882016-09-30 14:25:09 +00001084 // Check that we can capture the *enclosing object* (referred to by '*this')
1085 // by the capturing-entity/closure (lambda/block/etc) at
1086 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1087
1088 // Note: The *enclosing object* can only be captured by-value by a
1089 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001090 // [*this] { ... }.
1091 // Every other capture of the *enclosing object* results in its by-reference
1092 // capture.
1093
1094 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1095 // stack), we can capture the *enclosing object* only if:
1096 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1097 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001098 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001099 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001100 // -- or, there is some enclosing closure 'E' that has already captured the
1101 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001102 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001103 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001104 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001105
1106
Faisal Validc6b5962016-03-21 09:25:37 +00001107 unsigned NumCapturingClosures = 0;
Faisal Valia17d19f2013-11-07 05:17:06 +00001108 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001109 if (CapturingScopeInfo *CSI =
1110 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1111 if (CSI->CXXThisCaptureIndex != 0) {
1112 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman73a04092012-01-07 04:59:52 +00001113 break;
1114 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001115 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1116 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1117 // This context can't implicitly capture 'this'; fail out.
1118 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001119 Diag(Loc, diag::err_this_capture)
1120 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001121 return true;
1122 }
Eli Friedman20139d32012-01-11 02:36:31 +00001123 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001124 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001125 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001126 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001127 (Explicit && idx == MaxFunctionScopesIndex)) {
1128 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1129 // iteration through can be an explicit capture, all enclosing closures,
1130 // if any, must perform implicit captures.
1131
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001132 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001133 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001134 continue;
1135 }
Eli Friedman20139d32012-01-11 02:36:31 +00001136 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001137 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001138 Diag(Loc, diag::err_this_capture)
1139 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001140 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001141 }
Eli Friedman73a04092012-01-07 04:59:52 +00001142 break;
1143 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001144 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001145
1146 // If we got here, then the closure at MaxFunctionScopesIndex on the
1147 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1148 // (including implicit by-reference captures in any enclosing closures).
1149
1150 // In the loop below, respect the ByCopy flag only for the closure requesting
1151 // the capture (i.e. first iteration through the loop below). Ignore it for
1152 // all enclosing closure's upto NumCapturingClosures (since they must be
1153 // implicitly capturing the *enclosing object* by reference (see loop
1154 // above)).
1155 assert((!ByCopy ||
1156 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1157 "Only a lambda can capture the enclosing object (referred to by "
1158 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001159 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1160 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001161 QualType ThisTy = getCurrentThisType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00001162 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
Faisal Validc6b5962016-03-21 09:25:37 +00001163 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001164 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001165 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001166
Faisal Validc6b5962016-03-21 09:25:37 +00001167 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1168 // For lambda expressions, build a field and an initializing expression,
1169 // and capture the *enclosing object* by copy only if this is the first
1170 // iteration.
1171 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1172 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001173
Faisal Validc6b5962016-03-21 09:25:37 +00001174 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001175 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001176 ThisExpr =
1177 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1178 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001179
Faisal Validc6b5962016-03-21 09:25:37 +00001180 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001181 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001182 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001183 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001184}
1185
Richard Smith938f40b2011-06-11 17:19:42 +00001186ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001187 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1188 /// is a non-lvalue expression whose value is the address of the object for
1189 /// which the function is called.
1190
Douglas Gregor09deffa2011-10-18 16:47:30 +00001191 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001192 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001193
Eli Friedman73a04092012-01-07 04:59:52 +00001194 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001195 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001196}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001197
Douglas Gregor3024f072012-04-16 07:05:22 +00001198bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1199 // If we're outside the body of a member function, then we'll have a specified
1200 // type for 'this'.
1201 if (CXXThisTypeOverride.isNull())
1202 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001203
Douglas Gregor3024f072012-04-16 07:05:22 +00001204 // Determine whether we're looking into a class that's currently being
1205 // defined.
1206 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1207 return Class && Class->isBeingDefined();
1208}
1209
John McCalldadc5752010-08-24 06:29:42 +00001210ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001211Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001212 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001213 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001214 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001215 if (!TypeRep)
1216 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001217
John McCall97513962010-01-15 18:39:57 +00001218 TypeSourceInfo *TInfo;
1219 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1220 if (!TInfo)
1221 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001222
Richard Smithb8c414c2016-06-30 20:24:30 +00001223 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1224 // Avoid creating a non-type-dependent expression that contains typos.
1225 // Non-type-dependent expressions are liable to be discarded without
1226 // checking for embedded typos.
1227 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1228 !Result.get()->isTypeDependent())
1229 Result = CorrectDelayedTyposInExpr(Result.get());
1230 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001231}
1232
1233/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1234/// Can be interpreted either as function-style casting ("int(x)")
1235/// or class type construction ("ClassType(x,y,z)")
1236/// or creation of a value-initialized type ("int()").
1237ExprResult
1238Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1239 SourceLocation LParenLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001240 MultiExprArg Exprs,
Douglas Gregor2b88c112010-09-08 00:15:04 +00001241 SourceLocation RParenLoc) {
1242 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001243 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001244
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001245 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001246 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1247 RParenLoc);
Douglas Gregor0950e412009-03-13 21:01:28 +00001248 }
1249
Sebastian Redld74dd492012-02-12 18:41:05 +00001250 bool ListInitialization = LParenLoc.isInvalid();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001251 assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
Sebastian Redld74dd492012-02-12 18:41:05 +00001252 && "List initialization must have initializer list as expression.");
1253 SourceRange FullRange = SourceRange(TyBeginLoc,
1254 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1255
Douglas Gregordd04d332009-01-16 18:33:17 +00001256 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001257 // If the expression list is a single expression, the type conversion
1258 // expression is equivalent (in definedness, and if defined in meaning) to the
1259 // corresponding cast expression.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001260 if (Exprs.size() == 1 && !ListInitialization) {
John McCallb50451a2011-10-05 07:41:44 +00001261 Expr *Arg = Exprs[0];
John McCallb50451a2011-10-05 07:41:44 +00001262 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001263 }
1264
David Majnemer7eddcff2015-09-14 07:05:00 +00001265 // C++14 [expr.type.conv]p2: The expression T(), where T is a
1266 // simple-type-specifier or typename-specifier for a non-array complete
1267 // object type or the (possibly cv-qualified) void type, creates a prvalue
1268 // of the specified type, whose value is that produced by value-initializing
1269 // an object of type T.
Eli Friedman576cbd02012-02-29 00:00:28 +00001270 QualType ElemTy = Ty;
1271 if (Ty->isArrayType()) {
1272 if (!ListInitialization)
1273 return ExprError(Diag(TyBeginLoc,
1274 diag::err_value_init_for_array_type) << FullRange);
1275 ElemTy = Context.getBaseElementType(Ty);
1276 }
1277
David Majnemer7eddcff2015-09-14 07:05:00 +00001278 if (!ListInitialization && Ty->isFunctionType())
1279 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_function_type)
1280 << FullRange);
1281
Eli Friedman576cbd02012-02-29 00:00:28 +00001282 if (!Ty->isVoidType() &&
1283 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001284 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001285 return ExprError();
1286
1287 if (RequireNonAbstractType(TyBeginLoc, Ty,
1288 diag::err_allocation_of_abstract_type))
1289 return ExprError();
1290
Douglas Gregor8ec51732010-09-08 21:40:08 +00001291 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001292 InitializationKind Kind =
1293 Exprs.size() ? ListInitialization
1294 ? InitializationKind::CreateDirectList(TyBeginLoc)
1295 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
1296 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1297 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1298 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001299
Richard Smith90061902013-09-23 02:20:00 +00001300 if (Result.isInvalid() || !ListInitialization)
1301 return Result;
1302
1303 Expr *Inner = Result.get();
1304 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1305 Inner = BTE->getSubExpr();
Richard Smith1ae689c2015-01-28 22:06:01 +00001306 if (!isa<CXXTemporaryObjectExpr>(Inner)) {
1307 // If we created a CXXTemporaryObjectExpr, that node also represents the
1308 // functional cast. Otherwise, create an explicit cast to represent
1309 // the syntactic form of a functional-style cast that was used here.
1310 //
1311 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1312 // would give a more consistent AST representation than using a
1313 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1314 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001315 QualType ResultType = Result.get()->getType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001316 Result = CXXFunctionalCastExpr::Create(
Richard Smith90061902013-09-23 02:20:00 +00001317 Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001318 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
Sebastian Redl2b80af42012-02-13 19:55:43 +00001319 }
1320
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001321 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001322}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001323
Richard Smithb2f0f052016-10-10 18:54:32 +00001324/// \brief Determine whether the given function is a non-placement
1325/// deallocation function.
1326static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1327 if (FD->isInvalidDecl())
1328 return false;
1329
1330 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1331 return Method->isUsualDeallocationFunction();
1332
1333 if (FD->getOverloadedOperator() != OO_Delete &&
1334 FD->getOverloadedOperator() != OO_Array_Delete)
1335 return false;
1336
1337 unsigned UsualParams = 1;
1338
1339 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1340 S.Context.hasSameUnqualifiedType(
1341 FD->getParamDecl(UsualParams)->getType(),
1342 S.Context.getSizeType()))
1343 ++UsualParams;
1344
1345 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1346 S.Context.hasSameUnqualifiedType(
1347 FD->getParamDecl(UsualParams)->getType(),
1348 S.Context.getTypeDeclType(S.getStdAlignValT())))
1349 ++UsualParams;
1350
1351 return UsualParams == FD->getNumParams();
1352}
1353
1354namespace {
1355 struct UsualDeallocFnInfo {
1356 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001357 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001358 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smithf75dcbe2016-10-11 00:21:10 +00001359 HasSizeT(false), HasAlignValT(false), CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001360 // A function template declaration is never a usual deallocation function.
1361 if (!FD)
1362 return;
1363 if (FD->getNumParams() == 3)
1364 HasAlignValT = HasSizeT = true;
1365 else if (FD->getNumParams() == 2) {
1366 HasSizeT = FD->getParamDecl(1)->getType()->isIntegerType();
1367 HasAlignValT = !HasSizeT;
1368 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001369
1370 // In CUDA, determine how much we'd like / dislike to call this.
1371 if (S.getLangOpts().CUDA)
1372 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1373 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001374 }
1375
1376 operator bool() const { return FD; }
1377
Richard Smithf75dcbe2016-10-11 00:21:10 +00001378 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1379 bool WantAlign) const {
1380 // C++17 [expr.delete]p10:
1381 // If the type has new-extended alignment, a function with a parameter
1382 // of type std::align_val_t is preferred; otherwise a function without
1383 // such a parameter is preferred
1384 if (HasAlignValT != Other.HasAlignValT)
1385 return HasAlignValT == WantAlign;
1386
1387 if (HasSizeT != Other.HasSizeT)
1388 return HasSizeT == WantSize;
1389
1390 // Use CUDA call preference as a tiebreaker.
1391 return CUDAPref > Other.CUDAPref;
1392 }
1393
Richard Smithb2f0f052016-10-10 18:54:32 +00001394 DeclAccessPair Found;
1395 FunctionDecl *FD;
1396 bool HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001397 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001398 };
1399}
1400
1401/// Determine whether a type has new-extended alignment. This may be called when
1402/// the type is incomplete (for a delete-expression with an incomplete pointee
1403/// type), in which case it will conservatively return false if the alignment is
1404/// not known.
1405static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1406 return S.getLangOpts().AlignedAllocation &&
1407 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1408 S.getASTContext().getTargetInfo().getNewAlign();
1409}
1410
1411/// Select the correct "usual" deallocation function to use from a selection of
1412/// deallocation functions (either global or class-scope).
1413static UsualDeallocFnInfo resolveDeallocationOverload(
1414 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1415 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1416 UsualDeallocFnInfo Best;
1417
Richard Smithb2f0f052016-10-10 18:54:32 +00001418 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001419 UsualDeallocFnInfo Info(S, I.getPair());
1420 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1421 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001422 continue;
1423
1424 if (!Best) {
1425 Best = Info;
1426 if (BestFns)
1427 BestFns->push_back(Info);
1428 continue;
1429 }
1430
Richard Smithf75dcbe2016-10-11 00:21:10 +00001431 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001432 continue;
1433
1434 // If more than one preferred function is found, all non-preferred
1435 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001436 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001437 BestFns->clear();
1438
1439 Best = Info;
1440 if (BestFns)
1441 BestFns->push_back(Info);
1442 }
1443
1444 return Best;
1445}
1446
1447/// Determine whether a given type is a class for which 'delete[]' would call
1448/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1449/// we need to store the array size (even if the type is
1450/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001451static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1452 QualType allocType) {
1453 const RecordType *record =
1454 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1455 if (!record) return false;
1456
1457 // Try to find an operator delete[] in class scope.
1458
1459 DeclarationName deleteName =
1460 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1461 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1462 S.LookupQualifiedName(ops, record->getDecl());
1463
1464 // We're just doing this for information.
1465 ops.suppressDiagnostics();
1466
1467 // Very likely: there's no operator delete[].
1468 if (ops.empty()) return false;
1469
1470 // If it's ambiguous, it should be illegal to call operator delete[]
1471 // on this thing, so it doesn't matter if we allocate extra space or not.
1472 if (ops.isAmbiguous()) return false;
1473
Richard Smithb2f0f052016-10-10 18:54:32 +00001474 // C++17 [expr.delete]p10:
1475 // If the deallocation functions have class scope, the one without a
1476 // parameter of type std::size_t is selected.
1477 auto Best = resolveDeallocationOverload(
1478 S, ops, /*WantSize*/false,
1479 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1480 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001481}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001482
Sebastian Redld74dd492012-02-12 18:41:05 +00001483/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001484///
Sebastian Redld74dd492012-02-12 18:41:05 +00001485/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001486/// @code new (memory) int[size][4] @endcode
1487/// or
1488/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001489///
1490/// \param StartLoc The first location of the expression.
1491/// \param UseGlobal True if 'new' was prefixed with '::'.
1492/// \param PlacementLParen Opening paren of the placement arguments.
1493/// \param PlacementArgs Placement new arguments.
1494/// \param PlacementRParen Closing paren of the placement arguments.
1495/// \param TypeIdParens If the type is in parens, the source range.
1496/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001497/// \param Initializer The initializing expression or initializer-list, or null
1498/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001499ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001500Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001501 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001502 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001503 Declarator &D, Expr *Initializer) {
Richard Smith74aeef52013-04-26 16:15:35 +00001504 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
Richard Smith30482bc2011-02-20 03:19:35 +00001505
Craig Topperc3ec1492014-05-26 06:22:03 +00001506 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001507 // If the specified type is an array, unwrap it and save the expression.
1508 if (D.getNumTypeObjects() > 0 &&
1509 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
James Dennettf14a6e52012-06-15 22:23:43 +00001510 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith30482bc2011-02-20 03:19:35 +00001511 if (TypeContainsAuto)
1512 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1513 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001514 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001515 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1516 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001517 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001518 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1519 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001520
Sebastian Redl351bb782008-12-02 14:43:59 +00001521 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001522 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001523 }
1524
Douglas Gregor73341c42009-09-11 00:18:58 +00001525 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001526 if (ArraySize) {
1527 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001528 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1529 break;
1530
1531 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1532 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001533 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001534 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001535 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1536 // shall be a converted constant expression (5.19) of type std::size_t
1537 // and shall evaluate to a strictly positive value.
1538 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1539 assert(IntWidth && "Builtin type of size 0?");
1540 llvm::APSInt Value(IntWidth);
1541 Array.NumElts
1542 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1543 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001544 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001545 } else {
1546 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001547 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001548 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001549 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001550 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001551 if (!Array.NumElts)
1552 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001553 }
1554 }
1555 }
1556 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001557
Craig Topperc3ec1492014-05-26 06:22:03 +00001558 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001559 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001560 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001561 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001562
Sebastian Redl6047f072012-02-16 12:22:20 +00001563 SourceRange DirectInitRange;
1564 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1565 DirectInitRange = List->getSourceRange();
1566
David Blaikie7b97aef2012-11-07 00:12:38 +00001567 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001568 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001569 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001570 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001571 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001572 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001573 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001574 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001575 DirectInitRange,
1576 Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001577 TypeContainsAuto);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001578}
1579
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001580static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1581 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001582 if (!Init)
1583 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001584 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1585 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001586 if (isa<ImplicitValueInitExpr>(Init))
1587 return true;
1588 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1589 return !CCE->isListInitialization() &&
1590 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001591 else if (Style == CXXNewExpr::ListInit) {
1592 assert(isa<InitListExpr>(Init) &&
1593 "Shouldn't create list CXXConstructExprs for arrays.");
1594 return true;
1595 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001596 return false;
1597}
1598
John McCalldadc5752010-08-24 06:29:42 +00001599ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001600Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001601 SourceLocation PlacementLParen,
1602 MultiExprArg PlacementArgs,
1603 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001604 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001605 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001606 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001607 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001608 SourceRange DirectInitRange,
1609 Expr *Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001610 bool TypeMayContainAuto) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001611 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001612 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001613
Sebastian Redl6047f072012-02-16 12:22:20 +00001614 CXXNewExpr::InitializationStyle initStyle;
1615 if (DirectInitRange.isValid()) {
1616 assert(Initializer && "Have parens but no initializer.");
1617 initStyle = CXXNewExpr::CallInit;
1618 } else if (Initializer && isa<InitListExpr>(Initializer))
1619 initStyle = CXXNewExpr::ListInit;
1620 else {
1621 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1622 isa<CXXConstructExpr>(Initializer)) &&
1623 "Initializer expression that cannot have been implicitly created.");
1624 initStyle = CXXNewExpr::NoInit;
1625 }
1626
1627 Expr **Inits = &Initializer;
1628 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001629 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1630 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1631 Inits = List->getExprs();
1632 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001633 }
1634
Richard Smith66204ec2014-03-12 17:42:45 +00001635 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00001636 if (TypeMayContainAuto && AllocType->isUndeducedType()) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001637 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001638 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1639 << AllocType << TypeRange);
Richard Smith66204ec2014-03-12 17:42:45 +00001640 if (initStyle == CXXNewExpr::ListInit ||
1641 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001642 return ExprError(Diag(Inits[0]->getLocStart(),
Richard Smith66204ec2014-03-12 17:42:45 +00001643 diag::err_auto_new_list_init)
Sebastian Redl6047f072012-02-16 12:22:20 +00001644 << AllocType << TypeRange);
1645 if (NumInits > 1) {
1646 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001647 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001648 diag::err_auto_new_ctor_multiple_expressions)
1649 << AllocType << TypeRange);
1650 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001651 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001652 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001653 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001654 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001655 << AllocType << Deduce->getType()
1656 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001657 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001658 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001659 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001660 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001661
Douglas Gregorcda95f42010-05-16 16:01:03 +00001662 // Per C++0x [expr.new]p5, the type being constructed may be a
1663 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001664 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001665 if (const ConstantArrayType *Array
1666 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001667 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1668 Context.getSizeType(),
1669 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001670 AllocType = Array->getElementType();
1671 }
1672 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001673
Douglas Gregor3999e152010-10-06 16:00:31 +00001674 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1675 return ExprError();
1676
Craig Topperc3ec1492014-05-26 06:22:03 +00001677 if (initStyle == CXXNewExpr::ListInit &&
1678 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001679 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1680 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001681 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001682 }
1683
Simon Pilgrim75c26882016-09-30 14:25:09 +00001684 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001685 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001686 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1687 AllocType->isObjCLifetimeType()) {
1688 AllocType = Context.getLifetimeQualifiedType(AllocType,
1689 AllocType->getObjCARCImplicitLifetime());
1690 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001691
John McCall31168b02011-06-15 23:02:42 +00001692 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001693
John McCall5e77d762013-04-16 07:28:30 +00001694 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1695 ExprResult result = CheckPlaceholderExpr(ArraySize);
1696 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001697 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001698 }
Richard Smith8dd34252012-02-04 07:07:42 +00001699 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1700 // integral or enumeration type with a non-negative value."
1701 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1702 // enumeration type, or a class type for which a single non-explicit
1703 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001704 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001705 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001706 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001707 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001708 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001709 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001710 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1711
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001712 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1713 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001714
Simon Pilgrim75c26882016-09-30 14:25:09 +00001715 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001716 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001717 // Diagnose the compatibility of this conversion.
1718 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1719 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001720 } else {
1721 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1722 protected:
1723 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001724
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001725 public:
1726 SizeConvertDiagnoser(Expr *ArraySize)
1727 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1728 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001729
1730 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1731 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001732 return S.Diag(Loc, diag::err_array_size_not_integral)
1733 << S.getLangOpts().CPlusPlus11 << T;
1734 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001735
1736 SemaDiagnosticBuilder diagnoseIncomplete(
1737 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001738 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1739 << T << ArraySize->getSourceRange();
1740 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001741
1742 SemaDiagnosticBuilder diagnoseExplicitConv(
1743 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001744 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1745 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001746
1747 SemaDiagnosticBuilder noteExplicitConv(
1748 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001749 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1750 << ConvTy->isEnumeralType() << ConvTy;
1751 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001752
1753 SemaDiagnosticBuilder diagnoseAmbiguous(
1754 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001755 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1756 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001757
1758 SemaDiagnosticBuilder noteAmbiguous(
1759 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001760 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1761 << ConvTy->isEnumeralType() << ConvTy;
1762 }
Richard Smithccc11812013-05-21 19:05:48 +00001763
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001764 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1765 QualType T,
1766 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001767 return S.Diag(Loc,
1768 S.getLangOpts().CPlusPlus11
1769 ? diag::warn_cxx98_compat_array_size_conversion
1770 : diag::ext_array_size_conversion)
1771 << T << ConvTy->isEnumeralType() << ConvTy;
1772 }
1773 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001774
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001775 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1776 SizeDiagnoser);
1777 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001778 if (ConvertedSize.isInvalid())
1779 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001780
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001781 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001782 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001783
Douglas Gregor0bf31402010-10-08 23:50:27 +00001784 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001785 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001786
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001787 // C++98 [expr.new]p7:
1788 // The expression in a direct-new-declarator shall have integral type
1789 // with a non-negative value.
1790 //
Richard Smith0511d232016-10-05 22:41:02 +00001791 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1792 // per CWG1464. Otherwise, if it's not a constant, we must have an
1793 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001794 if (!ArraySize->isValueDependent()) {
1795 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001796 // We've already performed any required implicit conversion to integer or
1797 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001798 // FIXME: Per CWG1464, we are required to check the value prior to
1799 // converting to size_t. This will never find a negative array size in
1800 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001801 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001802 if (Value.isSigned() && Value.isNegative()) {
1803 return ExprError(Diag(ArraySize->getLocStart(),
1804 diag::err_typecheck_negative_array_size)
1805 << ArraySize->getSourceRange());
1806 }
1807
1808 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001809 unsigned ActiveSizeBits =
1810 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00001811 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1812 return ExprError(Diag(ArraySize->getLocStart(),
1813 diag::err_array_too_large)
1814 << Value.toString(10)
1815 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001816 }
Richard Smith0511d232016-10-05 22:41:02 +00001817
1818 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00001819 } else if (TypeIdParens.isValid()) {
1820 // Can't have dynamic array size when the type-id is in parentheses.
1821 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1822 << ArraySize->getSourceRange()
1823 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1824 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001825
Douglas Gregorf2753b32010-07-13 15:54:32 +00001826 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001827 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001828 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001829
John McCall036f2f62011-05-15 07:14:44 +00001830 // Note that we do *not* convert the argument in any way. It can
1831 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001832 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001833
Craig Topperc3ec1492014-05-26 06:22:03 +00001834 FunctionDecl *OperatorNew = nullptr;
1835 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00001836 unsigned Alignment =
1837 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1838 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1839 bool PassAlignment = getLangOpts().AlignedAllocation &&
1840 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001841
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001842 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001843 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001844 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001845 SourceRange(PlacementLParen, PlacementRParen),
Richard Smithb2f0f052016-10-10 18:54:32 +00001846 UseGlobal, AllocType, ArraySize, PassAlignment,
1847 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001848 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001849
1850 // If this is an array allocation, compute whether the usual array
1851 // deallocation function for the type has a size_t parameter.
1852 bool UsualArrayDeleteWantsSize = false;
1853 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00001854 UsualArrayDeleteWantsSize =
1855 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00001856
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001857 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001858 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001859 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00001860 OperatorNew->getType()->getAs<FunctionProtoType>();
1861 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1862 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001863
Richard Smithd6f9e732014-05-13 19:56:21 +00001864 // We've already converted the placement args, just fill in any default
1865 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00001866 // argument. Skip the second parameter too if we're passing in the
1867 // alignment; we've already filled it in.
1868 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
1869 PassAlignment ? 2 : 1, PlacementArgs,
1870 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001871 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001872
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001873 if (!AllPlaceArgs.empty())
1874 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00001875
Richard Smithd6f9e732014-05-13 19:56:21 +00001876 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001877 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00001878
1879 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001880
Richard Smithb2f0f052016-10-10 18:54:32 +00001881 // Warn if the type is over-aligned and is being allocated by (unaligned)
1882 // global operator new.
1883 if (PlacementArgs.empty() && !PassAlignment &&
1884 (OperatorNew->isImplicit() ||
1885 (OperatorNew->getLocStart().isValid() &&
1886 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
1887 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00001888 Diag(StartLoc, diag::warn_overaligned_type)
1889 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00001890 << unsigned(Alignment / Context.getCharWidth())
1891 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00001892 }
1893 }
1894
Sebastian Redl6047f072012-02-16 12:22:20 +00001895 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001896 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1897 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00001898 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
1899 SourceRange InitRange(Inits[0]->getLocStart(),
1900 Inits[NumInits - 1]->getLocEnd());
1901 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1902 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001903 }
1904
Richard Smithdd2ca572012-11-26 08:32:48 +00001905 // If we can perform the initialization, and we've not already done so,
1906 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00001907 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001908 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00001909 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00001910 // The type we initialize is the complete type, including the array bound.
1911 QualType InitType;
1912 if (KnownArraySize)
1913 InitType = Context.getConstantArrayType(
1914 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
1915 *KnownArraySize),
1916 ArrayType::Normal, 0);
1917 else if (ArraySize)
1918 InitType =
1919 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
1920 else
1921 InitType = AllocType;
1922
Sebastian Redld74dd492012-02-12 18:41:05 +00001923 // C++11 [expr.new]p15:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001924 // A new-expression that creates an object of type T initializes that
1925 // object as follows:
1926 InitializationKind Kind
1927 // - If the new-initializer is omitted, the object is default-
1928 // initialized (8.5); if no initialization is performed,
1929 // the object has indeterminate value
Sebastian Redl6047f072012-02-16 12:22:20 +00001930 = initStyle == CXXNewExpr::NoInit
1931 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001932 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001933 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +00001934 : initStyle == CXXNewExpr::ListInit
1935 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1936 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1937 DirectInitRange.getBegin(),
1938 DirectInitRange.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001939
Douglas Gregor85dabae2009-12-16 01:38:02 +00001940 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001941 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00001942 InitializationSequence InitSeq(*this, Entity, Kind,
1943 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001944 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00001945 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00001946 if (FullInit.isInvalid())
1947 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001948
Sebastian Redl6047f072012-02-16 12:22:20 +00001949 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1950 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00001951 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00001952 if (CXXBindTemporaryExpr *Binder =
1953 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001954 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001955
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001956 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001958
Douglas Gregor6642ca22010-02-26 05:06:18 +00001959 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00001960 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00001961 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1962 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001963 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00001964 }
1965 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00001966 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1967 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001968 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00001969 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00001970
John McCall928a2572011-07-13 20:12:57 +00001971 // C++0x [expr.new]p17:
1972 // If the new expression creates an array of objects of class type,
1973 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00001974 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1975 if (ArraySize && !BaseAllocType->isDependentType()) {
1976 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1977 if (CXXDestructorDecl *dtor = LookupDestructor(
1978 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1979 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001980 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00001981 PDiag(diag::err_access_dtor)
1982 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00001983 if (DiagnoseUseOfDecl(dtor, StartLoc))
1984 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00001985 }
John McCall928a2572011-07-13 20:12:57 +00001986 }
1987 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001988
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001989 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00001990 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001991 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
1992 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
1993 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00001994}
1995
Sebastian Redl6047f072012-02-16 12:22:20 +00001996/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00001997/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00001998bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00001999 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002000 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2001 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002002 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002003 return Diag(Loc, diag::err_bad_new_type)
2004 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002005 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002006 return Diag(Loc, diag::err_bad_new_type)
2007 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002008 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002009 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002010 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002011 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002012 diag::err_allocation_of_abstract_type))
2013 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002014 else if (AllocType->isVariablyModifiedType())
2015 return Diag(Loc, diag::err_variably_modified_new_type)
2016 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00002017 else if (unsigned AddressSpace = AllocType.getAddressSpace())
2018 return Diag(Loc, diag::err_address_space_qualified_new)
2019 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002020 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002021 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2022 QualType BaseAllocType = Context.getBaseElementType(AT);
2023 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2024 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002025 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002026 << BaseAllocType;
2027 }
2028 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002029
Sebastian Redlbd150f42008-11-21 19:14:01 +00002030 return false;
2031}
2032
Richard Smithb2f0f052016-10-10 18:54:32 +00002033static bool
2034resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2035 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2036 FunctionDecl *&Operator,
2037 OverloadCandidateSet *AlignedCandidates = nullptr,
2038 Expr *AlignArg = nullptr) {
2039 OverloadCandidateSet Candidates(R.getNameLoc(),
2040 OverloadCandidateSet::CSK_Normal);
2041 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2042 Alloc != AllocEnd; ++Alloc) {
2043 // Even member operator new/delete are implicitly treated as
2044 // static, so don't use AddMemberCandidate.
2045 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2046
2047 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2048 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2049 /*ExplicitTemplateArgs=*/nullptr, Args,
2050 Candidates,
2051 /*SuppressUserConversions=*/false);
2052 continue;
2053 }
2054
2055 FunctionDecl *Fn = cast<FunctionDecl>(D);
2056 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2057 /*SuppressUserConversions=*/false);
2058 }
2059
2060 // Do the resolution.
2061 OverloadCandidateSet::iterator Best;
2062 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2063 case OR_Success: {
2064 // Got one!
2065 FunctionDecl *FnDecl = Best->Function;
2066 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2067 Best->FoundDecl) == Sema::AR_inaccessible)
2068 return true;
2069
2070 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002071 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002072 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002073
Richard Smithb2f0f052016-10-10 18:54:32 +00002074 case OR_No_Viable_Function:
2075 // C++17 [expr.new]p13:
2076 // If no matching function is found and the allocated object type has
2077 // new-extended alignment, the alignment argument is removed from the
2078 // argument list, and overload resolution is performed again.
2079 if (PassAlignment) {
2080 PassAlignment = false;
2081 AlignArg = Args[1];
2082 Args.erase(Args.begin() + 1);
2083 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2084 Operator, &Candidates, AlignArg);
2085 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002086
Richard Smithb2f0f052016-10-10 18:54:32 +00002087 // MSVC will fall back on trying to find a matching global operator new
2088 // if operator new[] cannot be found. Also, MSVC will leak by not
2089 // generating a call to operator delete or operator delete[], but we
2090 // will not replicate that bug.
2091 // FIXME: Find out how this interacts with the std::align_val_t fallback
2092 // once MSVC implements it.
2093 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2094 S.Context.getLangOpts().MSVCCompat) {
2095 R.clear();
2096 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2097 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2098 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2099 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2100 Operator, nullptr);
2101 }
Richard Smith1cdec012013-09-29 04:40:38 +00002102
Richard Smithb2f0f052016-10-10 18:54:32 +00002103 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2104 << R.getLookupName() << Range;
2105
2106 // If we have aligned candidates, only note the align_val_t candidates
2107 // from AlignedCandidates and the non-align_val_t candidates from
2108 // Candidates.
2109 if (AlignedCandidates) {
2110 auto IsAligned = [](OverloadCandidate &C) {
2111 return C.Function->getNumParams() > 1 &&
2112 C.Function->getParamDecl(1)->getType()->isAlignValT();
2113 };
2114 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2115
2116 // This was an overaligned allocation, so list the aligned candidates
2117 // first.
2118 Args.insert(Args.begin() + 1, AlignArg);
2119 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2120 R.getNameLoc(), IsAligned);
2121 Args.erase(Args.begin() + 1);
2122 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2123 IsUnaligned);
2124 } else {
2125 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2126 }
Richard Smith1cdec012013-09-29 04:40:38 +00002127 return true;
2128
Richard Smithb2f0f052016-10-10 18:54:32 +00002129 case OR_Ambiguous:
2130 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2131 << R.getLookupName() << Range;
2132 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2133 return true;
2134
2135 case OR_Deleted: {
2136 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2137 << Best->Function->isDeleted()
2138 << R.getLookupName()
2139 << S.getDeletedOrUnavailableSuffix(Best->Function)
2140 << Range;
2141 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2142 return true;
2143 }
2144 }
2145 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002146}
2147
Richard Smithb2f0f052016-10-10 18:54:32 +00002148
Sebastian Redlfaf68082008-12-03 20:26:15 +00002149/// FindAllocationFunctions - Finds the overloads of operator new and delete
2150/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002151bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2152 bool UseGlobal, QualType AllocType,
Richard Smithb2f0f052016-10-10 18:54:32 +00002153 bool IsArray, bool &PassAlignment,
2154 MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002155 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00002156 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002157 // --- Choosing an allocation function ---
2158 // C++ 5.3.4p8 - 14 & 18
2159 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2160 // in the scope of the allocated class.
2161 // 2) If an array size is given, look for operator new[], else look for
2162 // operator new.
2163 // 3) The first argument is always size_t. Append the arguments from the
2164 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002165
Richard Smithb2f0f052016-10-10 18:54:32 +00002166 SmallVector<Expr*, 8> AllocArgs;
2167 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2168
2169 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002170 // FIXME: Should the Sema create the expression and embed it in the syntax
2171 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002172 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002173 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002174 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002175 Context.getSizeType(),
2176 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002177 AllocArgs.push_back(&Size);
2178
2179 QualType AlignValT = Context.VoidTy;
2180 if (PassAlignment) {
2181 DeclareGlobalNewDelete();
2182 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2183 }
2184 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2185 if (PassAlignment)
2186 AllocArgs.push_back(&Align);
2187
2188 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002189
Douglas Gregor6642ca22010-02-26 05:06:18 +00002190 // C++ [expr.new]p8:
2191 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002192 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002193 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002194 // type, the allocation function's name is operator new[] and the
2195 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002196 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002197 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002198
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002199 QualType AllocElemType = Context.getBaseElementType(AllocType);
2200
Richard Smithb2f0f052016-10-10 18:54:32 +00002201 // Find the allocation function.
2202 {
2203 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2204
2205 // C++1z [expr.new]p9:
2206 // If the new-expression begins with a unary :: operator, the allocation
2207 // function's name is looked up in the global scope. Otherwise, if the
2208 // allocated type is a class type T or array thereof, the allocation
2209 // function's name is looked up in the scope of T.
2210 if (AllocElemType->isRecordType() && !UseGlobal)
2211 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2212
2213 // We can see ambiguity here if the allocation function is found in
2214 // multiple base classes.
2215 if (R.isAmbiguous())
2216 return true;
2217
2218 // If this lookup fails to find the name, or if the allocated type is not
2219 // a class type, the allocation function's name is looked up in the
2220 // global scope.
2221 if (R.empty())
2222 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2223
2224 assert(!R.empty() && "implicitly declared allocation functions not found");
2225 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2226
2227 // We do our own custom access checks below.
2228 R.suppressDiagnostics();
2229
2230 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2231 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002232 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002233 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002234
Richard Smithb2f0f052016-10-10 18:54:32 +00002235 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002236 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002237 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002238 return false;
2239 }
2240
Richard Smithb2f0f052016-10-10 18:54:32 +00002241 // Note, the name of OperatorNew might have been changed from array to
2242 // non-array by resolveAllocationOverload.
2243 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2244 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2245 ? OO_Array_Delete
2246 : OO_Delete);
2247
Douglas Gregor6642ca22010-02-26 05:06:18 +00002248 // C++ [expr.new]p19:
2249 //
2250 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002251 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002252 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002253 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002254 // the scope of T. If this lookup fails to find the name, or if
2255 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002256 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002257 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002258 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002259 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002260 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002261 LookupQualifiedName(FoundDelete, RD);
2262 }
John McCallfb6f5262010-03-18 08:19:33 +00002263 if (FoundDelete.isAmbiguous())
2264 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002265
Richard Smithb2f0f052016-10-10 18:54:32 +00002266 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002267 if (FoundDelete.empty()) {
2268 DeclareGlobalNewDelete();
2269 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2270 }
2271
2272 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002273
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002274 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002275
John McCalld3be2c82010-09-14 21:34:24 +00002276 // Whether we're looking for a placement operator delete is dictated
2277 // by whether we selected a placement operator new, not by whether
2278 // we had explicit placement arguments. This matters for things like
2279 // struct A { void *operator new(size_t, int = 0); ... };
2280 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002281 //
2282 // We don't have any definition for what a "placement allocation function"
2283 // is, but we assume it's any allocation function whose
2284 // parameter-declaration-clause is anything other than (size_t).
2285 //
2286 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2287 // This affects whether an exception from the constructor of an overaligned
2288 // type uses the sized or non-sized form of aligned operator delete.
2289 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2290 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002291
2292 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002293 // C++ [expr.new]p20:
2294 // A declaration of a placement deallocation function matches the
2295 // declaration of a placement allocation function if it has the
2296 // same number of parameters and, after parameter transformations
2297 // (8.3.5), all parameter types except the first are
2298 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002299 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002300 // To perform this comparison, we compute the function type that
2301 // the deallocation function should have, and use that type both
2302 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00002303 //
2304 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002305 QualType ExpectedFunctionType;
2306 {
2307 const FunctionProtoType *Proto
2308 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002309
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002310 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002311 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002312 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2313 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002314
John McCalldb40c7f2010-12-14 08:05:40 +00002315 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002316 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002317 EPI.Variadic = Proto->isVariadic();
Richard Smithb2f0f052016-10-10 18:54:32 +00002318 EPI.ExceptionSpec.Type = EST_BasicNoexcept;
John McCalldb40c7f2010-12-14 08:05:40 +00002319
Douglas Gregor6642ca22010-02-26 05:06:18 +00002320 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002321 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002322 }
2323
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002324 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002325 DEnd = FoundDelete.end();
2326 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002327 FunctionDecl *Fn = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002328 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6642ca22010-02-26 05:06:18 +00002329 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2330 // Perform template argument deduction to try to match the
2331 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002332 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002333 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2334 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002335 continue;
2336 } else
2337 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2338
2339 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002340 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002341 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002342
Richard Smithb2f0f052016-10-10 18:54:32 +00002343 if (getLangOpts().CUDA)
2344 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2345 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002346 // C++1y [expr.new]p22:
2347 // For a non-placement allocation function, the normal deallocation
2348 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002349 //
2350 // Per [expr.delete]p10, this lookup prefers a member operator delete
2351 // without a size_t argument, but prefers a non-member operator delete
2352 // with a size_t where possible (which it always is in this case).
2353 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2354 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2355 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2356 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2357 &BestDeallocFns);
2358 if (Selected)
2359 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2360 else {
2361 // If we failed to select an operator, all remaining functions are viable
2362 // but ambiguous.
2363 for (auto Fn : BestDeallocFns)
2364 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002365 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002366 }
2367
2368 // C++ [expr.new]p20:
2369 // [...] If the lookup finds a single matching deallocation
2370 // function, that function will be called; otherwise, no
2371 // deallocation function will be called.
2372 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002373 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002374
Richard Smithb2f0f052016-10-10 18:54:32 +00002375 // C++1z [expr.new]p23:
2376 // If the lookup finds a usual deallocation function (3.7.4.2)
2377 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002378 // as a placement deallocation function, would have been
2379 // selected as a match for the allocation function, the program
2380 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002381 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002382 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002383 UsualDeallocFnInfo Info(*this,
2384 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002385 // Core issue, per mail to core reflector, 2016-10-09:
2386 // If this is a member operator delete, and there is a corresponding
2387 // non-sized member operator delete, this isn't /really/ a sized
2388 // deallocation function, it just happens to have a size_t parameter.
2389 bool IsSizedDelete = Info.HasSizeT;
2390 if (IsSizedDelete && !FoundGlobalDelete) {
2391 auto NonSizedDelete =
2392 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2393 /*WantAlign*/Info.HasAlignValT);
2394 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2395 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2396 IsSizedDelete = false;
2397 }
2398
2399 if (IsSizedDelete) {
2400 SourceRange R = PlaceArgs.empty()
2401 ? SourceRange()
2402 : SourceRange(PlaceArgs.front()->getLocStart(),
2403 PlaceArgs.back()->getLocEnd());
2404 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2405 if (!OperatorDelete->isImplicit())
2406 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2407 << DeleteName;
2408 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002409 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002410
2411 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2412 Matches[0].first);
2413 } else if (!Matches.empty()) {
2414 // We found multiple suitable operators. Per [expr.new]p20, that means we
2415 // call no 'operator delete' function, but we should at least warn the user.
2416 // FIXME: Suppress this warning if the construction cannot throw.
2417 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2418 << DeleteName << AllocElemType;
2419
2420 for (auto &Match : Matches)
2421 Diag(Match.second->getLocation(),
2422 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002423 }
2424
Sebastian Redlfaf68082008-12-03 20:26:15 +00002425 return false;
2426}
2427
2428/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2429/// delete. These are:
2430/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002431/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002432/// void* operator new(std::size_t) throw(std::bad_alloc);
2433/// void* operator new[](std::size_t) throw(std::bad_alloc);
2434/// void operator delete(void *) throw();
2435/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002436/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002437/// void* operator new(std::size_t);
2438/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002439/// void operator delete(void *) noexcept;
2440/// void operator delete[](void *) noexcept;
2441/// // C++1y:
2442/// void* operator new(std::size_t);
2443/// void* operator new[](std::size_t);
2444/// void operator delete(void *) noexcept;
2445/// void operator delete[](void *) noexcept;
2446/// void operator delete(void *, std::size_t) noexcept;
2447/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002448/// @endcode
2449/// Note that the placement and nothrow forms of new are *not* implicitly
2450/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002451void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002452 if (GlobalNewDeleteDeclared)
2453 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002454
Douglas Gregor87f54062009-09-15 22:30:29 +00002455 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002456 // [...] The following allocation and deallocation functions (18.4) are
2457 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002458 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002459 //
Sebastian Redl37588092011-03-14 18:08:30 +00002460 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002461 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002462 // void* operator new[](std::size_t) throw(std::bad_alloc);
2463 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002464 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002465 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002466 // void* operator new(std::size_t);
2467 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002468 // void operator delete(void*) noexcept;
2469 // void operator delete[](void*) noexcept;
2470 // C++1y:
2471 // void* operator new(std::size_t);
2472 // void* operator new[](std::size_t);
2473 // void operator delete(void*) noexcept;
2474 // void operator delete[](void*) noexcept;
2475 // void operator delete(void*, std::size_t) noexcept;
2476 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002477 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002478 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002479 // new, operator new[], operator delete, operator delete[].
2480 //
2481 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2482 // "std" or "bad_alloc" as necessary to form the exception specification.
2483 // However, we do not make these implicit declarations visible to name
2484 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002485 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002486 // The "std::bad_alloc" class has not yet been declared, so build it
2487 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002488 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2489 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002490 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002491 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002492 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002493 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002494 }
Richard Smith59139022016-09-30 22:41:36 +00002495 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002496 // The "std::align_val_t" enum class has not yet been declared, so build it
2497 // implicitly.
2498 auto *AlignValT = EnumDecl::Create(
2499 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2500 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2501 AlignValT->setIntegerType(Context.getSizeType());
2502 AlignValT->setPromotionType(Context.getSizeType());
2503 AlignValT->setImplicit(true);
2504 StdAlignValT = AlignValT;
2505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002506
Sebastian Redlfaf68082008-12-03 20:26:15 +00002507 GlobalNewDeleteDeclared = true;
2508
2509 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2510 QualType SizeT = Context.getSizeType();
2511
Richard Smith96269c52016-09-29 22:49:46 +00002512 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2513 QualType Return, QualType Param) {
2514 llvm::SmallVector<QualType, 3> Params;
2515 Params.push_back(Param);
2516
2517 // Create up to four variants of the function (sized/aligned).
2518 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2519 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002520 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002521
2522 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2523 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2524 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002525 if (Sized)
2526 Params.push_back(SizeT);
2527
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002528 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002529 if (Aligned)
2530 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2531
2532 DeclareGlobalAllocationFunction(
2533 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2534
2535 if (Aligned)
2536 Params.pop_back();
2537 }
2538 }
2539 };
2540
2541 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2542 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2543 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2544 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002545}
2546
2547/// DeclareGlobalAllocationFunction - Declares a single implicit global
2548/// allocation function if it doesn't already exist.
2549void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002550 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002551 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002552 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2553
2554 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002555 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2556 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2557 Alloc != AllocEnd; ++Alloc) {
2558 // Only look at non-template functions, as it is the predefined,
2559 // non-templated allocation function we are trying to declare here.
2560 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002561 if (Func->getNumParams() == Params.size()) {
2562 llvm::SmallVector<QualType, 3> FuncParams;
2563 for (auto *P : Func->parameters())
2564 FuncParams.push_back(
2565 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2566 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002567 // Make the function visible to name lookup, even if we found it in
2568 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002569 // allocation function, or is suppressing that function.
2570 Func->setHidden(false);
Chandler Carruth93538422010-02-03 11:02:14 +00002571 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002572 }
Chandler Carruth93538422010-02-03 11:02:14 +00002573 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002574 }
2575 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002576
Richard Smithc015bc22014-02-07 22:39:53 +00002577 FunctionProtoType::ExtProtoInfo EPI;
2578
Richard Smithf8b417c2014-02-08 00:42:45 +00002579 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002580 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002581 = (Name.getCXXOverloadedOperator() == OO_New ||
2582 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002583 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002584 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002585 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002586 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002587 EPI.ExceptionSpec.Type = EST_Dynamic;
2588 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002589 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002590 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002591 EPI.ExceptionSpec =
2592 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002594
Richard Smith96269c52016-09-29 22:49:46 +00002595 QualType FnType = Context.getFunctionType(Return, Params, EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002596 FunctionDecl *Alloc =
Abramo Bagnaradff19302011-03-08 08:55:46 +00002597 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
2598 SourceLocation(), Name,
Craig Topperc3ec1492014-05-26 06:22:03 +00002599 FnType, /*TInfo=*/nullptr, SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002600 Alloc->setImplicit();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002601
Larisse Voufo404e1422015-02-04 02:34:32 +00002602 // Implicit sized deallocation functions always have default visibility.
2603 Alloc->addAttr(VisibilityAttr::CreateImplicit(Context,
2604 VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002605
Richard Smith96269c52016-09-29 22:49:46 +00002606 llvm::SmallVector<ParmVarDecl*, 3> ParamDecls;
2607 for (QualType T : Params) {
2608 ParamDecls.push_back(
2609 ParmVarDecl::Create(Context, Alloc, SourceLocation(), SourceLocation(),
2610 nullptr, T, /*TInfo=*/nullptr, SC_None, nullptr));
2611 ParamDecls.back()->setImplicit();
Richard Smithbdd14642014-02-04 01:14:30 +00002612 }
Richard Smith96269c52016-09-29 22:49:46 +00002613 Alloc->setParams(ParamDecls);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002614
John McCallcc14d1f2010-08-24 08:50:51 +00002615 Context.getTranslationUnitDecl()->addDecl(Alloc);
Richard Smithdebcd502014-05-16 02:14:42 +00002616 IdResolver.tryAddTopLevelDecl(Alloc, Name);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002617}
2618
Richard Smith1cdec012013-09-29 04:40:38 +00002619FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2620 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002621 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002622 DeclarationName Name) {
2623 DeclareGlobalNewDelete();
2624
2625 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2626 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2627
Richard Smithb2f0f052016-10-10 18:54:32 +00002628 // FIXME: It's possible for this to result in ambiguity, through a
2629 // user-declared variadic operator delete or the enable_if attribute. We
2630 // should probably not consider those cases to be usual deallocation
2631 // functions. But for now we just make an arbitrary choice in that case.
2632 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2633 Overaligned);
2634 assert(Result.FD && "operator delete missing from global scope?");
2635 return Result.FD;
2636}
Richard Smith1cdec012013-09-29 04:40:38 +00002637
Richard Smithb2f0f052016-10-10 18:54:32 +00002638FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2639 CXXRecordDecl *RD) {
2640 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002641
Richard Smithb2f0f052016-10-10 18:54:32 +00002642 FunctionDecl *OperatorDelete = nullptr;
2643 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2644 return nullptr;
2645 if (OperatorDelete)
2646 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002647
Richard Smithb2f0f052016-10-10 18:54:32 +00002648 // If there's no class-specific operator delete, look up the global
2649 // non-array delete.
2650 return FindUsualDeallocationFunction(
2651 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2652 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002653}
2654
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002655bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2656 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002657 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002658 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002659 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002660 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002661
John McCall27b18f82009-11-17 02:14:36 +00002662 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002663 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002664
Chandler Carruthb6f99172010-06-28 00:30:51 +00002665 Found.suppressDiagnostics();
2666
Richard Smithb2f0f052016-10-10 18:54:32 +00002667 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002668
Richard Smithb2f0f052016-10-10 18:54:32 +00002669 // C++17 [expr.delete]p10:
2670 // If the deallocation functions have class scope, the one without a
2671 // parameter of type std::size_t is selected.
2672 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2673 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2674 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002675
Richard Smithb2f0f052016-10-10 18:54:32 +00002676 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002677 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002678 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002679
Richard Smithb2f0f052016-10-10 18:54:32 +00002680 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002681 if (Operator->isDeleted()) {
2682 if (Diagnose) {
2683 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002684 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002685 }
2686 return true;
2687 }
2688
Richard Smith921bd202012-02-26 09:11:52 +00002689 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002690 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002691 return true;
2692
John McCall66a87592010-08-04 00:31:26 +00002693 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002694 }
John McCall66a87592010-08-04 00:31:26 +00002695
Richard Smithb2f0f052016-10-10 18:54:32 +00002696 // We found multiple suitable operators; complain about the ambiguity.
2697 // FIXME: The standard doesn't say to do this; it appears that the intent
2698 // is that this should never happen.
2699 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002700 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002701 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2702 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002703 for (auto &Match : Matches)
2704 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002705 }
John McCall66a87592010-08-04 00:31:26 +00002706 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002707 }
2708
2709 // We did find operator delete/operator delete[] declarations, but
2710 // none of them were suitable.
2711 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002712 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002713 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2714 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002715
Richard Smithb2f0f052016-10-10 18:54:32 +00002716 for (NamedDecl *D : Found)
2717 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002718 diag::note_member_declared_here) << Name;
2719 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002720 return true;
2721 }
2722
Craig Topperc3ec1492014-05-26 06:22:03 +00002723 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002724 return false;
2725}
2726
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002727namespace {
2728/// \brief Checks whether delete-expression, and new-expression used for
2729/// initializing deletee have the same array form.
2730class MismatchingNewDeleteDetector {
2731public:
2732 enum MismatchResult {
2733 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2734 NoMismatch,
2735 /// Indicates that variable is initialized with mismatching form of \a new.
2736 VarInitMismatches,
2737 /// Indicates that member is initialized with mismatching form of \a new.
2738 MemberInitMismatches,
2739 /// Indicates that 1 or more constructors' definitions could not been
2740 /// analyzed, and they will be checked again at the end of translation unit.
2741 AnalyzeLater
2742 };
2743
2744 /// \param EndOfTU True, if this is the final analysis at the end of
2745 /// translation unit. False, if this is the initial analysis at the point
2746 /// delete-expression was encountered.
2747 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002748 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002749 HasUndefinedConstructors(false) {}
2750
2751 /// \brief Checks whether pointee of a delete-expression is initialized with
2752 /// matching form of new-expression.
2753 ///
2754 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2755 /// point where delete-expression is encountered, then a warning will be
2756 /// issued immediately. If return value is \c AnalyzeLater at the point where
2757 /// delete-expression is seen, then member will be analyzed at the end of
2758 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2759 /// couldn't be analyzed. If at least one constructor initializes the member
2760 /// with matching type of new, the return value is \c NoMismatch.
2761 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2762 /// \brief Analyzes a class member.
2763 /// \param Field Class member to analyze.
2764 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2765 /// for deleting the \p Field.
2766 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002767 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002768 /// List of mismatching new-expressions used for initialization of the pointee
2769 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2770 /// Indicates whether delete-expression was in array form.
2771 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002772
2773private:
2774 const bool EndOfTU;
2775 /// \brief Indicates that there is at least one constructor without body.
2776 bool HasUndefinedConstructors;
2777 /// \brief Returns \c CXXNewExpr from given initialization expression.
2778 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002779 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002780 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2781 /// \brief Returns whether member is initialized with mismatching form of
2782 /// \c new either by the member initializer or in-class initialization.
2783 ///
2784 /// If bodies of all constructors are not visible at the end of translation
2785 /// unit or at least one constructor initializes member with the matching
2786 /// form of \c new, mismatch cannot be proven, and this function will return
2787 /// \c NoMismatch.
2788 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2789 /// \brief Returns whether variable is initialized with mismatching form of
2790 /// \c new.
2791 ///
2792 /// If variable is initialized with matching form of \c new or variable is not
2793 /// initialized with a \c new expression, this function will return true.
2794 /// If variable is initialized with mismatching form of \c new, returns false.
2795 /// \param D Variable to analyze.
2796 bool hasMatchingVarInit(const DeclRefExpr *D);
2797 /// \brief Checks whether the constructor initializes pointee with mismatching
2798 /// form of \c new.
2799 ///
2800 /// Returns true, if member is initialized with matching form of \c new in
2801 /// member initializer list. Returns false, if member is initialized with the
2802 /// matching form of \c new in this constructor's initializer or given
2803 /// constructor isn't defined at the point where delete-expression is seen, or
2804 /// member isn't initialized by the constructor.
2805 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2806 /// \brief Checks whether member is initialized with matching form of
2807 /// \c new in member initializer list.
2808 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2809 /// Checks whether member is initialized with mismatching form of \c new by
2810 /// in-class initializer.
2811 MismatchResult analyzeInClassInitializer();
2812};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002813}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002814
2815MismatchingNewDeleteDetector::MismatchResult
2816MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2817 NewExprs.clear();
2818 assert(DE && "Expected delete-expression");
2819 IsArrayForm = DE->isArrayForm();
2820 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2821 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2822 return analyzeMemberExpr(ME);
2823 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2824 if (!hasMatchingVarInit(D))
2825 return VarInitMismatches;
2826 }
2827 return NoMismatch;
2828}
2829
2830const CXXNewExpr *
2831MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2832 assert(E != nullptr && "Expected a valid initializer expression");
2833 E = E->IgnoreParenImpCasts();
2834 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2835 if (ILE->getNumInits() == 1)
2836 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2837 }
2838
2839 return dyn_cast_or_null<const CXXNewExpr>(E);
2840}
2841
2842bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2843 const CXXCtorInitializer *CI) {
2844 const CXXNewExpr *NE = nullptr;
2845 if (Field == CI->getMember() &&
2846 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2847 if (NE->isArray() == IsArrayForm)
2848 return true;
2849 else
2850 NewExprs.push_back(NE);
2851 }
2852 return false;
2853}
2854
2855bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2856 const CXXConstructorDecl *CD) {
2857 if (CD->isImplicit())
2858 return false;
2859 const FunctionDecl *Definition = CD;
2860 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2861 HasUndefinedConstructors = true;
2862 return EndOfTU;
2863 }
2864 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2865 if (hasMatchingNewInCtorInit(CI))
2866 return true;
2867 }
2868 return false;
2869}
2870
2871MismatchingNewDeleteDetector::MismatchResult
2872MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2873 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00002874 const Expr *InitExpr = Field->getInClassInitializer();
2875 if (!InitExpr)
2876 return EndOfTU ? NoMismatch : AnalyzeLater;
2877 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002878 if (NE->isArray() != IsArrayForm) {
2879 NewExprs.push_back(NE);
2880 return MemberInitMismatches;
2881 }
2882 }
2883 return NoMismatch;
2884}
2885
2886MismatchingNewDeleteDetector::MismatchResult
2887MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2888 bool DeleteWasArrayForm) {
2889 assert(Field != nullptr && "Analysis requires a valid class member.");
2890 this->Field = Field;
2891 IsArrayForm = DeleteWasArrayForm;
2892 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2893 for (const auto *CD : RD->ctors()) {
2894 if (hasMatchingNewInCtor(CD))
2895 return NoMismatch;
2896 }
2897 if (HasUndefinedConstructors)
2898 return EndOfTU ? NoMismatch : AnalyzeLater;
2899 if (!NewExprs.empty())
2900 return MemberInitMismatches;
2901 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
2902 : NoMismatch;
2903}
2904
2905MismatchingNewDeleteDetector::MismatchResult
2906MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
2907 assert(ME != nullptr && "Expected a member expression");
2908 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2909 return analyzeField(F, IsArrayForm);
2910 return NoMismatch;
2911}
2912
2913bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
2914 const CXXNewExpr *NE = nullptr;
2915 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
2916 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
2917 NE->isArray() != IsArrayForm) {
2918 NewExprs.push_back(NE);
2919 }
2920 }
2921 return NewExprs.empty();
2922}
2923
2924static void
2925DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
2926 const MismatchingNewDeleteDetector &Detector) {
2927 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
2928 FixItHint H;
2929 if (!Detector.IsArrayForm)
2930 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
2931 else {
2932 SourceLocation RSquare = Lexer::findLocationAfterToken(
2933 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
2934 SemaRef.getLangOpts(), true);
2935 if (RSquare.isValid())
2936 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
2937 }
2938 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
2939 << Detector.IsArrayForm << H;
2940
2941 for (const auto *NE : Detector.NewExprs)
2942 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
2943 << Detector.IsArrayForm;
2944}
2945
2946void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
2947 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
2948 return;
2949 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
2950 switch (Detector.analyzeDeleteExpr(DE)) {
2951 case MismatchingNewDeleteDetector::VarInitMismatches:
2952 case MismatchingNewDeleteDetector::MemberInitMismatches: {
2953 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
2954 break;
2955 }
2956 case MismatchingNewDeleteDetector::AnalyzeLater: {
2957 DeleteExprs[Detector.Field].push_back(
2958 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
2959 break;
2960 }
2961 case MismatchingNewDeleteDetector::NoMismatch:
2962 break;
2963 }
2964}
2965
2966void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
2967 bool DeleteWasArrayForm) {
2968 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
2969 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
2970 case MismatchingNewDeleteDetector::VarInitMismatches:
2971 llvm_unreachable("This analysis should have been done for class members.");
2972 case MismatchingNewDeleteDetector::AnalyzeLater:
2973 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
2974 "translation unit.");
2975 case MismatchingNewDeleteDetector::MemberInitMismatches:
2976 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
2977 break;
2978 case MismatchingNewDeleteDetector::NoMismatch:
2979 break;
2980 }
2981}
2982
Sebastian Redlbd150f42008-11-21 19:14:01 +00002983/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2984/// @code ::delete ptr; @endcode
2985/// or
2986/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00002987ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00002988Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00002989 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002990 // C++ [expr.delete]p1:
2991 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00002992 // non-explicit conversion function to a pointer type. The result has type
2993 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002994 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00002995 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2996
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002997 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00002998 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002999 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003000 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003001
John Wiegley01296292011-04-08 18:41:53 +00003002 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003003 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003004 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003005 if (Ex.isInvalid())
3006 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003007
John Wiegley01296292011-04-08 18:41:53 +00003008 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003009
Richard Smithccc11812013-05-21 19:05:48 +00003010 class DeleteConverter : public ContextualImplicitConverter {
3011 public:
3012 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003013
Craig Toppere14c0f82014-03-12 04:55:44 +00003014 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003015 // FIXME: If we have an operator T* and an operator void*, we must pick
3016 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003017 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003018 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003019 return true;
3020 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003021 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003022
Richard Smithccc11812013-05-21 19:05:48 +00003023 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003024 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003025 return S.Diag(Loc, diag::err_delete_operand) << T;
3026 }
3027
3028 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003029 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003030 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3031 }
3032
3033 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003034 QualType T,
3035 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003036 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3037 }
3038
3039 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003040 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003041 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3042 << ConvTy;
3043 }
3044
3045 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003046 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003047 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3048 }
3049
3050 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003051 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003052 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3053 << ConvTy;
3054 }
3055
3056 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003057 QualType T,
3058 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003059 llvm_unreachable("conversion functions are permitted");
3060 }
3061 } Converter;
3062
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003063 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003064 if (Ex.isInvalid())
3065 return ExprError();
3066 Type = Ex.get()->getType();
3067 if (!Converter.match(Type))
3068 // FIXME: PerformContextualImplicitConversion should return ExprError
3069 // itself in this case.
3070 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003071
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003072 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003073 QualType PointeeElem = Context.getBaseElementType(Pointee);
3074
3075 if (unsigned AddressSpace = Pointee.getAddressSpace())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003076 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003077 diag::err_address_space_qualified_delete)
3078 << Pointee.getUnqualifiedType() << AddressSpace;
3079
Craig Topperc3ec1492014-05-26 06:22:03 +00003080 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003081 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003082 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003083 // effectively bans deletion of "void*". However, most compilers support
3084 // this, so we treat it as a warning unless we're in a SFINAE context.
3085 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003086 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003087 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003088 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003089 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003090 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003091 // FIXME: This can result in errors if the definition was imported from a
3092 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003093 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003094 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003095 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3096 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3097 }
3098 }
3099
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003100 if (Pointee->isArrayType() && !ArrayForm) {
3101 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003102 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003103 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003104 ArrayForm = true;
3105 }
3106
Anders Carlssona471db02009-08-16 20:29:29 +00003107 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3108 ArrayForm ? OO_Array_Delete : OO_Delete);
3109
Eli Friedmanae4280f2011-07-26 22:25:31 +00003110 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003111 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003112 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3113 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003114 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003115
John McCall284c48f2011-01-27 09:37:56 +00003116 // If we're allocating an array of records, check whether the
3117 // usual operator delete[] has a size_t parameter.
3118 if (ArrayForm) {
3119 // If the user specifically asked to use the global allocator,
3120 // we'll need to do the lookup into the class.
3121 if (UseGlobal)
3122 UsualArrayDeleteWantsSize =
3123 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3124
3125 // Otherwise, the usual operator delete[] should be the
3126 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003127 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003128 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003129 UsualDeallocFnInfo(*this,
3130 DeclAccessPair::make(OperatorDelete, AS_public))
3131 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003132 }
3133
Richard Smitheec915d62012-02-18 04:13:32 +00003134 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003135 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003136 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003137 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003138 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3139 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003140 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003141
Nico Weber5a9259c2016-01-15 21:45:31 +00003142 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3143 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3144 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3145 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003147
Richard Smithb2f0f052016-10-10 18:54:32 +00003148 if (!OperatorDelete) {
3149 bool IsComplete = isCompleteType(StartLoc, Pointee);
3150 bool CanProvideSize =
3151 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3152 Pointee.isDestructedType());
3153 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3154
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003155 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003156 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3157 Overaligned, DeleteName);
3158 }
Mike Stump11289f42009-09-09 15:08:12 +00003159
Eli Friedmanfa0df832012-02-02 03:46:19 +00003160 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003161
Douglas Gregorfa778132011-02-01 15:50:11 +00003162 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003163 if (PointeeRD) {
3164 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00003165 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00003166 PDiag(diag::err_access_dtor) << PointeeElem);
3167 }
3168 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003169 }
3170
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003171 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003172 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3173 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003174 AnalyzeDeleteExprMismatch(Result);
3175 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003176}
3177
Nico Weber5a9259c2016-01-15 21:45:31 +00003178void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3179 bool IsDelete, bool CallCanBeVirtual,
3180 bool WarnOnNonAbstractTypes,
3181 SourceLocation DtorLoc) {
3182 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
3183 return;
3184
3185 // C++ [expr.delete]p3:
3186 // In the first alternative (delete object), if the static type of the
3187 // object to be deleted is different from its dynamic type, the static
3188 // type shall be a base class of the dynamic type of the object to be
3189 // deleted and the static type shall have a virtual destructor or the
3190 // behavior is undefined.
3191 //
3192 const CXXRecordDecl *PointeeRD = dtor->getParent();
3193 // Note: a final class cannot be derived from, no issue there
3194 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3195 return;
3196
3197 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3198 if (PointeeRD->isAbstract()) {
3199 // If the class is abstract, we warn by default, because we're
3200 // sure the code has undefined behavior.
3201 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3202 << ClassType;
3203 } else if (WarnOnNonAbstractTypes) {
3204 // Otherwise, if this is not an array delete, it's a bit suspect,
3205 // but not necessarily wrong.
3206 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3207 << ClassType;
3208 }
3209 if (!IsDelete) {
3210 std::string TypeStr;
3211 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3212 Diag(DtorLoc, diag::note_delete_non_virtual)
3213 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3214 }
3215}
3216
Richard Smith03a4aa32016-06-23 19:02:52 +00003217Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3218 SourceLocation StmtLoc,
3219 ConditionKind CK) {
3220 ExprResult E =
3221 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3222 if (E.isInvalid())
3223 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003224 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3225 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003226}
3227
Douglas Gregor633caca2009-11-23 23:44:04 +00003228/// \brief Check the use of the given variable as a C++ condition in an if,
3229/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003230ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003231 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003232 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003233 if (ConditionVar->isInvalidDecl())
3234 return ExprError();
3235
Douglas Gregor633caca2009-11-23 23:44:04 +00003236 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003237
Douglas Gregor633caca2009-11-23 23:44:04 +00003238 // C++ [stmt.select]p2:
3239 // The declarator shall not specify a function or an array.
3240 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003241 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003242 diag::err_invalid_use_of_function_type)
3243 << ConditionVar->getSourceRange());
3244 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003245 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003246 diag::err_invalid_use_of_array_type)
3247 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003248
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003249 ExprResult Condition = DeclRefExpr::Create(
3250 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3251 /*enclosing*/ false, ConditionVar->getLocation(),
3252 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003253
Eli Friedmanfa0df832012-02-02 03:46:19 +00003254 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003255
Richard Smith03a4aa32016-06-23 19:02:52 +00003256 switch (CK) {
3257 case ConditionKind::Boolean:
3258 return CheckBooleanCondition(StmtLoc, Condition.get());
3259
Richard Smithb130fe72016-06-23 19:16:49 +00003260 case ConditionKind::ConstexprIf:
3261 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3262
Richard Smith03a4aa32016-06-23 19:02:52 +00003263 case ConditionKind::Switch:
3264 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003265 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003266
Richard Smith03a4aa32016-06-23 19:02:52 +00003267 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003268}
3269
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003270/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003271ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003272 // C++ 6.4p4:
3273 // The value of a condition that is an initialized declaration in a statement
3274 // other than a switch statement is the value of the declared variable
3275 // implicitly converted to type bool. If that conversion is ill-formed, the
3276 // program is ill-formed.
3277 // The value of a condition that is an expression is the value of the
3278 // expression, implicitly converted to bool.
3279 //
Richard Smithb130fe72016-06-23 19:16:49 +00003280 // FIXME: Return this value to the caller so they don't need to recompute it.
3281 llvm::APSInt Value(/*BitWidth*/1);
3282 return (IsConstexpr && !CondExpr->isValueDependent())
3283 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3284 CCEK_ConstexprIf)
3285 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003286}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003287
3288/// Helper function to determine whether this is the (deprecated) C++
3289/// conversion from a string literal to a pointer to non-const char or
3290/// non-const wchar_t (for narrow and wide string literals,
3291/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003292bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003293Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3294 // Look inside the implicit cast, if it exists.
3295 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3296 From = Cast->getSubExpr();
3297
3298 // A string literal (2.13.4) that is not a wide string literal can
3299 // be converted to an rvalue of type "pointer to char"; a wide
3300 // string literal can be converted to an rvalue of type "pointer
3301 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003302 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003303 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003304 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003305 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003306 // This conversion is considered only when there is an
3307 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003308 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3309 switch (StrLit->getKind()) {
3310 case StringLiteral::UTF8:
3311 case StringLiteral::UTF16:
3312 case StringLiteral::UTF32:
3313 // We don't allow UTF literals to be implicitly converted
3314 break;
3315 case StringLiteral::Ascii:
3316 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3317 ToPointeeType->getKind() == BuiltinType::Char_S);
3318 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003319 return Context.typesAreCompatible(Context.getWideCharType(),
3320 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003321 }
3322 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003323 }
3324
3325 return false;
3326}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003327
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003328static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003329 SourceLocation CastLoc,
3330 QualType Ty,
3331 CastKind Kind,
3332 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003333 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003334 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003335 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003336 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003337 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003338 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003339 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003340 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341
Richard Smith72d74052013-07-20 19:41:36 +00003342 if (S.RequireNonAbstractType(CastLoc, Ty,
3343 diag::err_allocation_of_abstract_type))
3344 return ExprError();
3345
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003346 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003347 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003348
Richard Smith5179eb72016-06-28 19:03:57 +00003349 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3350 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003351 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003352 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003353
Richard Smithf8adcdc2014-07-17 05:12:35 +00003354 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003355 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003356 ConstructorArgs, HadMultipleCandidates,
3357 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3358 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003359 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003360 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003361
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003362 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003363 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364
John McCalle3027922010-08-25 11:45:40 +00003365 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003366 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003367
Richard Smithd3f2d322015-02-24 21:16:19 +00003368 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003369 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003370 return ExprError();
3371
Douglas Gregora4253922010-04-16 22:17:36 +00003372 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003373 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3374 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003375 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003376 if (Result.isInvalid())
3377 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003378 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003379 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3380 CK_UserDefinedConversion, Result.get(),
3381 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003382
Douglas Gregor668443e2011-01-20 00:18:04 +00003383 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003384 }
3385 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003386}
Douglas Gregora4253922010-04-16 22:17:36 +00003387
Douglas Gregor5fb53972009-01-14 15:45:31 +00003388/// PerformImplicitConversion - Perform an implicit conversion of the
3389/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003390/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003391/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003392/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003393ExprResult
3394Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003395 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003396 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003397 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003398 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003399 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003400 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3401 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003402 if (Res.isInvalid())
3403 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003404 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003405 break;
John Wiegley01296292011-04-08 18:41:53 +00003406 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003407
Anders Carlsson110b07b2009-09-15 06:28:28 +00003408 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003409
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003410 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003411 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003412 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003413 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003414 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003415 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003416
Anders Carlsson110b07b2009-09-15 06:28:28 +00003417 // If the user-defined conversion is specified by a conversion function,
3418 // the initial standard conversion sequence converts the source type to
3419 // the implicit object parameter of the conversion function.
3420 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003421 } else {
3422 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003423 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003424 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003425 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003426 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003427 // initial standard conversion sequence converts the source type to
3428 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003429 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003431 }
Richard Smith72d74052013-07-20 19:41:36 +00003432 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003433 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003434 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003435 PerformImplicitConversion(From, BeforeToType,
3436 ICS.UserDefined.Before, AA_Converting,
3437 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003438 if (Res.isInvalid())
3439 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003440 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003441 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003442
3443 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003444 = BuildCXXCastArgument(*this,
3445 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003446 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003447 CastKind, cast<CXXMethodDecl>(FD),
3448 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003449 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003450 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003451
3452 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003453 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003454
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003455 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003456
Richard Smith507840d2011-11-29 22:48:16 +00003457 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3458 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003459 }
John McCall0d1da222010-01-12 00:44:57 +00003460
3461 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003462 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003463 PDiag(diag::err_typecheck_ambiguous_condition)
3464 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003465 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003466
Douglas Gregor39c16d42008-10-24 04:54:22 +00003467 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003468 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003469
3470 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003471 bool Diagnosed =
3472 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3473 From->getType(), From, Action);
3474 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003475 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003476 }
3477
3478 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003479 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003480}
3481
Richard Smith507840d2011-11-29 22:48:16 +00003482/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003483/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003484/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003485/// expression. Flavor is the context in which we're performing this
3486/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003487ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003488Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003489 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003490 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003491 CheckedConversionKind CCK) {
3492 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003493
Mike Stump87c57ac2009-05-16 07:39:55 +00003494 // Overall FIXME: we are recomputing too many types here and doing far too
3495 // much extra work. What this means is that we need to keep track of more
3496 // information that is computed when we try the implicit conversion initially,
3497 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003498 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003499
Douglas Gregor2fe98832008-11-03 19:09:14 +00003500 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003501 // FIXME: When can ToType be a reference type?
3502 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003503 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003504 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003505 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003506 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003507 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003508 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003509 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003510 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3511 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003512 ConstructorArgs, /*HadMultipleCandidates*/ false,
3513 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3514 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003515 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003516 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003517 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3518 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003519 From, /*HadMultipleCandidates*/ false,
3520 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3521 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003522 }
3523
Douglas Gregor980fb162010-04-29 18:24:40 +00003524 // Resolve overloaded function references.
3525 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3526 DeclAccessPair Found;
3527 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3528 true, Found);
3529 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003530 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003531
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003532 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003533 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003534
Douglas Gregor980fb162010-04-29 18:24:40 +00003535 From = FixOverloadedFunctionReference(From, Found, Fn);
3536 FromType = From->getType();
3537 }
3538
Richard Smitha23ab512013-05-23 00:30:41 +00003539 // If we're converting to an atomic type, first convert to the corresponding
3540 // non-atomic type.
3541 QualType ToAtomicType;
3542 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3543 ToAtomicType = ToType;
3544 ToType = ToAtomic->getValueType();
3545 }
3546
George Burgess IV8d141e02015-12-14 22:00:49 +00003547 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003548 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003549 switch (SCS.First) {
3550 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003551 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3552 FromType = FromAtomic->getValueType().getUnqualifiedType();
3553 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3554 From, /*BasePath=*/nullptr, VK_RValue);
3555 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003556 break;
3557
Eli Friedman946b7b52012-01-24 22:51:26 +00003558 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003559 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003560 ExprResult FromRes = DefaultLvalueConversion(From);
3561 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003562 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003563 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003564 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003565 }
John McCall34376a62010-12-04 03:47:34 +00003566
Douglas Gregor39c16d42008-10-24 04:54:22 +00003567 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003568 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003569 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003570 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003571 break;
3572
3573 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003574 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003575 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003576 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003577 break;
3578
3579 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003580 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003581 }
3582
Richard Smith507840d2011-11-29 22:48:16 +00003583 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003584 switch (SCS.Second) {
3585 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003586 // C++ [except.spec]p5:
3587 // [For] assignment to and initialization of pointers to functions,
3588 // pointers to member functions, and references to functions: the
3589 // target entity shall allow at least the exceptions allowed by the
3590 // source value in the assignment or initialization.
3591 switch (Action) {
3592 case AA_Assigning:
3593 case AA_Initializing:
3594 // Note, function argument passing and returning are initialization.
3595 case AA_Passing:
3596 case AA_Returning:
3597 case AA_Sending:
3598 case AA_Passing_CFAudited:
3599 if (CheckExceptionSpecCompatibility(From, ToType))
3600 return ExprError();
3601 break;
3602
3603 case AA_Casting:
3604 case AA_Converting:
3605 // Casts and implicit conversions are not initialization, so are not
3606 // checked for exception specification mismatches.
3607 break;
3608 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003609 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003610 break;
3611
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00003612 case ICK_NoReturn_Adjustment:
3613 // If both sides are functions (or pointers/references to them), there could
3614 // be incompatible exception declarations.
3615 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003616 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003617
Simon Pilgrim75c26882016-09-30 14:25:09 +00003618 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003619 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00003620 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003621
Douglas Gregor39c16d42008-10-24 04:54:22 +00003622 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003623 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003624 if (ToType->isBooleanType()) {
3625 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3626 SCS.Second == ICK_Integral_Promotion &&
3627 "only enums with fixed underlying type can promote to bool");
3628 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003629 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003630 } else {
3631 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003632 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003633 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003634 break;
3635
3636 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003637 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003638 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003639 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003640 break;
3641
3642 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003643 case ICK_Complex_Conversion: {
3644 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3645 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3646 CastKind CK;
3647 if (FromEl->isRealFloatingType()) {
3648 if (ToEl->isRealFloatingType())
3649 CK = CK_FloatingComplexCast;
3650 else
3651 CK = CK_FloatingComplexToIntegralComplex;
3652 } else if (ToEl->isRealFloatingType()) {
3653 CK = CK_IntegralComplexToFloatingComplex;
3654 } else {
3655 CK = CK_IntegralComplexCast;
3656 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003657 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003658 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003659 break;
John McCall8cb679e2010-11-15 09:13:47 +00003660 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003661
Douglas Gregor39c16d42008-10-24 04:54:22 +00003662 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003663 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003664 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003665 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003666 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00003667 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003668 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003669 break;
3670
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003671 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003672 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003673 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003674 break;
3675
John McCall31168b02011-06-15 23:02:42 +00003676 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003677 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003678 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003679 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00003680 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003681 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003682 diag::ext_typecheck_convert_incompatible_pointer)
3683 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003684 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003685 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003686 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003687 diag::ext_typecheck_convert_incompatible_pointer)
3688 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003689 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00003690
Douglas Gregor33823722011-06-11 01:09:30 +00003691 if (From->getType()->isObjCObjectPointerType() &&
3692 ToType->isObjCObjectPointerType())
3693 EmitRelatedResultTypeNote(From);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003694 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00003695 else if (getLangOpts().ObjCAutoRefCount &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00003696 !CheckObjCARCUnavailableWeakConversion(ToType,
Fariborz Jahanianf2913402011-07-08 17:41:42 +00003697 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00003698 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003699 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003700 diag::err_arc_weak_unavailable_assign);
3701 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003702 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00003703 diag::err_arc_convesion_of_weak_unavailable)
3704 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00003705 << From->getSourceRange();
3706 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003707
John McCall8cb679e2010-11-15 09:13:47 +00003708 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003709 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003710 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003711 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00003712
3713 // Make sure we extend blocks if necessary.
3714 // FIXME: doing this here is really ugly.
3715 if (Kind == CK_BlockPointerToObjCPointerCast) {
3716 ExprResult E = From;
3717 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003718 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00003719 }
Fariborz Jahanian374089e2013-07-31 17:12:26 +00003720 if (getLangOpts().ObjCAutoRefCount)
3721 CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00003722 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003723 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003724 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003725 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003726
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003727 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00003728 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003729 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003730 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003731 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00003732 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003733 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00003734
3735 // We may not have been able to figure out what this member pointer resolved
3736 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00003737 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003738 (void)isCompleteType(From->getExprLoc(), From->getType());
3739 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00003740 }
David Majnemerd96b9972014-08-08 00:10:39 +00003741
Richard Smith507840d2011-11-29 22:48:16 +00003742 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003743 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003744 break;
3745 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003746
Abramo Bagnara7ccce982011-04-07 09:26:19 +00003747 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003748 // Perform half-to-boolean conversion via float.
3749 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003750 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003751 FromType = Context.FloatTy;
3752 }
3753
Richard Smith507840d2011-11-29 22:48:16 +00003754 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003755 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003756 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003757 break;
3758
Douglas Gregor88d292c2010-05-13 16:44:06 +00003759 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00003760 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003762 ToType.getNonReferenceType(),
3763 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003764 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003765 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00003766 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003767 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00003768
Richard Smith507840d2011-11-29 22:48:16 +00003769 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3770 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003771 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003772 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00003773 }
3774
Douglas Gregor46188682010-05-18 22:42:18 +00003775 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003776 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003777 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003778 break;
3779
George Burgess IVdf1ed002016-01-13 01:52:39 +00003780 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00003781 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00003782 Expr *Elem = prepareVectorSplat(ToType, From).get();
3783 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3784 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003785 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00003786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003787
Douglas Gregor46188682010-05-18 22:42:18 +00003788 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00003789 // Case 1. x -> _Complex y
3790 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3791 QualType ElType = ToComplex->getElementType();
3792 bool isFloatingComplex = ElType->isRealFloatingType();
3793
3794 // x -> y
3795 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3796 // do nothing
3797 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003798 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003799 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00003800 } else {
3801 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003802 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003803 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00003804 }
3805 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00003806 From = ImpCastExprToType(From, ToType,
3807 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003808 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00003809
3810 // Case 2. _Complex x -> y
3811 } else {
3812 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3813 assert(FromComplex);
3814
3815 QualType ElType = FromComplex->getElementType();
3816 bool isFloatingComplex = ElType->isRealFloatingType();
3817
3818 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00003819 From = ImpCastExprToType(From, ElType,
3820 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00003821 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003822 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003823
3824 // x -> y
3825 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3826 // do nothing
3827 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003828 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003829 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003830 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003831 } else {
3832 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003833 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003834 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003835 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003836 }
3837 }
Douglas Gregor46188682010-05-18 22:42:18 +00003838 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00003839
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00003840 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003841 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003842 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00003843 break;
3844 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003845
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003846 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003847 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003848 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00003849 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3850 if (FromRes.isInvalid())
3851 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003852 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003853 assert ((ConvTy == Sema::Compatible) &&
3854 "Improper transparent union conversion");
3855 (void)ConvTy;
3856 break;
3857 }
3858
Guy Benyei259f9f42013-02-07 16:05:33 +00003859 case ICK_Zero_Event_Conversion:
3860 From = ImpCastExprToType(From, ToType,
3861 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003862 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00003863 break;
3864
Douglas Gregor46188682010-05-18 22:42:18 +00003865 case ICK_Lvalue_To_Rvalue:
3866 case ICK_Array_To_Pointer:
3867 case ICK_Function_To_Pointer:
3868 case ICK_Qualification:
3869 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00003870 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00003871 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003872 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003873 }
3874
3875 switch (SCS.Third) {
3876 case ICK_Identity:
3877 // Nothing to do.
3878 break;
3879
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003880 case ICK_Qualification: {
3881 // The qualification keeps the category of the inner expression, unless the
3882 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00003883 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003884 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00003885 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003886 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00003887
Douglas Gregore981bb02011-03-14 16:13:32 +00003888 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003889 !getLangOpts().WritableStrings) {
3890 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3891 ? diag::ext_deprecated_string_literal_conversion
3892 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00003893 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003894 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00003895
Douglas Gregor39c16d42008-10-24 04:54:22 +00003896 break;
Richard Smitha23ab512013-05-23 00:30:41 +00003897 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003898
Douglas Gregor39c16d42008-10-24 04:54:22 +00003899 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003900 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003901 }
3902
Douglas Gregor298f43d2012-04-12 20:42:30 +00003903 // If this conversion sequence involved a scalar -> atomic conversion, perform
3904 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00003905 if (!ToAtomicType.isNull()) {
3906 assert(Context.hasSameType(
3907 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3908 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003909 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00003910 }
3911
George Burgess IV8d141e02015-12-14 22:00:49 +00003912 // If this conversion sequence succeeded and involved implicitly converting a
3913 // _Nullable type to a _Nonnull one, complain.
3914 if (CCK == CCK_ImplicitConversion)
3915 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
3916 From->getLocStart());
3917
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003918 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003919}
3920
Chandler Carruth8e172c62011-05-01 06:51:22 +00003921/// \brief Check the completeness of a type in a unary type trait.
3922///
3923/// If the particular type trait requires a complete type, tries to complete
3924/// it. If completing the type fails, a diagnostic is emitted and false
3925/// returned. If completing the type succeeds or no completion was required,
3926/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00003927static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00003928 SourceLocation Loc,
3929 QualType ArgTy) {
3930 // C++0x [meta.unary.prop]p3:
3931 // For all of the class templates X declared in this Clause, instantiating
3932 // that template with a template argument that is a class template
3933 // specialization may result in the implicit instantiation of the template
3934 // argument if and only if the semantics of X require that the argument
3935 // must be a complete type.
3936 // We apply this rule to all the type trait expressions used to implement
3937 // these class templates. We also try to follow any GCC documented behavior
3938 // in these expressions to ensure portability of standard libraries.
3939 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00003940 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00003941 // is_complete_type somewhat obviously cannot require a complete type.
3942 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003943 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003944
3945 // These traits are modeled on the type predicates in C++0x
3946 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3947 // requiring a complete type, as whether or not they return true cannot be
3948 // impacted by the completeness of the type.
3949 case UTT_IsVoid:
3950 case UTT_IsIntegral:
3951 case UTT_IsFloatingPoint:
3952 case UTT_IsArray:
3953 case UTT_IsPointer:
3954 case UTT_IsLvalueReference:
3955 case UTT_IsRvalueReference:
3956 case UTT_IsMemberFunctionPointer:
3957 case UTT_IsMemberObjectPointer:
3958 case UTT_IsEnum:
3959 case UTT_IsUnion:
3960 case UTT_IsClass:
3961 case UTT_IsFunction:
3962 case UTT_IsReference:
3963 case UTT_IsArithmetic:
3964 case UTT_IsFundamental:
3965 case UTT_IsObject:
3966 case UTT_IsScalar:
3967 case UTT_IsCompound:
3968 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003969 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003970
3971 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
3972 // which requires some of its traits to have the complete type. However,
3973 // the completeness of the type cannot impact these traits' semantics, and
3974 // so they don't require it. This matches the comments on these traits in
3975 // Table 49.
3976 case UTT_IsConst:
3977 case UTT_IsVolatile:
3978 case UTT_IsSigned:
3979 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00003980
3981 // This type trait always returns false, checking the type is moot.
3982 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00003983 return true;
3984
David Majnemer213bea32015-11-16 06:58:51 +00003985 // C++14 [meta.unary.prop]:
3986 // If T is a non-union class type, T shall be a complete type.
3987 case UTT_IsEmpty:
3988 case UTT_IsPolymorphic:
3989 case UTT_IsAbstract:
3990 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
3991 if (!RD->isUnion())
3992 return !S.RequireCompleteType(
3993 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
3994 return true;
3995
3996 // C++14 [meta.unary.prop]:
3997 // If T is a class type, T shall be a complete type.
3998 case UTT_IsFinal:
3999 case UTT_IsSealed:
4000 if (ArgTy->getAsCXXRecordDecl())
4001 return !S.RequireCompleteType(
4002 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4003 return true;
4004
4005 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
4006 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004007 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004008 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004009 case UTT_IsStandardLayout:
4010 case UTT_IsPOD:
4011 case UTT_IsLiteral:
David Majnemer213bea32015-11-16 06:58:51 +00004012
Alp Toker73287bf2014-01-20 00:24:09 +00004013 case UTT_IsDestructible:
4014 case UTT_IsNothrowDestructible:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004015 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004016
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004017 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00004018 // [meta.unary.prop] despite not being named the same. They are specified
4019 // by both GCC and the Embarcadero C++ compiler, and require the complete
4020 // type due to the overarching C++0x type predicates being implemented
4021 // requiring the complete type.
4022 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004023 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004024 case UTT_HasNothrowConstructor:
4025 case UTT_HasNothrowCopy:
4026 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004027 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004028 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004029 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004030 case UTT_HasTrivialCopy:
4031 case UTT_HasTrivialDestructor:
4032 case UTT_HasVirtualDestructor:
4033 // Arrays of unknown bound are expressly allowed.
4034 QualType ElTy = ArgTy;
4035 if (ArgTy->isIncompleteArrayType())
4036 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
4037
4038 // The void type is expressly allowed.
4039 if (ElTy->isVoidType())
4040 return true;
4041
4042 return !S.RequireCompleteType(
4043 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004044 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004045}
4046
Joao Matosc9523d42013-03-27 01:34:16 +00004047static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4048 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004049 bool (CXXRecordDecl::*HasTrivial)() const,
4050 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004051 bool (CXXMethodDecl::*IsDesiredOp)() const)
4052{
4053 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4054 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4055 return true;
4056
4057 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4058 DeclarationNameInfo NameInfo(Name, KeyLoc);
4059 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4060 if (Self.LookupQualifiedName(Res, RD)) {
4061 bool FoundOperator = false;
4062 Res.suppressDiagnostics();
4063 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4064 Op != OpEnd; ++Op) {
4065 if (isa<FunctionTemplateDecl>(*Op))
4066 continue;
4067
4068 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4069 if((Operator->*IsDesiredOp)()) {
4070 FoundOperator = true;
4071 const FunctionProtoType *CPT =
4072 Operator->getType()->getAs<FunctionProtoType>();
4073 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Alp Toker73287bf2014-01-20 00:24:09 +00004074 if (!CPT || !CPT->isNothrow(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004075 return false;
4076 }
4077 }
4078 return FoundOperator;
4079 }
4080 return false;
4081}
4082
Alp Toker95e7ff22014-01-01 05:57:51 +00004083static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004084 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004085 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004086
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004087 ASTContext &C = Self.Context;
4088 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004089 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004090 // Type trait expressions corresponding to the primary type category
4091 // predicates in C++0x [meta.unary.cat].
4092 case UTT_IsVoid:
4093 return T->isVoidType();
4094 case UTT_IsIntegral:
4095 return T->isIntegralType(C);
4096 case UTT_IsFloatingPoint:
4097 return T->isFloatingType();
4098 case UTT_IsArray:
4099 return T->isArrayType();
4100 case UTT_IsPointer:
4101 return T->isPointerType();
4102 case UTT_IsLvalueReference:
4103 return T->isLValueReferenceType();
4104 case UTT_IsRvalueReference:
4105 return T->isRValueReferenceType();
4106 case UTT_IsMemberFunctionPointer:
4107 return T->isMemberFunctionPointerType();
4108 case UTT_IsMemberObjectPointer:
4109 return T->isMemberDataPointerType();
4110 case UTT_IsEnum:
4111 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004112 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004113 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004114 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004115 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004116 case UTT_IsFunction:
4117 return T->isFunctionType();
4118
4119 // Type trait expressions which correspond to the convenient composition
4120 // predicates in C++0x [meta.unary.comp].
4121 case UTT_IsReference:
4122 return T->isReferenceType();
4123 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004124 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004125 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004126 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004127 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004128 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004129 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004130 // Note: semantic analysis depends on Objective-C lifetime types to be
4131 // considered scalar types. However, such types do not actually behave
4132 // like scalar types at run time (since they may require retain/release
4133 // operations), so we report them as non-scalar.
4134 if (T->isObjCLifetimeType()) {
4135 switch (T.getObjCLifetime()) {
4136 case Qualifiers::OCL_None:
4137 case Qualifiers::OCL_ExplicitNone:
4138 return true;
4139
4140 case Qualifiers::OCL_Strong:
4141 case Qualifiers::OCL_Weak:
4142 case Qualifiers::OCL_Autoreleasing:
4143 return false;
4144 }
4145 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004146
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004147 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004148 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004149 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004150 case UTT_IsMemberPointer:
4151 return T->isMemberPointerType();
4152
4153 // Type trait expressions which correspond to the type property predicates
4154 // in C++0x [meta.unary.prop].
4155 case UTT_IsConst:
4156 return T.isConstQualified();
4157 case UTT_IsVolatile:
4158 return T.isVolatileQualified();
4159 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004160 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004161 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004162 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004163 case UTT_IsStandardLayout:
4164 return T->isStandardLayoutType();
4165 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004166 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004167 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004168 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004169 case UTT_IsEmpty:
4170 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4171 return !RD->isUnion() && RD->isEmpty();
4172 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004173 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004174 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004175 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004176 return false;
4177 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004178 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004179 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004180 return false;
David Majnemer213bea32015-11-16 06:58:51 +00004181 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4182 // even then only when it is used with the 'interface struct ...' syntax
4183 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004184 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004185 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004186 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004187 case UTT_IsSealed:
4188 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004189 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004190 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004191 case UTT_IsSigned:
4192 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004193 case UTT_IsUnsigned:
4194 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004195
4196 // Type trait expressions which query classes regarding their construction,
4197 // destruction, and copying. Rather than being based directly on the
4198 // related type predicates in the standard, they are specified by both
4199 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4200 // specifications.
4201 //
4202 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4203 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004204 //
4205 // Note that these builtins do not behave as documented in g++: if a class
4206 // has both a trivial and a non-trivial special member of a particular kind,
4207 // they return false! For now, we emulate this behavior.
4208 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4209 // does not correctly compute triviality in the presence of multiple special
4210 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004211 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004212 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4213 // If __is_pod (type) is true then the trait is true, else if type is
4214 // a cv class or union type (or array thereof) with a trivial default
4215 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004216 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004217 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004218 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4219 return RD->hasTrivialDefaultConstructor() &&
4220 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004221 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004222 case UTT_HasTrivialMoveConstructor:
4223 // This trait is implemented by MSVC 2012 and needed to parse the
4224 // standard library headers. Specifically this is used as the logic
4225 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004226 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004227 return true;
4228 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4229 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4230 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004231 case UTT_HasTrivialCopy:
4232 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4233 // If __is_pod (type) is true or type is a reference type then
4234 // the trait is true, else if type is a cv class or union type
4235 // with a trivial copy constructor ([class.copy]) then the trait
4236 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004237 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004238 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004239 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4240 return RD->hasTrivialCopyConstructor() &&
4241 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004242 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004243 case UTT_HasTrivialMoveAssign:
4244 // This trait is implemented by MSVC 2012 and needed to parse the
4245 // standard library headers. Specifically it is used as the logic
4246 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004247 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004248 return true;
4249 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4250 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4251 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004252 case UTT_HasTrivialAssign:
4253 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4254 // If type is const qualified or is a reference type then the
4255 // trait is false. Otherwise if __is_pod (type) is true then the
4256 // trait is true, else if type is a cv class or union type with
4257 // a trivial copy assignment ([class.copy]) then the trait is
4258 // true, else it is false.
4259 // Note: the const and reference restrictions are interesting,
4260 // given that const and reference members don't prevent a class
4261 // from having a trivial copy assignment operator (but do cause
4262 // errors if the copy assignment operator is actually used, q.v.
4263 // [class.copy]p12).
4264
Richard Smith92f241f2012-12-08 02:53:02 +00004265 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004266 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004267 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004268 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004269 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4270 return RD->hasTrivialCopyAssignment() &&
4271 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004272 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004273 case UTT_IsDestructible:
4274 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004275 // C++14 [meta.unary.prop]:
4276 // For reference types, is_destructible<T>::value is true.
4277 if (T->isReferenceType())
4278 return true;
4279
4280 // Objective-C++ ARC: autorelease types don't require destruction.
4281 if (T->isObjCLifetimeType() &&
4282 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4283 return true;
4284
4285 // C++14 [meta.unary.prop]:
4286 // For incomplete types and function types, is_destructible<T>::value is
4287 // false.
4288 if (T->isIncompleteType() || T->isFunctionType())
4289 return false;
4290
4291 // C++14 [meta.unary.prop]:
4292 // For object types and given U equal to remove_all_extents_t<T>, if the
4293 // expression std::declval<U&>().~U() is well-formed when treated as an
4294 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4295 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4296 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4297 if (!Destructor)
4298 return false;
4299 // C++14 [dcl.fct.def.delete]p2:
4300 // A program that refers to a deleted function implicitly or
4301 // explicitly, other than to declare it, is ill-formed.
4302 if (Destructor->isDeleted())
4303 return false;
4304 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4305 return false;
4306 if (UTT == UTT_IsNothrowDestructible) {
4307 const FunctionProtoType *CPT =
4308 Destructor->getType()->getAs<FunctionProtoType>();
4309 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4310 if (!CPT || !CPT->isNothrow(C))
4311 return false;
4312 }
4313 }
4314 return true;
4315
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004316 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004317 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004318 // If __is_pod (type) is true or type is a reference type
4319 // then the trait is true, else if type is a cv class or union
4320 // type (or array thereof) with a trivial destructor
4321 // ([class.dtor]) then the trait is true, else it is
4322 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004323 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004324 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004325
John McCall31168b02011-06-15 23:02:42 +00004326 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004327 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004328 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4329 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004330
Richard Smith92f241f2012-12-08 02:53:02 +00004331 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4332 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004333 return false;
4334 // TODO: Propagate nothrowness for implicitly declared special members.
4335 case UTT_HasNothrowAssign:
4336 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4337 // If type is const qualified or is a reference type then the
4338 // trait is false. Otherwise if __has_trivial_assign (type)
4339 // is true then the trait is true, else if type is a cv class
4340 // or union type with copy assignment operators that are known
4341 // not to throw an exception then the trait is true, else it is
4342 // false.
4343 if (C.getBaseElementType(T).isConstQualified())
4344 return false;
4345 if (T->isReferenceType())
4346 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004347 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004348 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004349
Joao Matosc9523d42013-03-27 01:34:16 +00004350 if (const RecordType *RT = T->getAs<RecordType>())
4351 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4352 &CXXRecordDecl::hasTrivialCopyAssignment,
4353 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4354 &CXXMethodDecl::isCopyAssignmentOperator);
4355 return false;
4356 case UTT_HasNothrowMoveAssign:
4357 // This trait is implemented by MSVC 2012 and needed to parse the
4358 // standard library headers. Specifically this is used as the logic
4359 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004360 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004361 return true;
4362
4363 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4364 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4365 &CXXRecordDecl::hasTrivialMoveAssignment,
4366 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4367 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004368 return false;
4369 case UTT_HasNothrowCopy:
4370 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4371 // If __has_trivial_copy (type) is true then the trait is true, else
4372 // if type is a cv class or union type with copy constructors that are
4373 // known not to throw an exception then the trait is true, else it is
4374 // false.
John McCall31168b02011-06-15 23:02:42 +00004375 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004376 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004377 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4378 if (RD->hasTrivialCopyConstructor() &&
4379 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004380 return true;
4381
4382 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004383 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004384 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004385 // A template constructor is never a copy constructor.
4386 // FIXME: However, it may actually be selected at the actual overload
4387 // resolution point.
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004388 if (isa<FunctionTemplateDecl>(ND))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004389 continue;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004390 const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004391 if (Constructor->isCopyConstructor(FoundTQs)) {
4392 FoundConstructor = true;
4393 const FunctionProtoType *CPT
4394 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004395 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4396 if (!CPT)
4397 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004398 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004399 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004400 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004401 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004402 }
4403 }
4404
Richard Smith938f40b2011-06-11 17:19:42 +00004405 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004406 }
4407 return false;
4408 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004409 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004410 // If __has_trivial_constructor (type) is true then the trait is
4411 // true, else if type is a cv class or union type (or array
4412 // thereof) with a default constructor that is known not to
4413 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004414 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004415 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004416 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4417 if (RD->hasTrivialDefaultConstructor() &&
4418 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004419 return true;
4420
Alp Tokerb4bca412014-01-20 00:23:47 +00004421 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004422 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004423 // FIXME: In C++0x, a constructor template can be a default constructor.
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004424 if (isa<FunctionTemplateDecl>(ND))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004425 continue;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004426 const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND);
Sebastian Redlc15c3262010-09-13 22:02:47 +00004427 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004428 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004429 const FunctionProtoType *CPT
4430 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004431 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4432 if (!CPT)
4433 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004434 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004435 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004436 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004437 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004438 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004439 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004440 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004441 }
4442 return false;
4443 case UTT_HasVirtualDestructor:
4444 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4445 // If type is a class type with a virtual destructor ([class.dtor])
4446 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004447 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004448 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004449 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004450 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004451
4452 // These type trait expressions are modeled on the specifications for the
4453 // Embarcadero C++0x type trait functions:
4454 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4455 case UTT_IsCompleteType:
4456 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4457 // Returns True if and only if T is a complete type at the point of the
4458 // function call.
4459 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004460 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004461}
Sebastian Redl5822f082009-02-07 20:10:22 +00004462
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004463/// \brief Determine whether T has a non-trivial Objective-C lifetime in
4464/// ARC mode.
4465static bool hasNontrivialObjCLifetime(QualType T) {
4466 switch (T.getObjCLifetime()) {
4467 case Qualifiers::OCL_ExplicitNone:
4468 return false;
4469
4470 case Qualifiers::OCL_Strong:
4471 case Qualifiers::OCL_Weak:
4472 case Qualifiers::OCL_Autoreleasing:
4473 return true;
4474
4475 case Qualifiers::OCL_None:
4476 return T->isObjCLifetimeType();
4477 }
4478
4479 llvm_unreachable("Unknown ObjC lifetime qualifier");
4480}
4481
Alp Tokercbb90342013-12-13 20:49:58 +00004482static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4483 QualType RhsT, SourceLocation KeyLoc);
4484
Douglas Gregor29c42f22012-02-24 07:38:34 +00004485static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4486 ArrayRef<TypeSourceInfo *> Args,
4487 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004488 if (Kind <= UTT_Last)
4489 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4490
Alp Tokercbb90342013-12-13 20:49:58 +00004491 if (Kind <= BTT_Last)
4492 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4493 Args[1]->getType(), RParenLoc);
4494
Douglas Gregor29c42f22012-02-24 07:38:34 +00004495 switch (Kind) {
Alp Toker73287bf2014-01-20 00:24:09 +00004496 case clang::TT_IsConstructible:
4497 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004498 case clang::TT_IsTriviallyConstructible: {
4499 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004500 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004501 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004502 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004503 // definition for is_constructible, as defined below, is known to call
4504 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004505 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004506 // The predicate condition for a template specialization
4507 // is_constructible<T, Args...> shall be satisfied if and only if the
4508 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004509 // variable t:
4510 //
4511 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004512 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004513
4514 // Precondition: T and all types in the parameter pack Args shall be
4515 // complete types, (possibly cv-qualified) void, or arrays of
4516 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004517 for (const auto *TSI : Args) {
4518 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004519 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004520 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004521
Simon Pilgrim75c26882016-09-30 14:25:09 +00004522 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004523 diag::err_incomplete_type_used_in_type_trait_expr))
4524 return false;
4525 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004526
David Majnemer9658ecc2015-11-13 05:32:43 +00004527 // Make sure the first argument is not incomplete nor a function type.
4528 QualType T = Args[0]->getType();
4529 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004530 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004531
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004532 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004533 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004534 if (RD && RD->isAbstract())
4535 return false;
4536
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004537 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4538 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004539 ArgExprs.reserve(Args.size() - 1);
4540 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004541 QualType ArgTy = Args[I]->getType();
4542 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4543 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004544 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004545 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4546 ArgTy.getNonLValueExprType(S.Context),
4547 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004548 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004549 for (Expr &E : OpaqueArgExprs)
4550 ArgExprs.push_back(&E);
4551
Simon Pilgrim75c26882016-09-30 14:25:09 +00004552 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004553 // trap at translation unit scope.
4554 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
4555 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4556 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4557 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4558 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4559 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004560 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004561 if (Init.Failed())
4562 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004563
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004564 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004565 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4566 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004567
Alp Toker73287bf2014-01-20 00:24:09 +00004568 if (Kind == clang::TT_IsConstructible)
4569 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004570
Alp Toker73287bf2014-01-20 00:24:09 +00004571 if (Kind == clang::TT_IsNothrowConstructible)
4572 return S.canThrow(Result.get()) == CT_Cannot;
4573
4574 if (Kind == clang::TT_IsTriviallyConstructible) {
4575 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4576 // lifetime, this is a non-trivial construction.
4577 if (S.getLangOpts().ObjCAutoRefCount &&
David Majnemer9658ecc2015-11-13 05:32:43 +00004578 hasNontrivialObjCLifetime(T.getNonReferenceType()))
Alp Toker73287bf2014-01-20 00:24:09 +00004579 return false;
4580
4581 // The initialization succeeded; now make sure there are no non-trivial
4582 // calls.
4583 return !Result.get()->hasNonTrivialCall(S.Context);
4584 }
4585
4586 llvm_unreachable("unhandled type trait");
4587 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004588 }
Alp Tokercbb90342013-12-13 20:49:58 +00004589 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004590 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004591
Douglas Gregor29c42f22012-02-24 07:38:34 +00004592 return false;
4593}
4594
Simon Pilgrim75c26882016-09-30 14:25:09 +00004595ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4596 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004597 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004598 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004599
Alp Toker95e7ff22014-01-01 05:57:51 +00004600 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4601 *this, Kind, KWLoc, Args[0]->getType()))
4602 return ExprError();
4603
Douglas Gregor29c42f22012-02-24 07:38:34 +00004604 bool Dependent = false;
4605 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4606 if (Args[I]->getType()->isDependentType()) {
4607 Dependent = true;
4608 break;
4609 }
4610 }
Alp Tokercbb90342013-12-13 20:49:58 +00004611
4612 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004613 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004614 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4615
4616 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4617 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004618}
4619
Alp Toker88f64e62013-12-13 21:19:30 +00004620ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4621 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004622 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004623 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004624 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00004625
Douglas Gregor29c42f22012-02-24 07:38:34 +00004626 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4627 TypeSourceInfo *TInfo;
4628 QualType T = GetTypeFromParser(Args[I], &TInfo);
4629 if (!TInfo)
4630 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004631
4632 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004633 }
Alp Tokercbb90342013-12-13 20:49:58 +00004634
Douglas Gregor29c42f22012-02-24 07:38:34 +00004635 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4636}
4637
Alp Tokercbb90342013-12-13 20:49:58 +00004638static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4639 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004640 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4641 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004642
4643 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004644 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004645 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004646 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004647 // Base and Derived are not unions and name the same class type without
4648 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004649
John McCall388ef532011-01-28 22:02:36 +00004650 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4651 if (!lhsRecord) return false;
4652
4653 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4654 if (!rhsRecord) return false;
4655
4656 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4657 == (lhsRecord == rhsRecord));
4658
4659 if (lhsRecord == rhsRecord)
4660 return !lhsRecord->getDecl()->isUnion();
4661
4662 // C++0x [meta.rel]p2:
4663 // If Base and Derived are class types and are different types
4664 // (ignoring possible cv-qualifiers) then Derived shall be a
4665 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004666 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00004667 diag::err_incomplete_type_used_in_type_trait_expr))
4668 return false;
4669
4670 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4671 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4672 }
John Wiegley65497cc2011-04-27 23:09:49 +00004673 case BTT_IsSame:
4674 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00004675 case BTT_TypeCompatible:
4676 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4677 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00004678 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00004679 case BTT_IsConvertibleTo: {
4680 // C++0x [meta.rel]p4:
4681 // Given the following function prototype:
4682 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004683 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00004684 // typename add_rvalue_reference<T>::type create();
4685 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004686 // the predicate condition for a template specialization
4687 // is_convertible<From, To> shall be satisfied if and only if
4688 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00004689 // well-formed, including any implicit conversions to the return
4690 // type of the function:
4691 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004692 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00004693 // return create<From>();
4694 // }
4695 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004696 // Access checking is performed as if in a context unrelated to To and
4697 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00004698 // of the return-statement (including conversions to the return type)
4699 // is considered.
4700 //
4701 // We model the initialization as a copy-initialization of a temporary
4702 // of the appropriate type, which for this expression is identical to the
4703 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004704
4705 // Functions aren't allowed to return function or array types.
4706 if (RhsT->isFunctionType() || RhsT->isArrayType())
4707 return false;
4708
4709 // A return statement in a void function must have void type.
4710 if (RhsT->isVoidType())
4711 return LhsT->isVoidType();
4712
4713 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00004714 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004715 return false;
4716
4717 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00004718 if (LhsT->isObjectType() || LhsT->isFunctionType())
4719 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004720
4721 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00004722 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00004723 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00004724 Expr::getValueKindForType(LhsT));
4725 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004726 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00004727 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004728
4729 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00004730 // trap at translation unit scope.
4731 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00004732 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4733 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004734 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004735 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00004736 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00004737
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004738 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00004739 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4740 }
Alp Toker73287bf2014-01-20 00:24:09 +00004741
David Majnemerb3d96882016-05-23 17:21:55 +00004742 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00004743 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00004744 case BTT_IsTriviallyAssignable: {
4745 // C++11 [meta.unary.prop]p3:
4746 // is_trivially_assignable is defined as:
4747 // is_assignable<T, U>::value is true and the assignment, as defined by
4748 // is_assignable, is known to call no operation that is not trivial
4749 //
4750 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004751 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00004752 // treated as an unevaluated operand (Clause 5).
4753 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004754 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00004755 // void, or arrays of unknown bound.
4756 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004757 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004758 diag::err_incomplete_type_used_in_type_trait_expr))
4759 return false;
4760 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004761 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004762 diag::err_incomplete_type_used_in_type_trait_expr))
4763 return false;
4764
4765 // cv void is never assignable.
4766 if (LhsT->isVoidType() || RhsT->isVoidType())
4767 return false;
4768
Simon Pilgrim75c26882016-09-30 14:25:09 +00004769 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00004770 // declval<U>().
4771 if (LhsT->isObjectType() || LhsT->isFunctionType())
4772 LhsT = Self.Context.getRValueReferenceType(LhsT);
4773 if (RhsT->isObjectType() || RhsT->isFunctionType())
4774 RhsT = Self.Context.getRValueReferenceType(RhsT);
4775 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4776 Expr::getValueKindForType(LhsT));
4777 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4778 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004779
4780 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00004781 // trap at translation unit scope.
4782 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
4783 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4784 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004785 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4786 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004787 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4788 return false;
4789
David Majnemerb3d96882016-05-23 17:21:55 +00004790 if (BTT == BTT_IsAssignable)
4791 return true;
4792
Alp Toker73287bf2014-01-20 00:24:09 +00004793 if (BTT == BTT_IsNothrowAssignable)
4794 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004795
Alp Toker73287bf2014-01-20 00:24:09 +00004796 if (BTT == BTT_IsTriviallyAssignable) {
4797 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4798 // lifetime, this is a non-trivial assignment.
4799 if (Self.getLangOpts().ObjCAutoRefCount &&
4800 hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
4801 return false;
4802
4803 return !Result.get()->hasNonTrivialCall(Self.Context);
4804 }
4805
4806 llvm_unreachable("unhandled type trait");
4807 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00004808 }
Alp Tokercbb90342013-12-13 20:49:58 +00004809 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004810 }
4811 llvm_unreachable("Unknown type trait or not implemented");
4812}
4813
John Wiegley6242b6a2011-04-28 00:16:57 +00004814ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4815 SourceLocation KWLoc,
4816 ParsedType Ty,
4817 Expr* DimExpr,
4818 SourceLocation RParen) {
4819 TypeSourceInfo *TSInfo;
4820 QualType T = GetTypeFromParser(Ty, &TSInfo);
4821 if (!TSInfo)
4822 TSInfo = Context.getTrivialTypeSourceInfo(T);
4823
4824 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4825}
4826
4827static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4828 QualType T, Expr *DimExpr,
4829 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004830 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00004831
4832 switch(ATT) {
4833 case ATT_ArrayRank:
4834 if (T->isArrayType()) {
4835 unsigned Dim = 0;
4836 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4837 ++Dim;
4838 T = AT->getElementType();
4839 }
4840 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00004841 }
John Wiegleyd3522222011-04-28 02:06:46 +00004842 return 0;
4843
John Wiegley6242b6a2011-04-28 00:16:57 +00004844 case ATT_ArrayExtent: {
4845 llvm::APSInt Value;
4846 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00004847 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00004848 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00004849 false).isInvalid())
4850 return 0;
4851 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00004852 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4853 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00004854 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00004855 }
Richard Smithf4c51d92012-02-04 09:53:13 +00004856 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00004857
4858 if (T->isArrayType()) {
4859 unsigned D = 0;
4860 bool Matched = false;
4861 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4862 if (Dim == D) {
4863 Matched = true;
4864 break;
4865 }
4866 ++D;
4867 T = AT->getElementType();
4868 }
4869
John Wiegleyd3522222011-04-28 02:06:46 +00004870 if (Matched && T->isArrayType()) {
4871 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4872 return CAT->getSize().getLimitedValue();
4873 }
John Wiegley6242b6a2011-04-28 00:16:57 +00004874 }
John Wiegleyd3522222011-04-28 02:06:46 +00004875 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00004876 }
4877 }
4878 llvm_unreachable("Unknown type trait or not implemented");
4879}
4880
4881ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4882 SourceLocation KWLoc,
4883 TypeSourceInfo *TSInfo,
4884 Expr* DimExpr,
4885 SourceLocation RParen) {
4886 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00004887
Chandler Carruthc5276e52011-05-01 08:48:21 +00004888 // FIXME: This should likely be tracked as an APInt to remove any host
4889 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004890 uint64_t Value = 0;
4891 if (!T->isDependentType())
4892 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4893
Chandler Carruthc5276e52011-05-01 08:48:21 +00004894 // While the specification for these traits from the Embarcadero C++
4895 // compiler's documentation says the return type is 'unsigned int', Clang
4896 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4897 // compiler, there is no difference. On several other platforms this is an
4898 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004899 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4900 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00004901}
4902
John Wiegleyf9f65842011-04-25 06:54:41 +00004903ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004904 SourceLocation KWLoc,
4905 Expr *Queried,
4906 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004907 // If error parsing the expression, ignore.
4908 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004909 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00004910
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004911 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004912
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004913 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00004914}
4915
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004916static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4917 switch (ET) {
4918 case ET_IsLValueExpr: return E->isLValue();
4919 case ET_IsRValueExpr: return E->isRValue();
4920 }
4921 llvm_unreachable("Expression trait not covered by switch");
4922}
4923
John Wiegleyf9f65842011-04-25 06:54:41 +00004924ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004925 SourceLocation KWLoc,
4926 Expr *Queried,
4927 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004928 if (Queried->isTypeDependent()) {
4929 // Delay type-checking for type-dependent expressions.
4930 } else if (Queried->getType()->isPlaceholderType()) {
4931 ExprResult PE = CheckPlaceholderExpr(Queried);
4932 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004933 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004934 }
4935
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004936 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00004937
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004938 return new (Context)
4939 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00004940}
4941
Richard Trieu82402a02011-09-15 21:56:47 +00004942QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004943 ExprValueKind &VK,
4944 SourceLocation Loc,
4945 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004946 assert(!LHS.get()->getType()->isPlaceholderType() &&
4947 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00004948 "placeholders should have been weeded out by now");
4949
4950 // The LHS undergoes lvalue conversions if this is ->*.
4951 if (isIndirect) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004952 LHS = DefaultLvalueConversion(LHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00004953 if (LHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004954 }
4955
4956 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004957 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00004958 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004959
Sebastian Redl5822f082009-02-07 20:10:22 +00004960 const char *OpSpelling = isIndirect ? "->*" : ".*";
4961 // C++ 5.5p2
4962 // The binary operator .* [p3: ->*] binds its second operand, which shall
4963 // be of type "pointer to member of T" (where T is a completely-defined
4964 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00004965 QualType RHSType = RHS.get()->getType();
4966 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004967 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00004968 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00004969 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00004970 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004971 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004972
Sebastian Redl5822f082009-02-07 20:10:22 +00004973 QualType Class(MemPtr->getClass(), 0);
4974
Douglas Gregord07ba342010-10-13 20:41:14 +00004975 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
4976 // member pointer points must be completely-defined. However, there is no
4977 // reason for this semantic distinction, and the rule is not enforced by
4978 // other compilers. Therefore, we do not check this property, as it is
4979 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00004980
Sebastian Redl5822f082009-02-07 20:10:22 +00004981 // C++ 5.5p2
4982 // [...] to its first operand, which shall be of class T or of a class of
4983 // which T is an unambiguous and accessible base class. [p3: a pointer to
4984 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00004985 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00004986 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004987 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
4988 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00004989 else {
4990 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00004991 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00004992 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00004993 return QualType();
4994 }
4995 }
4996
Richard Trieu82402a02011-09-15 21:56:47 +00004997 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00004998 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004999 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5000 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005001 return QualType();
5002 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005003
Richard Smith0f59cb32015-12-18 21:45:41 +00005004 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005005 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005006 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005007 return QualType();
5008 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005009
5010 CXXCastPath BasePath;
5011 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5012 SourceRange(LHS.get()->getLocStart(),
5013 RHS.get()->getLocEnd()),
5014 &BasePath))
5015 return QualType();
5016
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005017 // Cast LHS to type of use.
5018 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005019 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005020 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005021 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005022 }
5023
Richard Trieu82402a02011-09-15 21:56:47 +00005024 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005025 // Diagnose use of pointer-to-member type which when used as
5026 // the functional cast in a pointer-to-member expression.
5027 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5028 return QualType();
5029 }
John McCall7decc9e2010-11-18 06:31:45 +00005030
Sebastian Redl5822f082009-02-07 20:10:22 +00005031 // C++ 5.5p2
5032 // The result is an object or a function of the type specified by the
5033 // second operand.
5034 // The cv qualifiers are the union of those in the pointer and the left side,
5035 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005036 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005037 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005038
Douglas Gregor1d042092011-01-26 16:40:18 +00005039 // C++0x [expr.mptr.oper]p6:
5040 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041 // ill-formed if the second operand is a pointer to member function with
5042 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5043 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005044 // is a pointer to member function with ref-qualifier &&.
5045 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5046 switch (Proto->getRefQualifier()) {
5047 case RQ_None:
5048 // Do nothing
5049 break;
5050
5051 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005052 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005053 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005054 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005055 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005056
Douglas Gregor1d042092011-01-26 16:40:18 +00005057 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005058 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005059 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005060 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005061 break;
5062 }
5063 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005064
John McCall7decc9e2010-11-18 06:31:45 +00005065 // C++ [expr.mptr.oper]p6:
5066 // The result of a .* expression whose second operand is a pointer
5067 // to a data member is of the same value category as its
5068 // first operand. The result of a .* expression whose second
5069 // operand is a pointer to a member function is a prvalue. The
5070 // result of an ->* expression is an lvalue if its second operand
5071 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005072 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005073 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005074 return Context.BoundMemberTy;
5075 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005076 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005077 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005078 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005079 }
John McCall7decc9e2010-11-18 06:31:45 +00005080
Sebastian Redl5822f082009-02-07 20:10:22 +00005081 return Result;
5082}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005083
Richard Smith2414bca2016-04-25 19:30:37 +00005084/// \brief Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005085///
5086/// This is part of the parameter validation for the ? operator. If either
5087/// value operand is a class type, the two operands are attempted to be
5088/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005089/// It returns true if the program is ill-formed and has already been diagnosed
5090/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005091static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5092 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005093 bool &HaveConversion,
5094 QualType &ToType) {
5095 HaveConversion = false;
5096 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005097
5098 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005099 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005100 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005101 // The process for determining whether an operand expression E1 of type T1
5102 // can be converted to match an operand expression E2 of type T2 is defined
5103 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005104 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5105 // implicitly converted to type "lvalue reference to T2", subject to the
5106 // constraint that in the conversion the reference must bind directly to
5107 // an lvalue.
5108 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5109 // implicitly conveted to the type "rvalue reference to R2", subject to
5110 // the constraint that the reference must bind directly.
5111 if (To->isLValue() || To->isXValue()) {
5112 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5113 : Self.Context.getRValueReferenceType(ToType);
5114
Douglas Gregor838fcc32010-03-26 20:14:36 +00005115 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005116
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005117 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005118 if (InitSeq.isDirectReferenceBinding()) {
5119 ToType = T;
5120 HaveConversion = true;
5121 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005123
Douglas Gregor838fcc32010-03-26 20:14:36 +00005124 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005125 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005126 }
John McCall65eb8792010-02-25 01:37:24 +00005127
Sebastian Redl1a99f442009-04-16 17:51:27 +00005128 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5129 // -- if E1 and E2 have class type, and the underlying class types are
5130 // the same or one is a base class of the other:
5131 QualType FTy = From->getType();
5132 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005133 const RecordType *FRec = FTy->getAs<RecordType>();
5134 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005135 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005136 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5137 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5138 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005139 // E1 can be converted to match E2 if the class of T2 is the
5140 // same type as, or a base class of, the class of T1, and
5141 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005142 if (FRec == TRec || FDerivedFromT) {
5143 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005144 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005145 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005146 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005147 HaveConversion = true;
5148 return false;
5149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005150
Douglas Gregor838fcc32010-03-26 20:14:36 +00005151 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005152 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005153 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005154 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005155
Douglas Gregor838fcc32010-03-26 20:14:36 +00005156 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005157 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005158
Douglas Gregor838fcc32010-03-26 20:14:36 +00005159 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5160 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005161 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005162 // an rvalue).
5163 //
5164 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5165 // to the array-to-pointer or function-to-pointer conversions.
5166 if (!TTy->getAs<TagType>())
5167 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005168
Douglas Gregor838fcc32010-03-26 20:14:36 +00005169 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005170 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005171 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005172 ToType = TTy;
5173 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005174 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005175
Sebastian Redl1a99f442009-04-16 17:51:27 +00005176 return false;
5177}
5178
5179/// \brief Try to find a common type for two according to C++0x 5.16p5.
5180///
5181/// This is part of the parameter validation for the ? operator. If either
5182/// value operand is a class type, overload resolution is used to find a
5183/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005184static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005185 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005186 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005187 OverloadCandidateSet CandidateSet(QuestionLoc,
5188 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005189 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005190 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005191
5192 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005193 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005194 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005195 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00005196 ExprResult LHSRes =
5197 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
5198 Best->Conversions[0], Sema::AA_Converting);
5199 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005200 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005201 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005202
5203 ExprResult RHSRes =
5204 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
5205 Best->Conversions[1], Sema::AA_Converting);
5206 if (RHSRes.isInvalid())
5207 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005208 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005209 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005210 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005211 return false;
John Wiegley01296292011-04-08 18:41:53 +00005212 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005213
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005214 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005215
5216 // Emit a better diagnostic if one of the expressions is a null pointer
5217 // constant and the other is a pointer type. In this case, the user most
5218 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005219 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005220 return true;
5221
5222 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005223 << LHS.get()->getType() << RHS.get()->getType()
5224 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005225 return true;
5226
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005227 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005228 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005229 << LHS.get()->getType() << RHS.get()->getType()
5230 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005231 // FIXME: Print the possible common types by printing the return types of
5232 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005233 break;
5234
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005235 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005236 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005237 }
5238 return true;
5239}
5240
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005241/// \brief Perform an "extended" implicit conversion as returned by
5242/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005243static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005244 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005245 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005246 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005247 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005248 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005249 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005250 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005251 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005252
John Wiegley01296292011-04-08 18:41:53 +00005253 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005254 return false;
5255}
5256
Sebastian Redl1a99f442009-04-16 17:51:27 +00005257/// \brief Check the operands of ?: under C++ semantics.
5258///
5259/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5260/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005261QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5262 ExprResult &RHS, ExprValueKind &VK,
5263 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005264 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005265 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5266 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005267
Richard Smith45edb702012-08-07 22:06:48 +00005268 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005269 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00005270 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005271 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005272 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005273 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005274 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005275 }
5276
John McCall7decc9e2010-11-18 06:31:45 +00005277 // Assume r-value.
5278 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005279 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005280
Sebastian Redl1a99f442009-04-16 17:51:27 +00005281 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005282 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005283 return Context.DependentTy;
5284
Richard Smith45edb702012-08-07 22:06:48 +00005285 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005286 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005287 QualType LTy = LHS.get()->getType();
5288 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005289 bool LVoid = LTy->isVoidType();
5290 bool RVoid = RTy->isVoidType();
5291 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005292 // ... one of the following shall hold:
5293 // -- The second or the third operand (but not both) is a (possibly
5294 // parenthesized) throw-expression; the result is of the type
5295 // and value category of the other.
5296 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5297 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5298 if (LThrow != RThrow) {
5299 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5300 VK = NonThrow->getValueKind();
5301 // DR (no number yet): the result is a bit-field if the
5302 // non-throw-expression operand is a bit-field.
5303 OK = NonThrow->getObjectKind();
5304 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005305 }
5306
Sebastian Redl1a99f442009-04-16 17:51:27 +00005307 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005308 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005309 if (LVoid && RVoid)
5310 return Context.VoidTy;
5311
5312 // Neither holds, error.
5313 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5314 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005315 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005316 return QualType();
5317 }
5318
5319 // Neither is void.
5320
Richard Smithf2b084f2012-08-08 06:13:49 +00005321 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005322 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005323 // either has (cv) class type [...] an attempt is made to convert each of
5324 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005325 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005326 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005327 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005328 QualType L2RType, R2LType;
5329 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005330 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005331 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005332 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005333 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005334
Sebastian Redl1a99f442009-04-16 17:51:27 +00005335 // If both can be converted, [...] the program is ill-formed.
5336 if (HaveL2R && HaveR2L) {
5337 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005338 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005339 return QualType();
5340 }
5341
5342 // If exactly one conversion is possible, that conversion is applied to
5343 // the chosen operand and the converted operands are used in place of the
5344 // original operands for the remainder of this section.
5345 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005346 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005347 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005348 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005349 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005350 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005351 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005352 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005353 }
5354 }
5355
Richard Smithf2b084f2012-08-08 06:13:49 +00005356 // C++11 [expr.cond]p3
5357 // if both are glvalues of the same value category and the same type except
5358 // for cv-qualification, an attempt is made to convert each of those
5359 // operands to the type of the other.
5360 ExprValueKind LVK = LHS.get()->getValueKind();
5361 ExprValueKind RVK = RHS.get()->getValueKind();
5362 if (!Context.hasSameType(LTy, RTy) &&
5363 Context.hasSameUnqualifiedType(LTy, RTy) &&
5364 LVK == RVK && LVK != VK_RValue) {
5365 // Since the unqualified types are reference-related and we require the
5366 // result to be as if a reference bound directly, the only conversion
5367 // we can perform is to add cv-qualifiers.
5368 Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
5369 Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
5370 if (RCVR.isStrictSupersetOf(LCVR)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005371 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005372 LTy = LHS.get()->getType();
5373 }
5374 else if (LCVR.isStrictSupersetOf(RCVR)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005375 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005376 RTy = RHS.get()->getType();
5377 }
5378 }
5379
5380 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005381 // If the second and third operands are glvalues of the same value
5382 // category and have the same type, the result is of that type and
5383 // value category and it is a bit-field if the second or the third
5384 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005385 // We only extend this to bitfields, not to the crazy other kinds of
5386 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005387 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005388 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005389 LHS.get()->isOrdinaryOrBitFieldObject() &&
5390 RHS.get()->isOrdinaryOrBitFieldObject()) {
5391 VK = LHS.get()->getValueKind();
5392 if (LHS.get()->getObjectKind() == OK_BitField ||
5393 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005394 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00005395 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005396 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005397
Richard Smithf2b084f2012-08-08 06:13:49 +00005398 // C++11 [expr.cond]p5
5399 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005400 // do not have the same type, and either has (cv) class type, ...
5401 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5402 // ... overload resolution is used to determine the conversions (if any)
5403 // to be applied to the operands. If the overload resolution fails, the
5404 // program is ill-formed.
5405 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5406 return QualType();
5407 }
5408
Richard Smithf2b084f2012-08-08 06:13:49 +00005409 // C++11 [expr.cond]p6
5410 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005411 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005412 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5413 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005414 if (LHS.isInvalid() || RHS.isInvalid())
5415 return QualType();
5416 LTy = LHS.get()->getType();
5417 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005418
5419 // After those conversions, one of the following shall hold:
5420 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005421 // is of that type. If the operands have class type, the result
5422 // is a prvalue temporary of the result type, which is
5423 // copy-initialized from either the second operand or the third
5424 // operand depending on the value of the first operand.
5425 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5426 if (LTy->isRecordType()) {
5427 // The operands have class type. Make a temporary copy.
David Blaikie6154ef92012-09-10 22:05:41 +00005428 if (RequireNonAbstractType(QuestionLoc, LTy,
5429 diag::err_allocation_of_abstract_type))
5430 return QualType();
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005431 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005432
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005433 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5434 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005435 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005436 if (LHSCopy.isInvalid())
5437 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005438
5439 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5440 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005441 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005442 if (RHSCopy.isInvalid())
5443 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005444
John Wiegley01296292011-04-08 18:41:53 +00005445 LHS = LHSCopy;
5446 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005447 }
5448
Sebastian Redl1a99f442009-04-16 17:51:27 +00005449 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005450 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005451
Douglas Gregor46188682010-05-18 22:42:18 +00005452 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005453 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005454 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5455 /*AllowBothBool*/true,
5456 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005457
Sebastian Redl1a99f442009-04-16 17:51:27 +00005458 // -- The second and third operands have arithmetic or enumeration type;
5459 // the usual arithmetic conversions are performed to bring them to a
5460 // common type, and the result is of that type.
5461 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005462 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005463 if (LHS.isInvalid() || RHS.isInvalid())
5464 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005465 if (ResTy.isNull()) {
5466 Diag(QuestionLoc,
5467 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5468 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5469 return QualType();
5470 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005471
5472 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5473 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5474
5475 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005476 }
5477
5478 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005479 // type and the other is a null pointer constant, or both are null
5480 // pointer constants, at least one of which is non-integral; pointer
5481 // conversions and qualification conversions are performed to bring them
5482 // to their composite pointer type. The result is of the composite
5483 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005484 // -- The second and third operands have pointer to member type, or one has
5485 // pointer to member type and the other is a null pointer constant;
5486 // pointer to member conversions and qualification conversions are
5487 // performed to bring them to a common type, whose cv-qualification
5488 // shall match the cv-qualification of either the second or the third
5489 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005490 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005491 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Craig Topperc3ec1492014-05-26 06:22:03 +00005492 isSFINAEContext() ? nullptr
5493 : &NonStandardCompositeType);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005494 if (!Composite.isNull()) {
5495 if (NonStandardCompositeType)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005496 Diag(QuestionLoc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005497 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
5498 << LTy << RTy << Composite
John Wiegley01296292011-04-08 18:41:53 +00005499 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005500
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005501 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005503
Douglas Gregor697a3912010-04-01 22:47:07 +00005504 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005505 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5506 if (!Composite.isNull())
5507 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005508
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005509 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005510 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005511 return QualType();
5512
Sebastian Redl1a99f442009-04-16 17:51:27 +00005513 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005514 << LHS.get()->getType() << RHS.get()->getType()
5515 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005516 return QualType();
5517}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005518
5519/// \brief Find a merged pointer type and convert the two expressions to it.
5520///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005521/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smithf2b084f2012-08-08 06:13:49 +00005522/// and @p E2 according to C++11 5.9p2. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005523/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005524/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005525///
Douglas Gregor19175ff2010-04-16 23:20:25 +00005526/// \param Loc The location of the operator requiring these two expressions to
5527/// be converted to the composite pointer type.
5528///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005529/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
5530/// a non-standard (but still sane) composite type to which both expressions
5531/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
5532/// will be set true.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005533QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00005534 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005535 bool *NonStandardCompositeType) {
5536 if (NonStandardCompositeType)
5537 *NonStandardCompositeType = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005538
David Blaikiebbafb8a2012-03-11 07:00:24 +00005539 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005540 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005541
Richard Smithf2b084f2012-08-08 06:13:49 +00005542 // C++11 5.9p2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005543 // Pointer conversions and qualification conversions are performed on
5544 // pointer operands to bring them to their composite pointer type. If
5545 // one operand is a null pointer constant, the composite pointer type is
Richard Smithf2b084f2012-08-08 06:13:49 +00005546 // std::nullptr_t if the other operand is also a null pointer constant or,
5547 // if the other operand is a pointer, the type of the other operand.
5548 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
5549 !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
5550 if (T1->isNullPtrType() &&
5551 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005552 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
Richard Smithf2b084f2012-08-08 06:13:49 +00005553 return T1;
5554 }
5555 if (T2->isNullPtrType() &&
5556 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005557 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
Richard Smithf2b084f2012-08-08 06:13:49 +00005558 return T2;
5559 }
5560 return QualType();
5561 }
5562
Douglas Gregor56751b52009-09-25 04:25:58 +00005563 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005564 if (T2->isMemberPointerType())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005565 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005566 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005567 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005568 return T2;
5569 }
Douglas Gregor56751b52009-09-25 04:25:58 +00005570 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005571 if (T1->isMemberPointerType())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005572 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005573 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005574 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005575 return T1;
5576 }
Mike Stump11289f42009-09-09 15:08:12 +00005577
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005578 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00005579 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
5580 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005581 return QualType();
5582
5583 // Otherwise, of one of the operands has type "pointer to cv1 void," then
5584 // the other has type "pointer to cv2 T" and the composite pointer type is
5585 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
5586 // Otherwise, the composite pointer type is a pointer type similar to the
5587 // type of one of the operands, with a cv-qualification signature that is
5588 // the union of the cv-qualification signatures of the operand types.
5589 // In practice, the first part here is redundant; it's subsumed by the second.
5590 // What we do here is, we build the two possible composite types, and try the
5591 // conversions in both directions. If only one works, or if the two composite
5592 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00005593 // FIXME: extended qualifiers?
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005594 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redl658262f2009-11-16 21:03:45 +00005595 QualifierVector QualifierUnion;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005596 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redl658262f2009-11-16 21:03:45 +00005597 ContainingClassVector;
5598 ContainingClassVector MemberOfClass;
5599 QualType Composite1 = Context.getCanonicalType(T1),
5600 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005601 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005602 do {
5603 const PointerType *Ptr1, *Ptr2;
5604 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5605 (Ptr2 = Composite2->getAs<PointerType>())) {
5606 Composite1 = Ptr1->getPointeeType();
5607 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005608
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005609 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005610 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005611 if (NonStandardCompositeType &&
5612 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5613 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005614
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005615 QualifierUnion.push_back(
5616 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00005617 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005618 continue;
5619 }
Mike Stump11289f42009-09-09 15:08:12 +00005620
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005621 const MemberPointerType *MemPtr1, *MemPtr2;
5622 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5623 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5624 Composite1 = MemPtr1->getPointeeType();
5625 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005626
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005627 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005628 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005629 if (NonStandardCompositeType &&
5630 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5631 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005632
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005633 QualifierUnion.push_back(
5634 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5635 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5636 MemPtr2->getClass()));
5637 continue;
5638 }
Mike Stump11289f42009-09-09 15:08:12 +00005639
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005640 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00005641
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005642 // Cannot unwrap any more types.
5643 break;
5644 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00005645
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005646 if (NeedConstBefore && NonStandardCompositeType) {
5647 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005648 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005649 // requirements of C++ [conv.qual]p4 bullet 3.
5650 for (unsigned I = 0; I != NeedConstBefore; ++I) {
5651 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
5652 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
5653 *NonStandardCompositeType = true;
5654 }
5655 }
5656 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005657
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005658 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00005659 ContainingClassVector::reverse_iterator MOC
5660 = MemberOfClass.rbegin();
5661 for (QualifierVector::reverse_iterator
5662 I = QualifierUnion.rbegin(),
5663 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005664 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00005665 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005666 if (MOC->first && MOC->second) {
5667 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005668 Composite1 = Context.getMemberPointerType(
5669 Context.getQualifiedType(Composite1, Quals),
5670 MOC->first);
5671 Composite2 = Context.getMemberPointerType(
5672 Context.getQualifiedType(Composite2, Quals),
5673 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005674 } else {
5675 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005676 Composite1
5677 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5678 Composite2
5679 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005680 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005681 }
5682
Douglas Gregor19175ff2010-04-16 23:20:25 +00005683 // Try to convert to the first composite pointer type.
5684 InitializedEntity Entity1
5685 = InitializedEntity::InitializeTemporary(Composite1);
5686 InitializationKind Kind
5687 = InitializationKind::CreateCopy(Loc, SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005688 InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
5689 InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
Mike Stump11289f42009-09-09 15:08:12 +00005690
Douglas Gregor19175ff2010-04-16 23:20:25 +00005691 if (E1ToC1 && E2ToC1) {
5692 // Conversion to Composite1 is viable.
5693 if (!Context.hasSameType(Composite1, Composite2)) {
5694 // Composite2 is a different type from Composite1. Check whether
5695 // Composite2 is also viable.
5696 InitializedEntity Entity2
5697 = InitializedEntity::InitializeTemporary(Composite2);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005698 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
5699 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005700 if (E1ToC2 && E2ToC2) {
5701 // Both Composite1 and Composite2 are viable and are different;
5702 // this is an ambiguity.
5703 return QualType();
5704 }
5705 }
5706
5707 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00005708 ExprResult E1Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005709 = E1ToC1.Perform(*this, Entity1, Kind, E1);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005710 if (E1Result.isInvalid())
5711 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005712 E1 = E1Result.getAs<Expr>();
Douglas Gregor19175ff2010-04-16 23:20:25 +00005713
5714 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00005715 ExprResult E2Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005716 = E2ToC1.Perform(*this, Entity1, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005717 if (E2Result.isInvalid())
5718 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005719 E2 = E2Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005720
Douglas Gregor19175ff2010-04-16 23:20:25 +00005721 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005722 }
5723
Douglas Gregor19175ff2010-04-16 23:20:25 +00005724 // Check whether Composite2 is viable.
5725 InitializedEntity Entity2
5726 = InitializedEntity::InitializeTemporary(Composite2);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005727 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
5728 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005729 if (!E1ToC2 || !E2ToC2)
5730 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005731
Douglas Gregor19175ff2010-04-16 23:20:25 +00005732 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00005733 ExprResult E1Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005734 = E1ToC2.Perform(*this, Entity2, Kind, E1);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005735 if (E1Result.isInvalid())
5736 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005737 E1 = E1Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005738
Douglas Gregor19175ff2010-04-16 23:20:25 +00005739 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00005740 ExprResult E2Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005741 = E2ToC2.Perform(*this, Entity2, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005742 if (E2Result.isInvalid())
5743 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005744 E2 = E2Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005745
Douglas Gregor19175ff2010-04-16 23:20:25 +00005746 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005747}
Anders Carlsson85a307d2009-05-17 18:41:29 +00005748
John McCalldadc5752010-08-24 06:29:42 +00005749ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00005750 if (!E)
5751 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005752
John McCall31168b02011-06-15 23:02:42 +00005753 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
5754
5755 // If the result is a glvalue, we shouldn't bind it.
5756 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005757 return E;
Mike Stump11289f42009-09-09 15:08:12 +00005758
John McCall31168b02011-06-15 23:02:42 +00005759 // In ARC, calls that return a retainable type can return retained,
5760 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005761 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00005762 E->getType()->isObjCRetainableType()) {
5763
5764 bool ReturnsRetained;
5765
5766 // For actual calls, we compute this by examining the type of the
5767 // called value.
5768 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5769 Expr *Callee = Call->getCallee()->IgnoreParens();
5770 QualType T = Callee->getType();
5771
5772 if (T == Context.BoundMemberTy) {
5773 // Handle pointer-to-members.
5774 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5775 T = BinOp->getRHS()->getType();
5776 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5777 T = Mem->getMemberDecl()->getType();
5778 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005779
John McCall31168b02011-06-15 23:02:42 +00005780 if (const PointerType *Ptr = T->getAs<PointerType>())
5781 T = Ptr->getPointeeType();
5782 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
5783 T = Ptr->getPointeeType();
5784 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
5785 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00005786
John McCall31168b02011-06-15 23:02:42 +00005787 const FunctionType *FTy = T->getAs<FunctionType>();
5788 assert(FTy && "call to value not of function type?");
5789 ReturnsRetained = FTy->getExtInfo().getProducesResult();
5790
5791 // ActOnStmtExpr arranges things so that StmtExprs of retainable
5792 // type always produce a +1 object.
5793 } else if (isa<StmtExpr>(E)) {
5794 ReturnsRetained = true;
5795
Ted Kremeneke65b0862012-03-06 20:05:56 +00005796 // We hit this case with the lambda conversion-to-block optimization;
5797 // we don't want any extra casts here.
5798 } else if (isa<CastExpr>(E) &&
5799 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005800 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005801
John McCall31168b02011-06-15 23:02:42 +00005802 // For message sends and property references, we try to find an
5803 // actual method. FIXME: we should infer retention by selector in
5804 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00005805 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00005806 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005807 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
5808 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00005809 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
5810 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00005811 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
5812 D = ArrayLit->getArrayWithObjectsMethod();
5813 } else if (ObjCDictionaryLiteral *DictLit
5814 = dyn_cast<ObjCDictionaryLiteral>(E)) {
5815 D = DictLit->getDictWithObjectsMethod();
5816 }
John McCall31168b02011-06-15 23:02:42 +00005817
5818 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00005819
5820 // Don't do reclaims on performSelector calls; despite their
5821 // return type, the invoked method doesn't necessarily actually
5822 // return an object.
5823 if (!ReturnsRetained &&
5824 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005825 return E;
John McCall31168b02011-06-15 23:02:42 +00005826 }
5827
John McCall16de4d22011-11-14 19:53:16 +00005828 // Don't reclaim an object of Class type.
5829 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005830 return E;
John McCall16de4d22011-11-14 19:53:16 +00005831
Tim Shen4a05bb82016-06-21 20:29:17 +00005832 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00005833
John McCall2d637d22011-09-10 06:18:15 +00005834 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
5835 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005836 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
5837 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00005838 }
5839
David Blaikiebbafb8a2012-03-11 07:00:24 +00005840 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005841 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00005842
Peter Collingbournec331a1e2012-01-26 03:33:51 +00005843 // Search for the base element type (cf. ASTContext::getBaseElementType) with
5844 // a fast path for the common case that the type is directly a RecordType.
5845 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00005846 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00005847 while (!RT) {
5848 switch (T->getTypeClass()) {
5849 case Type::Record:
5850 RT = cast<RecordType>(T);
5851 break;
5852 case Type::ConstantArray:
5853 case Type::IncompleteArray:
5854 case Type::VariableArray:
5855 case Type::DependentSizedArray:
5856 T = cast<ArrayType>(T)->getElementType().getTypePtr();
5857 break;
5858 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005859 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00005860 }
5861 }
Mike Stump11289f42009-09-09 15:08:12 +00005862
Richard Smithfd555f62012-02-22 02:04:18 +00005863 // That should be enough to guarantee that this type is complete, if we're
5864 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00005865 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00005866 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005867 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00005868
5869 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00005870 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00005871
John McCall31168b02011-06-15 23:02:42 +00005872 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00005873 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00005874 CheckDestructorAccess(E->getExprLoc(), Destructor,
5875 PDiag(diag::err_access_dtor_temp)
5876 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00005877 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
5878 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00005879
Richard Smithfd555f62012-02-22 02:04:18 +00005880 // If destructor is trivial, we can avoid the extra copy.
5881 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005882 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00005883
John McCall28fc7092011-11-10 05:35:25 +00005884 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00005885 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00005886 }
Richard Smitheec915d62012-02-18 04:13:32 +00005887
5888 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00005889 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
5890
5891 if (IsDecltype)
5892 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
5893
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005894 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00005895}
5896
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005897ExprResult
John McCall5d413782010-12-06 08:20:24 +00005898Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005899 if (SubExpr.isInvalid())
5900 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005901
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005902 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005903}
5904
John McCall28fc7092011-11-10 05:35:25 +00005905Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00005906 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00005907
Eli Friedman3bda6b12012-02-02 23:15:15 +00005908 CleanupVarDeclMarking();
5909
John McCall28fc7092011-11-10 05:35:25 +00005910 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
5911 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00005912 assert(Cleanup.exprNeedsCleanups() ||
5913 ExprCleanupObjects.size() == FirstCleanup);
5914 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00005915 return SubExpr;
5916
Craig Topper5fc8fc22014-08-27 06:28:36 +00005917 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
5918 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00005919
Tim Shen4a05bb82016-06-21 20:29:17 +00005920 auto *E = ExprWithCleanups::Create(
5921 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00005922 DiscardCleanupsInEvaluationContext();
5923
5924 return E;
5925}
5926
John McCall5d413782010-12-06 08:20:24 +00005927Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00005928 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005929
Eli Friedman3bda6b12012-02-02 23:15:15 +00005930 CleanupVarDeclMarking();
5931
Tim Shen4a05bb82016-06-21 20:29:17 +00005932 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005933 return SubStmt;
5934
5935 // FIXME: In order to attach the temporaries, wrap the statement into
5936 // a StmtExpr; currently this is only used for asm statements.
5937 // This is hacky, either create a new CXXStmtWithTemporaries statement or
5938 // a new AsmStmtWithTemporaries.
Nico Webera2a0eb92012-12-29 20:03:39 +00005939 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005940 SourceLocation(),
5941 SourceLocation());
5942 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
5943 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00005944 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005945}
5946
Richard Smithfd555f62012-02-22 02:04:18 +00005947/// Process the expression contained within a decltype. For such expressions,
5948/// certain semantic checks on temporaries are delayed until this point, and
5949/// are omitted for the 'topmost' call in the decltype expression. If the
5950/// topmost call bound a temporary, strip that temporary off the expression.
5951ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005952 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00005953
5954 // C++11 [expr.call]p11:
5955 // If a function call is a prvalue of object type,
5956 // -- if the function call is either
5957 // -- the operand of a decltype-specifier, or
5958 // -- the right operand of a comma operator that is the operand of a
5959 // decltype-specifier,
5960 // a temporary object is not introduced for the prvalue.
5961
5962 // Recursively rebuild ParenExprs and comma expressions to strip out the
5963 // outermost CXXBindTemporaryExpr, if any.
5964 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5965 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
5966 if (SubExpr.isInvalid())
5967 return ExprError();
5968 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005969 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005970 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00005971 }
5972 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5973 if (BO->getOpcode() == BO_Comma) {
5974 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
5975 if (RHS.isInvalid())
5976 return ExprError();
5977 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005978 return E;
5979 return new (Context) BinaryOperator(
5980 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
5981 BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
Richard Smithfd555f62012-02-22 02:04:18 +00005982 }
5983 }
5984
5985 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00005986 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
5987 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00005988 if (TopCall)
5989 E = TopCall;
5990 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005991 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00005992
5993 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005994 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00005995
Richard Smithf86b0ae2012-07-28 19:54:11 +00005996 // In MS mode, don't perform any extra checking of call return types within a
5997 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00005998 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005999 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006000
Richard Smithfd555f62012-02-22 02:04:18 +00006001 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006002 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6003 I != N; ++I) {
6004 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006005 if (Call == TopCall)
6006 continue;
6007
David Majnemerced8bdf2015-02-25 17:36:15 +00006008 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006009 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006010 Call, Call->getDirectCallee()))
6011 return ExprError();
6012 }
6013
6014 // Now all relevant types are complete, check the destructors are accessible
6015 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006016 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6017 I != N; ++I) {
6018 CXXBindTemporaryExpr *Bind =
6019 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006020 if (Bind == TopBind)
6021 continue;
6022
6023 CXXTemporary *Temp = Bind->getTemporary();
6024
6025 CXXRecordDecl *RD =
6026 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6027 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6028 Temp->setDestructor(Destructor);
6029
Richard Smith7d847b12012-05-11 22:20:10 +00006030 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6031 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006032 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006033 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006034 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6035 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006036
6037 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006038 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006039 }
6040
6041 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006042 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006043}
6044
Richard Smith79c927b2013-11-06 19:31:51 +00006045/// Note a set of 'operator->' functions that were used for a member access.
6046static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006047 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006048 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6049 // FIXME: Make this configurable?
6050 unsigned Limit = 9;
6051 if (OperatorArrows.size() > Limit) {
6052 // Produce Limit-1 normal notes and one 'skipping' note.
6053 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6054 SkipCount = OperatorArrows.size() - (Limit - 1);
6055 }
6056
6057 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6058 if (I == SkipStart) {
6059 S.Diag(OperatorArrows[I]->getLocation(),
6060 diag::note_operator_arrows_suppressed)
6061 << SkipCount;
6062 I += SkipCount;
6063 } else {
6064 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6065 << OperatorArrows[I]->getCallResultType();
6066 ++I;
6067 }
6068 }
6069}
6070
Nico Weber964d3322015-02-16 22:35:45 +00006071ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6072 SourceLocation OpLoc,
6073 tok::TokenKind OpKind,
6074 ParsedType &ObjectType,
6075 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006076 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006077 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006078 if (Result.isInvalid()) return ExprError();
6079 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006080
John McCall526ab472011-10-25 17:37:35 +00006081 Result = CheckPlaceholderExpr(Base);
6082 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006083 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006084
John McCallb268a282010-08-23 23:25:46 +00006085 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006086 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006087 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006088 // If we have a pointer to a dependent type and are using the -> operator,
6089 // the object type is the type that the pointer points to. We might still
6090 // have enough information about that type to do something useful.
6091 if (OpKind == tok::arrow)
6092 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6093 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006094
John McCallba7bf592010-08-24 05:47:05 +00006095 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006096 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006097 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006098 }
Mike Stump11289f42009-09-09 15:08:12 +00006099
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006100 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006101 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006102 // returned, with the original second operand.
6103 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006104 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006105 bool NoArrowOperatorFound = false;
6106 bool FirstIteration = true;
6107 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006108 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006109 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006110 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006111 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006112
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006113 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006114 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6115 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006116 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006117 noteOperatorArrows(*this, OperatorArrows);
6118 Diag(OpLoc, diag::note_operator_arrow_depth)
6119 << getLangOpts().ArrowDepth;
6120 return ExprError();
6121 }
6122
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006123 Result = BuildOverloadedArrowExpr(
6124 S, Base, OpLoc,
6125 // When in a template specialization and on the first loop iteration,
6126 // potentially give the default diagnostic (with the fixit in a
6127 // separate note) instead of having the error reported back to here
6128 // and giving a diagnostic with a fixit attached to the error itself.
6129 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006130 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006131 : &NoArrowOperatorFound);
6132 if (Result.isInvalid()) {
6133 if (NoArrowOperatorFound) {
6134 if (FirstIteration) {
6135 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006136 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006137 << FixItHint::CreateReplacement(OpLoc, ".");
6138 OpKind = tok::period;
6139 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006140 }
6141 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6142 << BaseType << Base->getSourceRange();
6143 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006144 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006145 Diag(CD->getLocStart(),
6146 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006147 }
6148 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006149 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006150 }
John McCallb268a282010-08-23 23:25:46 +00006151 Base = Result.get();
6152 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006153 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006154 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006155 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006156 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006157 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6158 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006159 return ExprError();
6160 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006161 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006162 }
Mike Stump11289f42009-09-09 15:08:12 +00006163
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006164 if (OpKind == tok::arrow &&
6165 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006166 BaseType = BaseType->getPointeeType();
6167 }
Mike Stump11289f42009-09-09 15:08:12 +00006168
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006169 // Objective-C properties allow "." access on Objective-C pointer types,
6170 // so adjust the base type to the object type itself.
6171 if (BaseType->isObjCObjectPointerType())
6172 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006173
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006174 // C++ [basic.lookup.classref]p2:
6175 // [...] If the type of the object expression is of pointer to scalar
6176 // type, the unqualified-id is looked up in the context of the complete
6177 // postfix-expression.
6178 //
6179 // This also indicates that we could be parsing a pseudo-destructor-name.
6180 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006181 // expressions or normal member (ivar or property) access expressions, and
6182 // it's legal for the type to be incomplete if this is a pseudo-destructor
6183 // call. We'll do more incomplete-type checks later in the lookup process,
6184 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006185 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006186 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006187 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006188 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006189 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006190 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006191 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006192 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006193 }
Mike Stump11289f42009-09-09 15:08:12 +00006194
Douglas Gregor3024f072012-04-16 07:05:22 +00006195 // The object type must be complete (or dependent), or
6196 // C++11 [expr.prim.general]p3:
6197 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006198 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006199 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006200 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006201 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006202 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006203 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006204
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006205 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006206 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006207 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006208 // type C (or of pointer to a class type C), the unqualified-id is looked
6209 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006210 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006211 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006212}
6213
Simon Pilgrim75c26882016-09-30 14:25:09 +00006214static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006215 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006216 if (Base->hasPlaceholderType()) {
6217 ExprResult result = S.CheckPlaceholderExpr(Base);
6218 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006219 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006220 }
6221 ObjectType = Base->getType();
6222
David Blaikie1d578782011-12-16 16:03:09 +00006223 // C++ [expr.pseudo]p2:
6224 // The left-hand side of the dot operator shall be of scalar type. The
6225 // left-hand side of the arrow operator shall be of pointer to scalar type.
6226 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006227 // Note that this is rather different from the normal handling for the
6228 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006229 if (OpKind == tok::arrow) {
6230 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6231 ObjectType = Ptr->getPointeeType();
6232 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006233 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006234 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6235 << ObjectType << true
6236 << FixItHint::CreateReplacement(OpLoc, ".");
6237 if (S.isSFINAEContext())
6238 return true;
6239
6240 OpKind = tok::period;
6241 }
6242 }
6243
6244 return false;
6245}
6246
John McCalldadc5752010-08-24 06:29:42 +00006247ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006248 SourceLocation OpLoc,
6249 tok::TokenKind OpKind,
6250 const CXXScopeSpec &SS,
6251 TypeSourceInfo *ScopeTypeInfo,
6252 SourceLocation CCLoc,
6253 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006254 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006255 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006256
Eli Friedman0ce4de42012-01-25 04:35:06 +00006257 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006258 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6259 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006260
Douglas Gregorc5c57342012-09-10 14:57:06 +00006261 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6262 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006263 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006264 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006265 else {
Nico Weber58829272012-01-23 05:50:57 +00006266 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6267 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006268 return ExprError();
6269 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006270 }
6271
6272 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006273 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006274 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006275 if (DestructedTypeInfo) {
6276 QualType DestructedType = DestructedTypeInfo->getType();
6277 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006278 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006279 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6280 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6281 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6282 << ObjectType << DestructedType << Base->getSourceRange()
6283 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006284
John McCall31168b02011-06-15 23:02:42 +00006285 // Recover by setting the destructed type to the object type.
6286 DestructedType = ObjectType;
6287 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregor678f90d2010-02-25 01:56:36 +00006288 DestructedTypeStart);
John McCall31168b02011-06-15 23:02:42 +00006289 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
Simon Pilgrim75c26882016-09-30 14:25:09 +00006290 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006291 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006292
John McCall31168b02011-06-15 23:02:42 +00006293 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6294 // Okay: just pretend that the user provided the correctly-qualified
6295 // type.
6296 } else {
6297 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6298 << ObjectType << DestructedType << Base->getSourceRange()
6299 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6300 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006301
John McCall31168b02011-06-15 23:02:42 +00006302 // Recover by setting the destructed type to the object type.
6303 DestructedType = ObjectType;
6304 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6305 DestructedTypeStart);
6306 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6307 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006308 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006309 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006310
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006311 // C++ [expr.pseudo]p2:
6312 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6313 // form
6314 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006315 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006316 //
6317 // shall designate the same scalar type.
6318 if (ScopeTypeInfo) {
6319 QualType ScopeType = ScopeTypeInfo->getType();
6320 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006321 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006322
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006323 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006324 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006325 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006326 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006327
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006328 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006329 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006330 }
6331 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006332
John McCallb268a282010-08-23 23:25:46 +00006333 Expr *Result
6334 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6335 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006336 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006337 ScopeTypeInfo,
6338 CCLoc,
6339 TildeLoc,
6340 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006341
David Majnemerced8bdf2015-02-25 17:36:15 +00006342 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006343}
6344
John McCalldadc5752010-08-24 06:29:42 +00006345ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006346 SourceLocation OpLoc,
6347 tok::TokenKind OpKind,
6348 CXXScopeSpec &SS,
6349 UnqualifiedId &FirstTypeName,
6350 SourceLocation CCLoc,
6351 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006352 UnqualifiedId &SecondTypeName) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006353 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6354 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6355 "Invalid first type name in pseudo-destructor");
6356 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6357 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6358 "Invalid second type name in pseudo-destructor");
6359
Eli Friedman0ce4de42012-01-25 04:35:06 +00006360 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006361 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6362 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006363
6364 // Compute the object type that we should use for name lookup purposes. Only
6365 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006366 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006367 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006368 if (ObjectType->isRecordType())
6369 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006370 else if (ObjectType->isDependentType())
6371 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006372 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006373
6374 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006375 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006376 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006377 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006378 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006379 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006380 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006381 SecondTypeName.StartLocation,
Fariborz Jahanian87967422011-02-08 18:05:59 +00006382 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006383 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006384 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6385 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006386 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006387 // couldn't find anything useful in scope. Just store the identifier and
6388 // it's location, and we'll perform (qualified) name lookup again at
6389 // template instantiation time.
6390 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6391 SecondTypeName.StartLocation);
6392 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006393 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006394 diag::err_pseudo_dtor_destructor_non_type)
6395 << SecondTypeName.Identifier << ObjectType;
6396 if (isSFINAEContext())
6397 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006398
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006399 // Recover by assuming we had the right type all along.
6400 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006401 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006402 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006403 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006404 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006405 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006406 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006407 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006408 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006409 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006410 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006411 TemplateId->TemplateNameLoc,
6412 TemplateId->LAngleLoc,
6413 TemplateArgsPtr,
6414 TemplateId->RAngleLoc);
6415 if (T.isInvalid() || !T.get()) {
6416 // Recover by assuming we had the right type all along.
6417 DestructedType = ObjectType;
6418 } else
6419 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006420 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006421
6422 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006423 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006424 if (!DestructedType.isNull()) {
6425 if (!DestructedTypeInfo)
6426 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006427 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006428 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6429 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006430
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006431 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006432 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006433 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006434 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006435 FirstTypeName.Identifier) {
6436 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006437 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006438 FirstTypeName.StartLocation,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006439 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006440 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006441 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006442 diag::err_pseudo_dtor_destructor_non_type)
6443 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006444
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006445 if (isSFINAEContext())
6446 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006447
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006448 // Just drop this type. It's unnecessary anyway.
6449 ScopeType = QualType();
6450 } else
6451 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006452 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006453 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006454 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006455 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006456 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006457 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006458 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006459 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006460 TemplateId->TemplateNameLoc,
6461 TemplateId->LAngleLoc,
6462 TemplateArgsPtr,
6463 TemplateId->RAngleLoc);
6464 if (T.isInvalid() || !T.get()) {
6465 // Recover by dropping this type.
6466 ScopeType = QualType();
6467 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006468 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006469 }
6470 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006471
Douglas Gregor90ad9222010-02-24 23:02:30 +00006472 if (!ScopeType.isNull() && !ScopeTypeInfo)
6473 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6474 FirstTypeName.StartLocation);
6475
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006476
John McCallb268a282010-08-23 23:25:46 +00006477 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00006478 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006479 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00006480}
6481
David Blaikie1d578782011-12-16 16:03:09 +00006482ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6483 SourceLocation OpLoc,
6484 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006485 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006486 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00006487 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006488 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6489 return ExprError();
6490
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006491 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6492 false);
David Blaikie1d578782011-12-16 16:03:09 +00006493
6494 TypeLocBuilder TLB;
6495 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6496 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6497 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6498 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6499
6500 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006501 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006502 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00006503}
6504
John Wiegley01296292011-04-08 18:41:53 +00006505ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00006506 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006507 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00006508 if (Method->getParent()->isLambda() &&
6509 Method->getConversionType()->isBlockPointerType()) {
6510 // This is a lambda coversion to block pointer; check if the argument
6511 // is a LambdaExpr.
6512 Expr *SubE = E;
6513 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6514 if (CE && CE->getCastKind() == CK_NoOp)
6515 SubE = CE->getSubExpr();
6516 SubE = SubE->IgnoreParens();
6517 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6518 SubE = BE->getSubExpr();
6519 if (isa<LambdaExpr>(SubE)) {
6520 // For the conversion to block pointer on a lambda expression, we
6521 // construct a special BlockLiteral instead; this doesn't really make
6522 // a difference in ARC, but outside of ARC the resulting block literal
6523 // follows the normal lifetime rules for block literals instead of being
6524 // autoreleased.
6525 DiagnosticErrorTrap Trap(Diags);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006526 PushExpressionEvaluationContext(PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00006527 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6528 E->getExprLoc(),
6529 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006530 PopExpressionEvaluationContext();
6531
Eli Friedman98b01ed2012-03-01 04:01:32 +00006532 if (Exp.isInvalid())
6533 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6534 return Exp;
6535 }
6536 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00006537
Craig Topperc3ec1492014-05-26 06:22:03 +00006538 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006539 FoundDecl, Method);
6540 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00006541 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00006542
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00006543 MemberExpr *ME = new (Context) MemberExpr(
6544 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6545 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006546 if (HadMultipleCandidates)
6547 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00006548 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006549
Alp Toker314cc812014-01-25 16:55:45 +00006550 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00006551 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6552 ResultType = ResultType.getNonLValueExprType(Context);
6553
Douglas Gregor27381f32009-11-23 12:27:39 +00006554 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006555 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00006556 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006557 return CE;
6558}
6559
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006560ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6561 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00006562 // If the operand is an unresolved lookup expression, the expression is ill-
6563 // formed per [over.over]p1, because overloaded function names cannot be used
6564 // without arguments except in explicit contexts.
6565 ExprResult R = CheckPlaceholderExpr(Operand);
6566 if (R.isInvalid())
6567 return R;
6568
6569 // The operand may have been modified when checking the placeholder type.
6570 Operand = R.get();
6571
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006572 if (ActiveTemplateInstantiations.empty() &&
6573 Operand->HasSideEffects(Context, false)) {
6574 // The expression operand for noexcept is in an unevaluated expression
6575 // context, so side effects could result in unintended consequences.
6576 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6577 }
6578
Richard Smithf623c962012-04-17 00:58:00 +00006579 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006580 return new (Context)
6581 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006582}
6583
6584ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6585 Expr *Operand, SourceLocation RParen) {
6586 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00006587}
6588
Eli Friedmanf798f652012-05-24 22:04:19 +00006589static bool IsSpecialDiscardedValue(Expr *E) {
6590 // In C++11, discarded-value expressions of a certain form are special,
6591 // according to [expr]p10:
6592 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6593 // expression is an lvalue of volatile-qualified type and it has
6594 // one of the following forms:
6595 E = E->IgnoreParens();
6596
Eli Friedmanc49c2262012-05-24 22:36:31 +00006597 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006598 if (isa<DeclRefExpr>(E))
6599 return true;
6600
Eli Friedmanc49c2262012-05-24 22:36:31 +00006601 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006602 if (isa<ArraySubscriptExpr>(E))
6603 return true;
6604
Eli Friedmanc49c2262012-05-24 22:36:31 +00006605 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006606 if (isa<MemberExpr>(E))
6607 return true;
6608
Eli Friedmanc49c2262012-05-24 22:36:31 +00006609 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006610 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6611 if (UO->getOpcode() == UO_Deref)
6612 return true;
6613
6614 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00006615 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006616 if (BO->isPtrMemOp())
6617 return true;
6618
Eli Friedmanc49c2262012-05-24 22:36:31 +00006619 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00006620 if (BO->getOpcode() == BO_Comma)
6621 return IsSpecialDiscardedValue(BO->getRHS());
6622 }
6623
Eli Friedmanc49c2262012-05-24 22:36:31 +00006624 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00006625 // operands are one of the above, or
6626 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6627 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6628 IsSpecialDiscardedValue(CO->getFalseExpr());
6629 // The related edge case of "*x ?: *x".
6630 if (BinaryConditionalOperator *BCO =
6631 dyn_cast<BinaryConditionalOperator>(E)) {
6632 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6633 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6634 IsSpecialDiscardedValue(BCO->getFalseExpr());
6635 }
6636
6637 // Objective-C++ extensions to the rule.
6638 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6639 return true;
6640
6641 return false;
6642}
6643
John McCall34376a62010-12-04 03:47:34 +00006644/// Perform the conversions required for an expression used in a
6645/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00006646ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00006647 if (E->hasPlaceholderType()) {
6648 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006649 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006650 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00006651 }
6652
John McCallfee942d2010-12-02 02:07:15 +00006653 // C99 6.3.2.1:
6654 // [Except in specific positions,] an lvalue that does not have
6655 // array type is converted to the value stored in the
6656 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00006657 if (E->isRValue()) {
6658 // In C, function designators (i.e. expressions of function type)
6659 // are r-values, but we still want to do function-to-pointer decay
6660 // on them. This is both technically correct and convenient for
6661 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006662 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00006663 return DefaultFunctionArrayConversion(E);
6664
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006665 return E;
John McCalld68b2d02011-06-27 21:24:11 +00006666 }
John McCallfee942d2010-12-02 02:07:15 +00006667
Eli Friedmanf798f652012-05-24 22:04:19 +00006668 if (getLangOpts().CPlusPlus) {
6669 // The C++11 standard defines the notion of a discarded-value expression;
6670 // normally, we don't need to do anything to handle it, but if it is a
6671 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6672 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006673 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00006674 E->getType().isVolatileQualified() &&
6675 IsSpecialDiscardedValue(E)) {
6676 ExprResult Res = DefaultLvalueConversion(E);
6677 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006678 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006679 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006680 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006681 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00006682 }
John McCall34376a62010-12-04 03:47:34 +00006683
6684 // GCC seems to also exclude expressions of incomplete enum type.
6685 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6686 if (!T->getDecl()->isComplete()) {
6687 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006688 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006689 return E;
John McCall34376a62010-12-04 03:47:34 +00006690 }
6691 }
6692
John Wiegley01296292011-04-08 18:41:53 +00006693 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6694 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006695 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006696 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00006697
John McCallca61b652010-12-04 12:29:11 +00006698 if (!E->getType()->isVoidType())
6699 RequireCompleteType(E->getExprLoc(), E->getType(),
6700 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006701 return E;
John McCall34376a62010-12-04 03:47:34 +00006702}
6703
Faisal Valia17d19f2013-11-07 05:17:06 +00006704// If we can unambiguously determine whether Var can never be used
6705// in a constant expression, return true.
6706// - if the variable and its initializer are non-dependent, then
6707// we can unambiguously check if the variable is a constant expression.
6708// - if the initializer is not value dependent - we can determine whether
6709// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00006710// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00006711// never be a constant expression.
6712// - FXIME: if the initializer is dependent, we can still do some analysis and
6713// identify certain cases unambiguously as non-const by using a Visitor:
6714// - such as those that involve odr-use of a ParmVarDecl, involve a new
6715// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00006716static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00006717 ASTContext &Context) {
6718 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006719 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006720
6721 // If there is no initializer - this can not be a constant expression.
6722 if (!Var->getAnyInitializer(DefVD)) return true;
6723 assert(DefVD);
6724 if (DefVD->isWeak()) return false;
6725 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00006726
Faisal Valia17d19f2013-11-07 05:17:06 +00006727 Expr *Init = cast<Expr>(Eval->Value);
6728
6729 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00006730 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
6731 // of value-dependent expressions, and use it here to determine whether the
6732 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00006733 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00006734 }
6735
Simon Pilgrim75c26882016-09-30 14:25:09 +00006736 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00006737}
6738
Simon Pilgrim75c26882016-09-30 14:25:09 +00006739/// \brief Check if the current lambda has any potential captures
6740/// that must be captured by any of its enclosing lambdas that are ready to
6741/// capture. If there is a lambda that can capture a nested
6742/// potential-capture, go ahead and do so. Also, check to see if any
6743/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00006744/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00006745
Faisal Valiab3d6462013-12-07 20:22:44 +00006746static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
6747 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
6748
Simon Pilgrim75c26882016-09-30 14:25:09 +00006749 assert(!S.isUnevaluatedContext());
6750 assert(S.CurContext->isDependentContext());
6751 assert(CurrentLSI->CallOperator == S.CurContext &&
Faisal Valiab3d6462013-12-07 20:22:44 +00006752 "The current call operator must be synchronized with Sema's CurContext");
6753
6754 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
6755
6756 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
6757 S.FunctionScopes.data(), S.FunctionScopes.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00006758
Faisal Valiab3d6462013-12-07 20:22:44 +00006759 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00006760 // lambda (within a generic outer lambda), must be captured by an
6761 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00006762 const unsigned NumPotentialCaptures =
6763 CurrentLSI->getNumPotentialVariableCaptures();
6764 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006765 Expr *VarExpr = nullptr;
6766 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006767 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00006768 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00006769 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00006770 // need to check enclosing lambda's for speculative captures.
6771 // For e.g.:
6772 // Even though 'x' is not odr-used, it should be captured.
6773 // int test() {
6774 // const int x = 10;
6775 // auto L = [=](auto a) {
6776 // (void) +x + a;
6777 // };
6778 // }
6779 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00006780 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00006781 continue;
6782
6783 // If we have a capture-capable lambda for the variable, go ahead and
6784 // capture the variable in that lambda (and all its enclosing lambdas).
6785 if (const Optional<unsigned> Index =
6786 getStackIndexOfNearestEnclosingCaptureCapableLambda(
6787 FunctionScopesArrayRef, Var, S)) {
6788 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6789 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
6790 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00006791 }
6792 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00006793 VariableCanNeverBeAConstantExpression(Var, S.Context);
6794 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
6795 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00006796 // can not be used in a constant expression - which means
6797 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00006798 // capture violation early, if the variable is un-captureable.
6799 // This is purely for diagnosing errors early. Otherwise, this
6800 // error would get diagnosed when the lambda becomes capture ready.
6801 QualType CaptureType, DeclRefType;
6802 SourceLocation ExprLoc = VarExpr->getExprLoc();
6803 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006804 /*EllipsisLoc*/ SourceLocation(),
6805 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00006806 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00006807 // We will never be able to capture this variable, and we need
6808 // to be able to in any and all instantiations, so diagnose it.
6809 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006810 /*EllipsisLoc*/ SourceLocation(),
6811 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00006812 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00006813 }
6814 }
6815 }
6816
Faisal Valiab3d6462013-12-07 20:22:44 +00006817 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00006818 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00006819 // If we have a capture-capable lambda for 'this', go ahead and capture
6820 // 'this' in that lambda (and all its enclosing lambdas).
6821 if (const Optional<unsigned> Index =
6822 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Craig Topperc3ec1492014-05-26 06:22:03 +00006823 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00006824 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6825 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
6826 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
6827 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00006828 }
6829 }
Faisal Valiab3d6462013-12-07 20:22:44 +00006830
6831 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00006832 CurrentLSI->clearPotentialCaptures();
6833}
6834
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006835static ExprResult attemptRecovery(Sema &SemaRef,
6836 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00006837 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006838 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
6839 Consumer.getLookupResult().getLookupKind());
6840 const CXXScopeSpec *SS = Consumer.getSS();
6841 CXXScopeSpec NewSS;
6842
6843 // Use an approprate CXXScopeSpec for building the expr.
6844 if (auto *NNS = TC.getCorrectionSpecifier())
6845 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
6846 else if (SS && !TC.WillReplaceSpecifier())
6847 NewSS = *SS;
6848
Richard Smithde6d6c42015-12-29 19:43:10 +00006849 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00006850 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006851 R.addDecl(ND);
6852 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00006853 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006854 CXXRecordDecl *Record = nullptr;
6855 if (auto *NNS = TC.getCorrectionSpecifier())
6856 Record = NNS->getAsType()->getAsCXXRecordDecl();
6857 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00006858 Record =
6859 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
6860 if (Record)
6861 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006862
6863 // Detect and handle the case where the decl might be an implicit
6864 // member.
6865 bool MightBeImplicitMember;
6866 if (!Consumer.isAddressOfOperand())
6867 MightBeImplicitMember = true;
6868 else if (!NewSS.isEmpty())
6869 MightBeImplicitMember = false;
6870 else if (R.isOverloadedResult())
6871 MightBeImplicitMember = false;
6872 else if (R.isUnresolvableResult())
6873 MightBeImplicitMember = true;
6874 else
6875 MightBeImplicitMember = isa<FieldDecl>(ND) ||
6876 isa<IndirectFieldDecl>(ND) ||
6877 isa<MSPropertyDecl>(ND);
6878
6879 if (MightBeImplicitMember)
6880 return SemaRef.BuildPossibleImplicitMemberExpr(
6881 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00006882 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006883 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
6884 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
6885 Ivar->getIdentifier());
6886 }
6887 }
6888
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00006889 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
6890 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006891}
6892
Kaelyn Takata6c759512014-10-27 18:07:37 +00006893namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00006894class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
6895 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
6896
6897public:
6898 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
6899 : TypoExprs(TypoExprs) {}
6900 bool VisitTypoExpr(TypoExpr *TE) {
6901 TypoExprs.insert(TE);
6902 return true;
6903 }
6904};
6905
Kaelyn Takata6c759512014-10-27 18:07:37 +00006906class TransformTypos : public TreeTransform<TransformTypos> {
6907 typedef TreeTransform<TransformTypos> BaseTransform;
6908
Kaelyn Takatab8499f02015-05-05 19:17:03 +00006909 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
6910 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00006911 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006912 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00006913 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006914 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00006915
6916 /// \brief Emit diagnostics for all of the TypoExprs encountered.
6917 /// If the TypoExprs were successfully corrected, then the diagnostics should
6918 /// suggest the corrections. Otherwise the diagnostics will not suggest
6919 /// anything (having been passed an empty TypoCorrection).
6920 void EmitAllDiagnostics() {
6921 for (auto E : TypoExprs) {
6922 TypoExpr *TE = cast<TypoExpr>(E);
6923 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006924 if (State.DiagHandler) {
6925 TypoCorrection TC = State.Consumer->getCurrentCorrection();
6926 ExprResult Replacement = TransformCache[TE];
6927
6928 // Extract the NamedDecl from the transformed TypoExpr and add it to the
6929 // TypoCorrection, replacing the existing decls. This ensures the right
6930 // NamedDecl is used in diagnostics e.g. in the case where overload
6931 // resolution was used to select one from several possible decls that
6932 // had been stored in the TypoCorrection.
6933 if (auto *ND = getDeclFromExpr(
6934 Replacement.isInvalid() ? nullptr : Replacement.get()))
6935 TC.setCorrectionDecl(ND);
6936
6937 State.DiagHandler(TC);
6938 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00006939 SemaRef.clearDelayedTypo(TE);
6940 }
6941 }
6942
6943 /// \brief If corrections for the first TypoExpr have been exhausted for a
6944 /// given combination of the other TypoExprs, retry those corrections against
6945 /// the next combination of substitutions for the other TypoExprs by advancing
6946 /// to the next potential correction of the second TypoExpr. For the second
6947 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
6948 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
6949 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
6950 /// TransformCache). Returns true if there is still any untried combinations
6951 /// of corrections.
6952 bool CheckAndAdvanceTypoExprCorrectionStreams() {
6953 for (auto TE : TypoExprs) {
6954 auto &State = SemaRef.getTypoExprState(TE);
6955 TransformCache.erase(TE);
6956 if (!State.Consumer->finished())
6957 return true;
6958 State.Consumer->resetCorrectionStream();
6959 }
6960 return false;
6961 }
6962
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006963 NamedDecl *getDeclFromExpr(Expr *E) {
6964 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
6965 E = OverloadResolution[OE];
6966
6967 if (!E)
6968 return nullptr;
6969 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00006970 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006971 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00006972 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006973 // FIXME: Add any other expr types that could be be seen by the delayed typo
6974 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00006975 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006976 return nullptr;
6977 }
6978
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006979 ExprResult TryTransform(Expr *E) {
6980 Sema::SFINAETrap Trap(SemaRef);
6981 ExprResult Res = TransformExpr(E);
6982 if (Trap.hasErrorOccurred() || Res.isInvalid())
6983 return ExprError();
6984
6985 return ExprFilter(Res.get());
6986 }
6987
Kaelyn Takata6c759512014-10-27 18:07:37 +00006988public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00006989 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
6990 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00006991
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006992 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
6993 MultiExprArg Args,
6994 SourceLocation RParenLoc,
6995 Expr *ExecConfig = nullptr) {
6996 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
6997 RParenLoc, ExecConfig);
6998 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00006999 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007000 Expr *ResultCall = Result.get();
7001 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7002 ResultCall = BE->getSubExpr();
7003 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7004 OverloadResolution[OE] = CE->getCallee();
7005 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007006 }
7007 return Result;
7008 }
7009
Kaelyn Takata6c759512014-10-27 18:07:37 +00007010 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7011
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007012 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7013
Saleem Abdulrasool407f36b2016-02-07 02:30:55 +00007014 ExprResult TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
7015 return Owned(E);
7016 }
7017
Saleem Abdulrasool02e19a12016-02-07 02:30:59 +00007018 ExprResult TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
7019 return Owned(E);
7020 }
7021
Kaelyn Takata6c759512014-10-27 18:07:37 +00007022 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007023 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007024 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007025 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007026
Kaelyn Takata6c759512014-10-27 18:07:37 +00007027 // Exit if either the transform was valid or if there were no TypoExprs
7028 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007029 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007030 !CheckAndAdvanceTypoExprCorrectionStreams())
7031 break;
7032 }
7033
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007034 // Ensure none of the TypoExprs have multiple typo correction candidates
7035 // with the same edit length that pass all the checks and filters.
7036 // TODO: Properly handle various permutations of possible corrections when
7037 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007038 // Also, disable typo correction while attempting the transform when
7039 // handling potentially ambiguous typo corrections as any new TypoExprs will
7040 // have been introduced by the application of one of the correction
7041 // candidates and add little to no value if corrected.
7042 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007043 while (!AmbiguousTypoExprs.empty()) {
7044 auto TE = AmbiguousTypoExprs.back();
7045 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007046 auto &State = SemaRef.getTypoExprState(TE);
7047 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007048 TransformCache.erase(TE);
7049 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007050 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007051 TransformCache.erase(TE);
7052 Res = ExprError();
7053 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007054 }
7055 AmbiguousTypoExprs.remove(TE);
7056 State.Consumer->restoreSavedPosition();
7057 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007058 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007059 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007060
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007061 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007062 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007063 FindTypoExprs(TypoExprs).TraverseStmt(E);
7064
Kaelyn Takata6c759512014-10-27 18:07:37 +00007065 EmitAllDiagnostics();
7066
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007067 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007068 }
7069
7070 ExprResult TransformTypoExpr(TypoExpr *E) {
7071 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7072 // cached transformation result if there is one and the TypoExpr isn't the
7073 // first one that was encountered.
7074 auto &CacheEntry = TransformCache[E];
7075 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7076 return CacheEntry;
7077 }
7078
7079 auto &State = SemaRef.getTypoExprState(E);
7080 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7081
7082 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7083 // typo correction and return it.
7084 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007085 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007086 continue;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007087 ExprResult NE = State.RecoveryHandler ?
7088 State.RecoveryHandler(SemaRef, E, TC) :
7089 attemptRecovery(SemaRef, *State.Consumer, TC);
7090 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007091 // Check whether there may be a second viable correction with the same
7092 // edit distance; if so, remember this TypoExpr may have an ambiguous
7093 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007094 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007095 if ((Next = State.Consumer->peekNextCorrection()) &&
7096 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7097 AmbiguousTypoExprs.insert(E);
7098 } else {
7099 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007100 }
7101 assert(!NE.isUnset() &&
7102 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007103 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007104 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007105 }
7106 return CacheEntry = ExprError();
7107 }
7108};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007109}
Faisal Valia17d19f2013-11-07 05:17:06 +00007110
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007111ExprResult
7112Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7113 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007114 // If the current evaluation context indicates there are uncorrected typos
7115 // and the current expression isn't guaranteed to not have typos, try to
7116 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007117 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007118 (E->isTypeDependent() || E->isValueDependent() ||
7119 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007120 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7121 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7122 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007123 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007124 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007125 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007126 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007127 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007128 ExprEvalContexts.back().NumTypos -= TyposResolved;
7129 return Result;
7130 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007131 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007132 }
7133 return E;
7134}
7135
Richard Smith945f8d32013-01-14 22:39:08 +00007136ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007137 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007138 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007139 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007140 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007141
7142 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007143 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007144
7145 // If we are an init-expression in a lambdas init-capture, we should not
7146 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007147 // containing full-expression is done).
7148 // template<class ... Ts> void test(Ts ... t) {
7149 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7150 // return a;
7151 // }() ...);
7152 // }
7153 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7154 // when we parse the lambda introducer, and teach capturing (but not
7155 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7156 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7157 // lambda where we've entered the introducer but not the body, or represent a
7158 // lambda where we've entered the body, depending on where the
7159 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007160 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007161 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007162 return ExprError();
7163
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007164 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007165 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007166 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007167 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007168 if (FullExpr.isInvalid())
7169 return ExprError();
7170 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007171
Richard Smith945f8d32013-01-14 22:39:08 +00007172 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007173 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007174 if (FullExpr.isInvalid())
7175 return ExprError();
7176
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007177 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007178 if (FullExpr.isInvalid())
7179 return ExprError();
7180 }
John Wiegley01296292011-04-08 18:41:53 +00007181
Kaelyn Takata49d84322014-11-11 23:26:56 +00007182 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7183 if (FullExpr.isInvalid())
7184 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007185
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007186 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007187
Simon Pilgrim75c26882016-09-30 14:25:09 +00007188 // At the end of this full expression (which could be a deeply nested
7189 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007190 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007191 // Consider the following code:
7192 // void f(int, int);
7193 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007194 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007195 // const int x = 10, y = 20;
7196 // auto L = [=](auto a) {
7197 // auto M = [=](auto b) {
7198 // f(x, b); <-- requires x to be captured by L and M
7199 // f(y, a); <-- requires y to be captured by L, but not all Ms
7200 // };
7201 // };
7202 // }
7203
Simon Pilgrim75c26882016-09-30 14:25:09 +00007204 // FIXME: Also consider what happens for something like this that involves
7205 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007206 // void f() {
7207 // const int n = 0;
7208 // auto L = [&](auto a) {
7209 // +n + ({ 0; a; });
7210 // };
7211 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007212 //
7213 // Here, we see +n, and then the full-expression 0; ends, so we don't
7214 // capture n (and instead remove it from our list of potential captures),
7215 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007216 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007217
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007218 LambdaScopeInfo *const CurrentLSI = getCurLambda();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007219 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007220 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007221 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007222 // By ensuring we are in the context of a lambda's call operator
7223 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007224 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007225 // PR, a proper fix would entail :
7226 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007227 // - Add to Sema an integer holding the smallest (outermost) scope
7228 // index that we are *lexically* within, and save/restore/set to
7229 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007230 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007231 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007232 // stop at the outermost enclosing lexical scope."
7233 const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
7234 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007235 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007236 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7237 *this);
John McCall5d413782010-12-06 08:20:24 +00007238 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007239}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007240
7241StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7242 if (!FullStmt) return StmtError();
7243
John McCall5d413782010-12-06 08:20:24 +00007244 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007245}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007246
Simon Pilgrim75c26882016-09-30 14:25:09 +00007247Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007248Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7249 CXXScopeSpec &SS,
7250 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007251 DeclarationName TargetName = TargetNameInfo.getName();
7252 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007253 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007254
Douglas Gregor43edb322011-10-24 22:31:10 +00007255 // If the name itself is dependent, then the result is dependent.
7256 if (TargetName.isDependentName())
7257 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007258
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007259 // Do the redeclaration lookup in the current scope.
7260 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7261 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007262 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007263 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007264
Douglas Gregor43edb322011-10-24 22:31:10 +00007265 switch (R.getResultKind()) {
7266 case LookupResult::Found:
7267 case LookupResult::FoundOverloaded:
7268 case LookupResult::FoundUnresolvedValue:
7269 case LookupResult::Ambiguous:
7270 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007271
Douglas Gregor43edb322011-10-24 22:31:10 +00007272 case LookupResult::NotFound:
7273 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007274
Douglas Gregor43edb322011-10-24 22:31:10 +00007275 case LookupResult::NotFoundInCurrentInstantiation:
7276 return IER_Dependent;
7277 }
David Blaikie8a40f702012-01-17 06:56:22 +00007278
7279 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007280}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007281
Simon Pilgrim75c26882016-09-30 14:25:09 +00007282Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007283Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7284 bool IsIfExists, CXXScopeSpec &SS,
7285 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007286 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007287
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007288 // Check for unexpanded parameter packs.
7289 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
7290 collectUnexpandedParameterPacks(SS, Unexpanded);
7291 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
7292 if (!Unexpanded.empty()) {
7293 DiagnoseUnexpandedParameterPacks(KeywordLoc,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007294 IsIfExists? UPPC_IfExists
7295 : UPPC_IfNotExists,
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007296 Unexpanded);
7297 return IER_Error;
7298 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007299
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007300 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7301}