blob: 89055aecd4b6deb64ec1cd3a8e78340d29f700dd [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"
Akira Hatanaka3e40c302017-07-19 17:17:50 +000027#include "clang/Basic/AlignedAllocation.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Initialization.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000037#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000039#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000042using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000043using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000044
Richard Smith7447af42013-03-26 01:15:19 +000045/// \brief Handle the result of the special case name lookup for inheriting
46/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47/// constructor names in member using declarations, even if 'X' is not the
48/// name of the corresponding type.
49ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50 SourceLocation NameLoc,
51 IdentifierInfo &Name) {
52 NestedNameSpecifier *NNS = SS.getScopeRep();
53
54 // Convert the nested-name-specifier into a type.
55 QualType Type;
56 switch (NNS->getKind()) {
57 case NestedNameSpecifier::TypeSpec:
58 case NestedNameSpecifier::TypeSpecWithTemplate:
59 Type = QualType(NNS->getAsType(), 0);
60 break;
61
62 case NestedNameSpecifier::Identifier:
63 // Strip off the last layer of the nested-name-specifier and build a
64 // typename type for it.
65 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
66 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67 NNS->getAsIdentifier());
68 break;
69
70 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000071 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000072 case NestedNameSpecifier::Namespace:
73 case NestedNameSpecifier::NamespaceAlias:
74 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
75 }
76
77 // This reference to the type is located entirely at the location of the
78 // final identifier in the qualified-id.
79 return CreateParsedType(Type,
80 Context.getTrivialTypeSourceInfo(Type, NameLoc));
81}
82
John McCallba7bf592010-08-24 05:47:05 +000083ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000084 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000085 SourceLocation NameLoc,
86 Scope *S, CXXScopeSpec &SS,
87 ParsedType ObjectTypePtr,
88 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000089 // Determine where to perform name lookup.
90
91 // FIXME: This area of the standard is very messy, and the current
92 // wording is rather unclear about which scopes we search for the
93 // destructor name; see core issues 399 and 555. Issue 399 in
94 // particular shows where the current description of destructor name
95 // lookup is completely out of line with existing practice, e.g.,
96 // this appears to be ill-formed:
97 //
98 // namespace N {
99 // template <typename T> struct S {
100 // ~S();
101 // };
102 // }
103 //
104 // void f(N::S<int>* s) {
105 // s->N::S<int>::~S();
106 // }
107 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000108 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000109 // For this reason, we're currently only doing the C++03 version of this
110 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000111 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000112 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000113 bool isDependent = false;
114 bool LookInScope = false;
115
Richard Smith64e033f2015-01-15 00:48:52 +0000116 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000117 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000118
Douglas Gregorfe17d252010-02-16 19:09:40 +0000119 // If we have an object type, it's because we are in a
120 // pseudo-destructor-expression or a member access expression, and
121 // we know what type we're looking for.
122 if (ObjectTypePtr)
123 SearchType = GetTypeFromParser(ObjectTypePtr);
124
125 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000126 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000127
Douglas Gregor46841e12010-02-23 00:15:22 +0000128 bool AlreadySearched = false;
129 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000130 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000131 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000132 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000133 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000134 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000135 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000136 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000137 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000138 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000139 // Here, we determine whether the code below is permitted to look at the
140 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000141 DeclContext *DC = computeDeclContext(SS, EnteringContext);
142 if (DC && DC->isFileContext()) {
143 AlreadySearched = true;
144 LookupCtx = DC;
145 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000146 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000147 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000148 LookInScope = true;
149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000150
Sebastian Redla771d222010-07-07 23:17:38 +0000151 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000152 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000153 if (AlreadySearched) {
154 // Nothing left to do.
155 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
156 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000157 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000158 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
159 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000160 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000161 LookupCtx = computeDeclContext(SearchType);
162 isDependent = SearchType->isDependentType();
163 } else {
164 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000165 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000166 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000167 } else if (ObjectTypePtr) {
168 // C++ [basic.lookup.classref]p3:
169 // If the unqualified-id is ~type-name, the type-name is looked up
170 // in the context of the entire postfix-expression. If the type T
171 // of the object expression is of a class type C, the type-name is
172 // also looked up in the scope of class C. At least one of the
173 // lookups shall find a name that refers to (possibly
174 // cv-qualified) T.
175 LookupCtx = computeDeclContext(SearchType);
176 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000177 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000178 "Caller should have completed object type");
179
180 LookInScope = true;
181 } else {
182 // Perform lookup into the current scope (only).
183 LookInScope = true;
184 }
185
Craig Topperc3ec1492014-05-26 06:22:03 +0000186 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000187 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
188 for (unsigned Step = 0; Step != 2; ++Step) {
189 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000190 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000191 // we're allowed to look there).
192 Found.clear();
John McCallcb731542017-06-11 20:33:00 +0000193 if (Step == 0 && LookupCtx) {
194 if (RequireCompleteDeclContext(SS, LookupCtx))
195 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000196 LookupQualifiedName(Found, LookupCtx);
John McCallcb731542017-06-11 20:33:00 +0000197 } else if (Step == 1 && LookInScope && S) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000198 LookupName(Found, S);
John McCallcb731542017-06-11 20:33:00 +0000199 } else {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000200 continue;
John McCallcb731542017-06-11 20:33:00 +0000201 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000202
203 // FIXME: Should we be suppressing ambiguities here?
204 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000205 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000206
207 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
208 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000209 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000210
211 if (SearchType.isNull() || SearchType->isDependentType() ||
212 Context.hasSameUnqualifiedType(T, SearchType)) {
213 // We found our type!
214
Richard Smithc278c002014-01-22 00:30:17 +0000215 return CreateParsedType(T,
216 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000217 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000218
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000219 if (!SearchType.isNull())
220 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000221 }
222
223 // If the name that we found is a class template name, and it is
224 // the same name as the template name in the last part of the
225 // nested-name-specifier (if present) or the object type, then
226 // this is the destructor for that class.
227 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000228 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000229 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
230 QualType MemberOfType;
231 if (SS.isSet()) {
232 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
233 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000234 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
235 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000236 }
237 }
238 if (MemberOfType.isNull())
239 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000240
Douglas Gregorfe17d252010-02-16 19:09:40 +0000241 if (MemberOfType.isNull())
242 continue;
243
244 // We're referring into a class template specialization. If the
245 // class template we found is the same as the template being
246 // specialized, we found what we are looking for.
247 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
248 if (ClassTemplateSpecializationDecl *Spec
249 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
250 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
251 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000252 return CreateParsedType(
253 MemberOfType,
254 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000255 }
256
257 continue;
258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000259
Douglas Gregorfe17d252010-02-16 19:09:40 +0000260 // We're referring to an unresolved class template
261 // specialization. Determine whether we class template we found
262 // is the same as the template being specialized or, if we don't
263 // know which template is being specialized, that it at least
264 // has the same name.
265 if (const TemplateSpecializationType *SpecType
266 = MemberOfType->getAs<TemplateSpecializationType>()) {
267 TemplateName SpecName = SpecType->getTemplateName();
268
269 // The class template we found is the same template being
270 // specialized.
271 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
272 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000273 return CreateParsedType(
274 MemberOfType,
275 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000276
277 continue;
278 }
279
280 // The class template we found has the same name as the
281 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000282 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000283 = SpecName.getAsDependentTemplateName()) {
284 if (DepTemplate->isIdentifier() &&
285 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000286 return CreateParsedType(
287 MemberOfType,
288 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000289
290 continue;
291 }
292 }
293 }
294 }
295
296 if (isDependent) {
297 // We didn't find our type, but that's okay: it's dependent
298 // anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000299
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000300 // FIXME: What if we have no nested-name-specifier?
301 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
302 SS.getWithLocInContext(Context),
303 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000304 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000305 }
306
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000307 if (NonMatchingTypeDecl) {
308 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
309 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
310 << T << SearchType;
311 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
312 << T;
313 } else if (ObjectTypePtr)
314 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000315 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000316 else {
317 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
318 diag::err_destructor_class_name);
319 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000320 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000321 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
322 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
323 Class->getNameAsString());
324 }
325 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000326
David Blaikieefdccaa2016-01-15 23:43:34 +0000327 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000328}
329
Richard Smithef2cd8f2017-02-08 20:39:08 +0000330ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
331 ParsedType ObjectType) {
332 if (DS.getTypeSpecType() == DeclSpec::TST_error)
333 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000334
Richard Smithef2cd8f2017-02-08 20:39:08 +0000335 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
336 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
337 return nullptr;
338 }
339
340 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
341 "unexpected type in getDestructorType");
342 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
343
344 // If we know the type of the object, check that the correct destructor
345 // type was named now; we can give better diagnostics this way.
346 QualType SearchType = GetTypeFromParser(ObjectType);
347 if (!SearchType.isNull() && !SearchType->isDependentType() &&
348 !Context.hasSameUnqualifiedType(T, SearchType)) {
David Blaikieecd8a942011-12-08 16:13:53 +0000349 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
350 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000351 return nullptr;
Richard Smithef2cd8f2017-02-08 20:39:08 +0000352 }
353
354 return ParsedType::make(T);
David Blaikieecd8a942011-12-08 16:13:53 +0000355}
356
Richard Smithd091dc12013-12-05 00:58:33 +0000357bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
358 const UnqualifiedId &Name) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000359 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
Richard Smithd091dc12013-12-05 00:58:33 +0000360
361 if (!SS.isValid())
362 return false;
363
364 switch (SS.getScopeRep()->getKind()) {
365 case NestedNameSpecifier::Identifier:
366 case NestedNameSpecifier::TypeSpec:
367 case NestedNameSpecifier::TypeSpecWithTemplate:
368 // Per C++11 [over.literal]p2, literal operators can only be declared at
369 // namespace scope. Therefore, this unqualified-id cannot name anything.
370 // Reject it early, because we have no AST representation for this in the
371 // case where the scope is dependent.
372 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
373 << SS.getScopeRep();
374 return true;
375
376 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000377 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000378 case NestedNameSpecifier::Namespace:
379 case NestedNameSpecifier::NamespaceAlias:
380 return false;
381 }
382
383 llvm_unreachable("unknown nested name specifier kind");
384}
385
Douglas Gregor9da64192010-04-26 22:37:10 +0000386/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000387ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000388 SourceLocation TypeidLoc,
389 TypeSourceInfo *Operand,
390 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000391 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000392 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000393 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000394 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000395 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000396 Qualifiers Quals;
397 QualType T
398 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
399 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000400 if (T->getAs<RecordType>() &&
401 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
402 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000403
David Majnemer6f3150a2014-11-21 21:09:12 +0000404 if (T->isVariablyModifiedType())
405 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
406
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000407 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
408 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000409}
410
411/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000412ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000413 SourceLocation TypeidLoc,
414 Expr *E,
415 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000416 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000417 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000418 if (E->getType()->isPlaceholderType()) {
419 ExprResult result = CheckPlaceholderExpr(E);
420 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000421 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000422 }
423
Douglas Gregor9da64192010-04-26 22:37:10 +0000424 QualType T = E->getType();
425 if (const RecordType *RecordT = T->getAs<RecordType>()) {
426 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
427 // C++ [expr.typeid]p3:
428 // [...] If the type of the expression is a class type, the class
429 // shall be completely-defined.
430 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
431 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000432
Douglas Gregor9da64192010-04-26 22:37:10 +0000433 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000434 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000435 // polymorphic class type [...] [the] expression is an unevaluated
436 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000437 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000438 // The subexpression is potentially evaluated; switch the context
439 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000440 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000441 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000442 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000443
444 // We require a vtable to query the type at run time.
445 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000446 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000447 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000448 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000449
Douglas Gregor9da64192010-04-26 22:37:10 +0000450 // C++ [expr.typeid]p4:
451 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000452 // cv-qualified type, the result of the typeid expression refers to a
453 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000454 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000455 Qualifiers Quals;
456 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
457 if (!Context.hasSameType(T, UnqualT)) {
458 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000459 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000460 }
461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000462
David Majnemer6f3150a2014-11-21 21:09:12 +0000463 if (E->getType()->isVariablyModifiedType())
464 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
465 << E->getType());
Richard Smith51ec0cf2017-02-21 01:17:38 +0000466 else if (!inTemplateInstantiation() &&
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000467 E->HasSideEffects(Context, WasEvaluated)) {
468 // The expression operand for typeid is in an unevaluated expression
469 // context, so side effects could result in unintended consequences.
470 Diag(E->getExprLoc(), WasEvaluated
471 ? diag::warn_side_effects_typeid
472 : diag::warn_side_effects_unevaluated_context);
473 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000474
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000475 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
476 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000477}
478
479/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000480ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000481Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
482 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000483 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000484 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000485 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000486
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000487 if (!CXXTypeInfoDecl) {
488 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
489 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
490 LookupQualifiedName(R, getStdNamespace());
491 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000492 // Microsoft's typeinfo doesn't have type_info in std but in the global
493 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000494 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000495 LookupQualifiedName(R, Context.getTranslationUnitDecl());
496 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
497 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000498 if (!CXXTypeInfoDecl)
499 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000501
Nico Weber1b7f39d2012-05-20 01:27:21 +0000502 if (!getLangOpts().RTTI) {
503 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
504 }
505
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000506 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507
Douglas Gregor9da64192010-04-26 22:37:10 +0000508 if (isType) {
509 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000510 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000511 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
512 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000513 if (T.isNull())
514 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000515
Douglas Gregor9da64192010-04-26 22:37:10 +0000516 if (!TInfo)
517 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000518
Douglas Gregor9da64192010-04-26 22:37:10 +0000519 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000520 }
Mike Stump11289f42009-09-09 15:08:12 +0000521
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000522 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000523 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000524}
525
David Majnemer1dbc7a72016-03-27 04:46:07 +0000526/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
527/// a single GUID.
528static void
529getUuidAttrOfType(Sema &SemaRef, QualType QT,
530 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
531 // Optionally remove one level of pointer, reference or array indirection.
532 const Type *Ty = QT.getTypePtr();
533 if (QT->isPointerType() || QT->isReferenceType())
534 Ty = QT->getPointeeType().getTypePtr();
535 else if (QT->isArrayType())
536 Ty = Ty->getBaseElementTypeUnsafe();
537
Reid Klecknere516eab2016-12-13 18:58:09 +0000538 const auto *TD = Ty->getAsTagDecl();
539 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000540 return;
541
Reid Klecknere516eab2016-12-13 18:58:09 +0000542 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000543 UuidAttrs.insert(Uuid);
544 return;
545 }
546
547 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000548 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000549 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
550 for (const TemplateArgument &TA : TAL.asArray()) {
551 const UuidAttr *UuidForTA = nullptr;
552 if (TA.getKind() == TemplateArgument::Type)
553 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
554 else if (TA.getKind() == TemplateArgument::Declaration)
555 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
556
557 if (UuidForTA)
558 UuidAttrs.insert(UuidForTA);
559 }
560 }
561}
562
Francois Pichet9f4f2072010-09-08 12:20:18 +0000563/// \brief Build a Microsoft __uuidof expression with a type operand.
564ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
565 SourceLocation TypeidLoc,
566 TypeSourceInfo *Operand,
567 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000568 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000569 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000570 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
571 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
572 if (UuidAttrs.empty())
573 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
574 if (UuidAttrs.size() > 1)
575 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000576 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000577 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000578
David Majnemer2041b462016-03-28 03:19:50 +0000579 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000580 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000581}
582
583/// \brief Build a Microsoft __uuidof expression with an expression operand.
584ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
585 SourceLocation TypeidLoc,
586 Expr *E,
587 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000588 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000589 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000590 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
591 UuidStr = "00000000-0000-0000-0000-000000000000";
592 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000593 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
594 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
595 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000596 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000597 if (UuidAttrs.size() > 1)
598 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000599 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000600 }
Francois Pichetb7577652010-12-27 01:32:00 +0000601 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000602
David Majnemer2041b462016-03-28 03:19:50 +0000603 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000604 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000605}
606
607/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
608ExprResult
609Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
610 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000611 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000612 if (!MSVCGuidDecl) {
613 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
614 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
615 LookupQualifiedName(R, Context.getTranslationUnitDecl());
616 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
617 if (!MSVCGuidDecl)
618 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619 }
620
Francois Pichet9f4f2072010-09-08 12:20:18 +0000621 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622
Francois Pichet9f4f2072010-09-08 12:20:18 +0000623 if (isType) {
624 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000625 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000626 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
627 &TInfo);
628 if (T.isNull())
629 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000630
Francois Pichet9f4f2072010-09-08 12:20:18 +0000631 if (!TInfo)
632 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
633
634 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
635 }
636
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000637 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000638 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
639}
640
Steve Naroff66356bd2007-09-16 14:56:35 +0000641/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000642ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000643Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000644 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000645 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000646 return new (Context)
647 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000648}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000649
Sebastian Redl576fd422009-05-10 18:38:11 +0000650/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000651ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000652Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000653 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000654}
655
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000656/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000657ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000658Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
659 bool IsThrownVarInScope = false;
660 if (Ex) {
661 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000662 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000663 // copy/move construction of a class object [...]
664 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000665 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000666 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000667 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000668 // innermost enclosing try-block (if there is one), the copy/move
669 // operation from the operand to the exception object (15.1) can be
670 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000671 // exception object
672 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
673 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
674 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
675 for( ; S; S = S->getParent()) {
676 if (S->isDeclScope(Var)) {
677 IsThrownVarInScope = true;
678 break;
679 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000680
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000681 if (S->getFlags() &
682 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
683 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
684 Scope::TryScope))
685 break;
686 }
687 }
688 }
689 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000690
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000691 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
692}
693
Simon Pilgrim75c26882016-09-30 14:25:09 +0000694ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000695 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000696 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000697 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000698 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000699 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000700
Justin Lebar2a8db342016-09-28 22:45:54 +0000701 // Exceptions aren't allowed in CUDA device code.
702 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000703 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
704 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000705
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000706 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
707 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
708
John Wiegley01296292011-04-08 18:41:53 +0000709 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000710 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
711 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000712 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000713
714 // Initialize the exception result. This implicitly weeds out
715 // abstract types or types with inaccessible copy constructors.
716
717 // C++0x [class.copymove]p31:
718 // When certain criteria are met, an implementation is allowed to omit the
719 // copy/move construction of a class object [...]
720 //
721 // - in a throw-expression, when the operand is the name of a
722 // non-volatile automatic object (other than a function or
723 // catch-clause
724 // parameter) whose scope does not extend beyond the end of the
725 // innermost enclosing try-block (if there is one), the copy/move
726 // operation from the operand to the exception object (15.1) can be
727 // omitted by constructing the automatic object directly into the
728 // exception object
729 const VarDecl *NRVOVariable = nullptr;
730 if (IsThrownVarInScope)
731 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
732
733 InitializedEntity Entity = InitializedEntity::InitializeException(
734 OpLoc, ExceptionObjectTy,
735 /*NRVO=*/NRVOVariable != nullptr);
736 ExprResult Res = PerformMoveOrCopyInitialization(
737 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
738 if (Res.isInvalid())
739 return ExprError();
740 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000741 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000742
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000743 return new (Context)
744 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000745}
746
David Majnemere7a818f2015-03-06 18:53:55 +0000747static void
748collectPublicBases(CXXRecordDecl *RD,
749 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
750 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
751 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
752 bool ParentIsPublic) {
753 for (const CXXBaseSpecifier &BS : RD->bases()) {
754 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
755 bool NewSubobject;
756 // Virtual bases constitute the same subobject. Non-virtual bases are
757 // always distinct subobjects.
758 if (BS.isVirtual())
759 NewSubobject = VBases.insert(BaseDecl).second;
760 else
761 NewSubobject = true;
762
763 if (NewSubobject)
764 ++SubobjectsSeen[BaseDecl];
765
766 // Only add subobjects which have public access throughout the entire chain.
767 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
768 if (PublicPath)
769 PublicSubobjectsSeen.insert(BaseDecl);
770
771 // Recurse on to each base subobject.
772 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
773 PublicPath);
774 }
775}
776
777static void getUnambiguousPublicSubobjects(
778 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
779 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
780 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
781 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
782 SubobjectsSeen[RD] = 1;
783 PublicSubobjectsSeen.insert(RD);
784 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
785 /*ParentIsPublic=*/true);
786
787 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
788 // Skip ambiguous objects.
789 if (SubobjectsSeen[PublicSubobject] > 1)
790 continue;
791
792 Objects.push_back(PublicSubobject);
793 }
794}
795
Sebastian Redl4de47b42009-04-27 20:27:31 +0000796/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000797bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
798 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000799 // If the type of the exception would be an incomplete type or a pointer
800 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000801 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000802 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000803 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000804 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000805 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000806 }
807 if (!isPointer || !Ty->isVoidType()) {
808 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000809 isPointer ? diag::err_throw_incomplete_ptr
810 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000811 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000812 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000813
David Majnemerd09a51c2015-03-03 01:50:05 +0000814 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000815 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000816 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000817 }
818
Eli Friedman91a3d272010-06-03 20:39:03 +0000819 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000820 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
821 if (!RD)
822 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000823
Douglas Gregor88d292c2010-05-13 16:44:06 +0000824 // If we are throwing a polymorphic class type or pointer thereof,
825 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000826 MarkVTableUsed(ThrowLoc, RD);
827
Eli Friedman36ebbec2010-10-12 20:32:36 +0000828 // If a pointer is thrown, the referenced object will not be destroyed.
829 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000830 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000831
Richard Smitheec915d62012-02-18 04:13:32 +0000832 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000833 if (!RD->hasIrrelevantDestructor()) {
834 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
835 MarkFunctionReferenced(E->getExprLoc(), Destructor);
836 CheckDestructorAccess(E->getExprLoc(), Destructor,
837 PDiag(diag::err_access_dtor_exception) << Ty);
838 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000839 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000840 }
841 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000842
David Majnemerdfa6d202015-03-11 18:36:39 +0000843 // The MSVC ABI creates a list of all types which can catch the exception
844 // object. This list also references the appropriate copy constructor to call
845 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000846 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000847 // We are only interested in the public, unambiguous bases contained within
848 // the exception object. Bases which are ambiguous or otherwise
849 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000850 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
851 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000852
David Majnemere7a818f2015-03-06 18:53:55 +0000853 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000854 // Attempt to lookup the copy constructor. Various pieces of machinery
855 // will spring into action, like template instantiation, which means this
856 // cannot be a simple walk of the class's decls. Instead, we must perform
857 // lookup and overload resolution.
858 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
859 if (!CD)
860 continue;
861
862 // Mark the constructor referenced as it is used by this throw expression.
863 MarkFunctionReferenced(E->getExprLoc(), CD);
864
865 // Skip this copy constructor if it is trivial, we don't need to record it
866 // in the catchable type data.
867 if (CD->isTrivial())
868 continue;
869
870 // The copy constructor is non-trivial, create a mapping from this class
871 // type to this constructor.
872 // N.B. The selection of copy constructor is not sensitive to this
873 // particular throw-site. Lookup will be performed at the catch-site to
874 // ensure that the copy constructor is, in fact, accessible (via
875 // friendship or any other means).
876 Context.addCopyConstructorForExceptionObject(Subobject, CD);
877
878 // We don't keep the instantiated default argument expressions around so
879 // we must rebuild them here.
880 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000881 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
882 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000883 }
884 }
885 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000886
David Majnemerba3e5ec2015-03-13 18:26:17 +0000887 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000888}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000889
Faisal Vali67b04462016-06-11 16:41:54 +0000890static QualType adjustCVQualifiersForCXXThisWithinLambda(
891 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
892 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
893
894 QualType ClassType = ThisTy->getPointeeType();
895 LambdaScopeInfo *CurLSI = nullptr;
896 DeclContext *CurDC = CurSemaContext;
897
898 // Iterate through the stack of lambdas starting from the innermost lambda to
899 // the outermost lambda, checking if '*this' is ever captured by copy - since
900 // that could change the cv-qualifiers of the '*this' object.
901 // The object referred to by '*this' starts out with the cv-qualifiers of its
902 // member function. We then start with the innermost lambda and iterate
903 // outward checking to see if any lambda performs a by-copy capture of '*this'
904 // - and if so, any nested lambda must respect the 'constness' of that
905 // capturing lamdbda's call operator.
906 //
907
Faisal Vali999f27e2017-05-02 20:56:34 +0000908 // Since the FunctionScopeInfo stack is representative of the lexical
909 // nesting of the lambda expressions during initial parsing (and is the best
910 // place for querying information about captures about lambdas that are
911 // partially processed) and perhaps during instantiation of function templates
912 // that contain lambda expressions that need to be transformed BUT not
913 // necessarily during instantiation of a nested generic lambda's function call
914 // operator (which might even be instantiated at the end of the TU) - at which
915 // time the DeclContext tree is mature enough to query capture information
916 // reliably - we use a two pronged approach to walk through all the lexically
917 // enclosing lambda expressions:
918 //
919 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
920 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
921 // enclosed by the call-operator of the LSI below it on the stack (while
922 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
923 // the stack represents the innermost lambda.
924 //
925 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
926 // represents a lambda's call operator. If it does, we must be instantiating
927 // a generic lambda's call operator (represented by the Current LSI, and
928 // should be the only scenario where an inconsistency between the LSI and the
929 // DeclContext should occur), so climb out the DeclContexts if they
930 // represent lambdas, while querying the corresponding closure types
931 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +0000932
Faisal Vali999f27e2017-05-02 20:56:34 +0000933 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +0000934 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +0000935 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
936 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
937 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +0000938 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
939 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000940
941 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +0000942 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000943
Faisal Vali67b04462016-06-11 16:41:54 +0000944 auto C = CurLSI->getCXXThisCapture();
945
946 if (C.isCopyCapture()) {
947 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
948 if (CurLSI->CallOperator->isConst())
949 ClassType.addConst();
950 return ASTCtx.getPointerType(ClassType);
951 }
952 }
Faisal Vali999f27e2017-05-02 20:56:34 +0000953
954 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
955 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +0000956 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +0000957 assert(CurLSI && "While computing 'this' capture-type for a generic "
958 "lambda, we must have a corresponding LambdaScopeInfo");
959 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
960 "While computing 'this' capture-type for a generic lambda, when we "
961 "run out of enclosing LSI's, yet the enclosing DC is a "
962 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
963 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +0000964 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +0000965
Faisal Vali67b04462016-06-11 16:41:54 +0000966 auto IsThisCaptured =
967 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
968 IsConst = false;
969 IsByCopy = false;
970 for (auto &&C : Closure->captures()) {
971 if (C.capturesThis()) {
972 if (C.getCaptureKind() == LCK_StarThis)
973 IsByCopy = true;
974 if (Closure->getLambdaCallOperator()->isConst())
975 IsConst = true;
976 return true;
977 }
978 }
979 return false;
980 };
981
982 bool IsByCopyCapture = false;
983 bool IsConstCapture = false;
984 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
985 while (Closure &&
986 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
987 if (IsByCopyCapture) {
988 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
989 if (IsConstCapture)
990 ClassType.addConst();
991 return ASTCtx.getPointerType(ClassType);
992 }
993 Closure = isLambdaCallOperator(Closure->getParent())
994 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
995 : nullptr;
996 }
997 }
998 return ASTCtx.getPointerType(ClassType);
999}
1000
Eli Friedman73a04092012-01-07 04:59:52 +00001001QualType Sema::getCurrentThisType() {
1002 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001003 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001004
Richard Smith938f40b2011-06-11 17:19:42 +00001005 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1006 if (method && method->isInstance())
1007 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001008 }
Faisal Validc6b5962016-03-21 09:25:37 +00001009
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001010 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001011 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001012
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001013 assert(isa<CXXRecordDecl>(DC) &&
1014 "Trying to get 'this' type from static method?");
1015
1016 // This is a lambda call operator that is being instantiated as a default
1017 // initializer. DC must point to the enclosing class type, so we can recover
1018 // the 'this' type from it.
1019
1020 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1021 // There are no cv-qualifiers for 'this' within default initializers,
1022 // per [expr.prim.general]p4.
1023 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001024 }
Faisal Vali67b04462016-06-11 16:41:54 +00001025
1026 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1027 // might need to be adjusted if the lambda or any of its enclosing lambda's
1028 // captures '*this' by copy.
1029 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1030 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1031 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001032 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001033}
1034
Simon Pilgrim75c26882016-09-30 14:25:09 +00001035Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001036 Decl *ContextDecl,
1037 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001038 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001039 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1040{
1041 if (!Enabled || !ContextDecl)
1042 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001043
1044 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001045 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1046 Record = Template->getTemplatedDecl();
1047 else
1048 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001049
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001050 // We care only for CVR qualifiers here, so cut everything else.
1051 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001052 S.CXXThisTypeOverride
1053 = S.Context.getPointerType(
1054 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001055
Douglas Gregor3024f072012-04-16 07:05:22 +00001056 this->Enabled = true;
1057}
1058
1059
1060Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1061 if (Enabled) {
1062 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1063 }
1064}
1065
Faisal Validc6b5962016-03-21 09:25:37 +00001066static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1067 QualType ThisTy, SourceLocation Loc,
1068 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001069
Faisal Vali67b04462016-06-11 16:41:54 +00001070 QualType AdjustedThisTy = ThisTy;
1071 // The type of the corresponding data member (not a 'this' pointer if 'by
1072 // copy').
1073 QualType CaptureThisFieldTy = ThisTy;
1074 if (ByCopy) {
1075 // If we are capturing the object referred to by '*this' by copy, ignore any
1076 // cv qualifiers inherited from the type of the member function for the type
1077 // of the closure-type's corresponding data member and any use of 'this'.
1078 CaptureThisFieldTy = ThisTy->getPointeeType();
1079 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1080 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1081 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001082
Faisal Vali67b04462016-06-11 16:41:54 +00001083 FieldDecl *Field = FieldDecl::Create(
1084 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1085 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1086 ICIS_NoInit);
1087
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001088 Field->setImplicit(true);
1089 Field->setAccess(AS_private);
1090 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001091 Expr *This =
1092 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001093 if (ByCopy) {
1094 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1095 UO_Deref,
1096 This).get();
1097 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001098 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001099 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1100 InitializationSequence Init(S, Entity, InitKind, StarThis);
1101 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1102 if (ER.isInvalid()) return nullptr;
1103 return ER.get();
1104 }
1105 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001106}
1107
Simon Pilgrim75c26882016-09-30 14:25:09 +00001108bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001109 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1110 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001111 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001112 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001113 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001114
Faisal Validc6b5962016-03-21 09:25:37 +00001115 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001116
Faisal Valia17d19f2013-11-07 05:17:06 +00001117 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
Faisal Validc6b5962016-03-21 09:25:37 +00001118 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001119
Simon Pilgrim75c26882016-09-30 14:25:09 +00001120 // Check that we can capture the *enclosing object* (referred to by '*this')
1121 // by the capturing-entity/closure (lambda/block/etc) at
1122 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1123
1124 // Note: The *enclosing object* can only be captured by-value by a
1125 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001126 // [*this] { ... }.
1127 // Every other capture of the *enclosing object* results in its by-reference
1128 // capture.
1129
1130 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1131 // stack), we can capture the *enclosing object* only if:
1132 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1133 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001134 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001135 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001136 // -- or, there is some enclosing closure 'E' that has already captured the
1137 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001138 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001139 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001140 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001141
1142
Faisal Validc6b5962016-03-21 09:25:37 +00001143 unsigned NumCapturingClosures = 0;
Faisal Valia17d19f2013-11-07 05:17:06 +00001144 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001145 if (CapturingScopeInfo *CSI =
1146 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1147 if (CSI->CXXThisCaptureIndex != 0) {
1148 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001149 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001150 break;
1151 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001152 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1153 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1154 // This context can't implicitly capture 'this'; fail out.
1155 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001156 Diag(Loc, diag::err_this_capture)
1157 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001158 return true;
1159 }
Eli Friedman20139d32012-01-11 02:36:31 +00001160 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001161 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001162 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001163 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001164 (Explicit && idx == MaxFunctionScopesIndex)) {
1165 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1166 // iteration through can be an explicit capture, all enclosing closures,
1167 // if any, must perform implicit captures.
1168
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001169 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001170 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001171 continue;
1172 }
Eli Friedman20139d32012-01-11 02:36:31 +00001173 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001174 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001175 Diag(Loc, diag::err_this_capture)
1176 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001177 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001178 }
Eli Friedman73a04092012-01-07 04:59:52 +00001179 break;
1180 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001181 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001182
1183 // If we got here, then the closure at MaxFunctionScopesIndex on the
1184 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1185 // (including implicit by-reference captures in any enclosing closures).
1186
1187 // In the loop below, respect the ByCopy flag only for the closure requesting
1188 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001189 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001190 // implicitly capturing the *enclosing object* by reference (see loop
1191 // above)).
1192 assert((!ByCopy ||
1193 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1194 "Only a lambda can capture the enclosing object (referred to by "
1195 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001196 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1197 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001198 QualType ThisTy = getCurrentThisType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00001199 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
Faisal Validc6b5962016-03-21 09:25:37 +00001200 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001201 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001202 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001203
Faisal Validc6b5962016-03-21 09:25:37 +00001204 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1205 // For lambda expressions, build a field and an initializing expression,
1206 // and capture the *enclosing object* by copy only if this is the first
1207 // iteration.
1208 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1209 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001210
Faisal Validc6b5962016-03-21 09:25:37 +00001211 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001212 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001213 ThisExpr =
1214 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1215 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001216
Faisal Validc6b5962016-03-21 09:25:37 +00001217 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001218 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001219 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001220 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001221}
1222
Richard Smith938f40b2011-06-11 17:19:42 +00001223ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001224 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1225 /// is a non-lvalue expression whose value is the address of the object for
1226 /// which the function is called.
1227
Douglas Gregor09deffa2011-10-18 16:47:30 +00001228 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001229 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001230
Eli Friedman73a04092012-01-07 04:59:52 +00001231 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001232 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001233}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001234
Douglas Gregor3024f072012-04-16 07:05:22 +00001235bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1236 // If we're outside the body of a member function, then we'll have a specified
1237 // type for 'this'.
1238 if (CXXThisTypeOverride.isNull())
1239 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001240
Douglas Gregor3024f072012-04-16 07:05:22 +00001241 // Determine whether we're looking into a class that's currently being
1242 // defined.
1243 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1244 return Class && Class->isBeingDefined();
1245}
1246
John McCalldadc5752010-08-24 06:29:42 +00001247ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001248Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001249 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001250 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001251 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001252 if (!TypeRep)
1253 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001254
John McCall97513962010-01-15 18:39:57 +00001255 TypeSourceInfo *TInfo;
1256 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1257 if (!TInfo)
1258 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001259
Richard Smithb8c414c2016-06-30 20:24:30 +00001260 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1261 // Avoid creating a non-type-dependent expression that contains typos.
1262 // Non-type-dependent expressions are liable to be discarded without
1263 // checking for embedded typos.
1264 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1265 !Result.get()->isTypeDependent())
1266 Result = CorrectDelayedTyposInExpr(Result.get());
1267 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001268}
1269
1270/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1271/// Can be interpreted either as function-style casting ("int(x)")
1272/// or class type construction ("ClassType(x,y,z)")
1273/// or creation of a value-initialized type ("int()").
1274ExprResult
1275Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1276 SourceLocation LParenLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001277 MultiExprArg Exprs,
Douglas Gregor2b88c112010-09-08 00:15:04 +00001278 SourceLocation RParenLoc) {
1279 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001280 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001281
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001282 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001283 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1284 RParenLoc);
Douglas Gregor0950e412009-03-13 21:01:28 +00001285 }
1286
Sebastian Redld74dd492012-02-12 18:41:05 +00001287 bool ListInitialization = LParenLoc.isInvalid();
Richard Smith600b5262017-01-26 20:40:47 +00001288 assert((!ListInitialization ||
1289 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1290 "List initialization must have initializer list as expression.");
Sebastian Redld74dd492012-02-12 18:41:05 +00001291 SourceRange FullRange = SourceRange(TyBeginLoc,
1292 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1293
Richard Smith60437622017-02-09 19:17:44 +00001294 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1295 InitializationKind Kind =
1296 Exprs.size()
1297 ? ListInitialization
1298 ? InitializationKind::CreateDirectList(TyBeginLoc)
1299 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc,
1300 RParenLoc)
1301 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1302
1303 // C++1z [expr.type.conv]p1:
1304 // If the type is a placeholder for a deduced class type, [...perform class
1305 // template argument deduction...]
1306 DeducedType *Deduced = Ty->getContainedDeducedType();
1307 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1308 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1309 Kind, Exprs);
1310 if (Ty.isNull())
1311 return ExprError();
1312 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1313 }
1314
Douglas Gregordd04d332009-01-16 18:33:17 +00001315 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001316 // If the expression list is a parenthesized single expression, the type
1317 // conversion expression is equivalent (in definedness, and if defined in
1318 // meaning) to the corresponding cast expression.
1319 if (Exprs.size() == 1 && !ListInitialization &&
1320 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001321 Expr *Arg = Exprs[0];
Richard Smith60437622017-02-09 19:17:44 +00001322 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001323 }
1324
Richard Smith49a6b6e2017-03-24 01:14:25 +00001325 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001326 QualType ElemTy = Ty;
1327 if (Ty->isArrayType()) {
1328 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001329 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1330 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001331 ElemTy = Context.getBaseElementType(Ty);
1332 }
1333
Richard Smith49a6b6e2017-03-24 01:14:25 +00001334 // There doesn't seem to be an explicit rule against this but sanity demands
1335 // we only construct objects with object types.
1336 if (Ty->isFunctionType())
1337 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1338 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001339
Richard Smith49a6b6e2017-03-24 01:14:25 +00001340 // C++17 [expr.type.conv]p2:
1341 // If the type is cv void and the initializer is (), the expression is a
1342 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001343 if (!Ty->isVoidType() &&
1344 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001345 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001346 return ExprError();
1347
Richard Smith49a6b6e2017-03-24 01:14:25 +00001348 // Otherwise, the expression is a prvalue of the specified type whose
1349 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001350 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1351 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001352
Richard Smith49a6b6e2017-03-24 01:14:25 +00001353 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001354 return Result;
1355
1356 Expr *Inner = Result.get();
1357 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1358 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001359 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1360 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001361 // If we created a CXXTemporaryObjectExpr, that node also represents the
1362 // functional cast. Otherwise, create an explicit cast to represent
1363 // the syntactic form of a functional-style cast that was used here.
1364 //
1365 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1366 // would give a more consistent AST representation than using a
1367 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1368 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001369 QualType ResultType = Result.get()->getType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001370 Result = CXXFunctionalCastExpr::Create(
Richard Smith60437622017-02-09 19:17:44 +00001371 Context, ResultType, Expr::getValueKindForType(Ty), TInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001372 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
Sebastian Redl2b80af42012-02-13 19:55:43 +00001373 }
1374
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001375 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001376}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001377
Richard Smithb2f0f052016-10-10 18:54:32 +00001378/// \brief Determine whether the given function is a non-placement
1379/// deallocation function.
1380static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001381 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1382 return Method->isUsualDeallocationFunction();
1383
1384 if (FD->getOverloadedOperator() != OO_Delete &&
1385 FD->getOverloadedOperator() != OO_Array_Delete)
1386 return false;
1387
1388 unsigned UsualParams = 1;
1389
1390 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1391 S.Context.hasSameUnqualifiedType(
1392 FD->getParamDecl(UsualParams)->getType(),
1393 S.Context.getSizeType()))
1394 ++UsualParams;
1395
1396 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1397 S.Context.hasSameUnqualifiedType(
1398 FD->getParamDecl(UsualParams)->getType(),
1399 S.Context.getTypeDeclType(S.getStdAlignValT())))
1400 ++UsualParams;
1401
1402 return UsualParams == FD->getNumParams();
1403}
1404
1405namespace {
1406 struct UsualDeallocFnInfo {
1407 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001408 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001409 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smith5b349582017-10-13 01:55:36 +00001410 Destroying(false), HasSizeT(false), HasAlignValT(false),
1411 CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001412 // A function template declaration is never a usual deallocation function.
1413 if (!FD)
1414 return;
Richard Smith5b349582017-10-13 01:55:36 +00001415 unsigned NumBaseParams = 1;
1416 if (FD->isDestroyingOperatorDelete()) {
1417 Destroying = true;
1418 ++NumBaseParams;
1419 }
1420 if (FD->getNumParams() == NumBaseParams + 2)
Richard Smithb2f0f052016-10-10 18:54:32 +00001421 HasAlignValT = HasSizeT = true;
Richard Smith5b349582017-10-13 01:55:36 +00001422 else if (FD->getNumParams() == NumBaseParams + 1) {
1423 HasSizeT = FD->getParamDecl(NumBaseParams)->getType()->isIntegerType();
Richard Smithb2f0f052016-10-10 18:54:32 +00001424 HasAlignValT = !HasSizeT;
1425 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001426
1427 // In CUDA, determine how much we'd like / dislike to call this.
1428 if (S.getLangOpts().CUDA)
1429 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1430 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001431 }
1432
1433 operator bool() const { return FD; }
1434
Richard Smithf75dcbe2016-10-11 00:21:10 +00001435 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1436 bool WantAlign) const {
Richard Smith5b349582017-10-13 01:55:36 +00001437 // C++ P0722:
1438 // A destroying operator delete is preferred over a non-destroying
1439 // operator delete.
1440 if (Destroying != Other.Destroying)
1441 return Destroying;
1442
Richard Smithf75dcbe2016-10-11 00:21:10 +00001443 // C++17 [expr.delete]p10:
1444 // If the type has new-extended alignment, a function with a parameter
1445 // of type std::align_val_t is preferred; otherwise a function without
1446 // such a parameter is preferred
1447 if (HasAlignValT != Other.HasAlignValT)
1448 return HasAlignValT == WantAlign;
1449
1450 if (HasSizeT != Other.HasSizeT)
1451 return HasSizeT == WantSize;
1452
1453 // Use CUDA call preference as a tiebreaker.
1454 return CUDAPref > Other.CUDAPref;
1455 }
1456
Richard Smithb2f0f052016-10-10 18:54:32 +00001457 DeclAccessPair Found;
1458 FunctionDecl *FD;
Richard Smith5b349582017-10-13 01:55:36 +00001459 bool Destroying, HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001460 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001461 };
1462}
1463
1464/// Determine whether a type has new-extended alignment. This may be called when
1465/// the type is incomplete (for a delete-expression with an incomplete pointee
1466/// type), in which case it will conservatively return false if the alignment is
1467/// not known.
1468static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1469 return S.getLangOpts().AlignedAllocation &&
1470 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1471 S.getASTContext().getTargetInfo().getNewAlign();
1472}
1473
1474/// Select the correct "usual" deallocation function to use from a selection of
1475/// deallocation functions (either global or class-scope).
1476static UsualDeallocFnInfo resolveDeallocationOverload(
1477 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1478 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1479 UsualDeallocFnInfo Best;
1480
Richard Smithb2f0f052016-10-10 18:54:32 +00001481 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001482 UsualDeallocFnInfo Info(S, I.getPair());
1483 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1484 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001485 continue;
1486
1487 if (!Best) {
1488 Best = Info;
1489 if (BestFns)
1490 BestFns->push_back(Info);
1491 continue;
1492 }
1493
Richard Smithf75dcbe2016-10-11 00:21:10 +00001494 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001495 continue;
1496
1497 // If more than one preferred function is found, all non-preferred
1498 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001499 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001500 BestFns->clear();
1501
1502 Best = Info;
1503 if (BestFns)
1504 BestFns->push_back(Info);
1505 }
1506
1507 return Best;
1508}
1509
1510/// Determine whether a given type is a class for which 'delete[]' would call
1511/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1512/// we need to store the array size (even if the type is
1513/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001514static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1515 QualType allocType) {
1516 const RecordType *record =
1517 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1518 if (!record) return false;
1519
1520 // Try to find an operator delete[] in class scope.
1521
1522 DeclarationName deleteName =
1523 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1524 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1525 S.LookupQualifiedName(ops, record->getDecl());
1526
1527 // We're just doing this for information.
1528 ops.suppressDiagnostics();
1529
1530 // Very likely: there's no operator delete[].
1531 if (ops.empty()) return false;
1532
1533 // If it's ambiguous, it should be illegal to call operator delete[]
1534 // on this thing, so it doesn't matter if we allocate extra space or not.
1535 if (ops.isAmbiguous()) return false;
1536
Richard Smithb2f0f052016-10-10 18:54:32 +00001537 // C++17 [expr.delete]p10:
1538 // If the deallocation functions have class scope, the one without a
1539 // parameter of type std::size_t is selected.
1540 auto Best = resolveDeallocationOverload(
1541 S, ops, /*WantSize*/false,
1542 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1543 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001544}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001545
Sebastian Redld74dd492012-02-12 18:41:05 +00001546/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001547///
Sebastian Redld74dd492012-02-12 18:41:05 +00001548/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001549/// @code new (memory) int[size][4] @endcode
1550/// or
1551/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001552///
1553/// \param StartLoc The first location of the expression.
1554/// \param UseGlobal True if 'new' was prefixed with '::'.
1555/// \param PlacementLParen Opening paren of the placement arguments.
1556/// \param PlacementArgs Placement new arguments.
1557/// \param PlacementRParen Closing paren of the placement arguments.
1558/// \param TypeIdParens If the type is in parens, the source range.
1559/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001560/// \param Initializer The initializing expression or initializer-list, or null
1561/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001562ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001563Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001564 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001565 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001566 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001567 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001568 // If the specified type is an array, unwrap it and save the expression.
1569 if (D.getNumTypeObjects() > 0 &&
1570 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001571 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001572 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001573 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1574 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001575 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001576 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1577 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001578 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001579 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1580 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001581
Sebastian Redl351bb782008-12-02 14:43:59 +00001582 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001583 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001584 }
1585
Douglas Gregor73341c42009-09-11 00:18:58 +00001586 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001587 if (ArraySize) {
1588 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001589 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1590 break;
1591
1592 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1593 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001594 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001595 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001596 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1597 // shall be a converted constant expression (5.19) of type std::size_t
1598 // and shall evaluate to a strictly positive value.
1599 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1600 assert(IntWidth && "Builtin type of size 0?");
1601 llvm::APSInt Value(IntWidth);
1602 Array.NumElts
1603 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1604 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001605 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001606 } else {
1607 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001608 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001609 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001610 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001611 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001612 if (!Array.NumElts)
1613 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001614 }
1615 }
1616 }
1617 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001618
Craig Topperc3ec1492014-05-26 06:22:03 +00001619 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001620 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001621 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001622 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001623
Sebastian Redl6047f072012-02-16 12:22:20 +00001624 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001625 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001626 DirectInitRange = List->getSourceRange();
1627
David Blaikie7b97aef2012-11-07 00:12:38 +00001628 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001629 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001630 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001631 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001632 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001633 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001634 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001635 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001636 DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001637 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001638}
1639
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001640static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1641 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001642 if (!Init)
1643 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001644 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1645 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001646 if (isa<ImplicitValueInitExpr>(Init))
1647 return true;
1648 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1649 return !CCE->isListInitialization() &&
1650 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001651 else if (Style == CXXNewExpr::ListInit) {
1652 assert(isa<InitListExpr>(Init) &&
1653 "Shouldn't create list CXXConstructExprs for arrays.");
1654 return true;
1655 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001656 return false;
1657}
1658
Akira Hatanakacae83f72017-06-29 18:48:40 +00001659// Emit a diagnostic if an aligned allocation/deallocation function that is not
1660// implemented in the standard library is selected.
1661static void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1662 SourceLocation Loc, bool IsDelete,
1663 Sema &S) {
1664 if (!S.getLangOpts().AlignedAllocationUnavailable)
1665 return;
1666
1667 // Return if there is a definition.
1668 if (FD.isDefined())
1669 return;
1670
1671 bool IsAligned = false;
1672 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) {
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001673 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
1674 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1675 S.getASTContext().getTargetInfo().getPlatformName());
1676
Akira Hatanakacae83f72017-06-29 18:48:40 +00001677 S.Diag(Loc, diag::warn_aligned_allocation_unavailable)
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001678 << IsDelete << FD.getType().getAsString() << OSName
1679 << alignedAllocMinVersion(T.getOS()).getAsString();
Akira Hatanakacae83f72017-06-29 18:48:40 +00001680 S.Diag(Loc, diag::note_silence_unligned_allocation_unavailable);
1681 }
1682}
1683
John McCalldadc5752010-08-24 06:29:42 +00001684ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001685Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001686 SourceLocation PlacementLParen,
1687 MultiExprArg PlacementArgs,
1688 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001689 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001690 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001691 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001692 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001693 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001694 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001695 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001696 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001697
Sebastian Redl6047f072012-02-16 12:22:20 +00001698 CXXNewExpr::InitializationStyle initStyle;
1699 if (DirectInitRange.isValid()) {
1700 assert(Initializer && "Have parens but no initializer.");
1701 initStyle = CXXNewExpr::CallInit;
1702 } else if (Initializer && isa<InitListExpr>(Initializer))
1703 initStyle = CXXNewExpr::ListInit;
1704 else {
1705 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1706 isa<CXXConstructExpr>(Initializer)) &&
1707 "Initializer expression that cannot have been implicitly created.");
1708 initStyle = CXXNewExpr::NoInit;
1709 }
1710
1711 Expr **Inits = &Initializer;
1712 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001713 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1714 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1715 Inits = List->getExprs();
1716 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001717 }
1718
Richard Smith60437622017-02-09 19:17:44 +00001719 // C++11 [expr.new]p15:
1720 // A new-expression that creates an object of type T initializes that
1721 // object as follows:
1722 InitializationKind Kind
1723 // - If the new-initializer is omitted, the object is default-
1724 // initialized (8.5); if no initialization is performed,
1725 // the object has indeterminate value
1726 = initStyle == CXXNewExpr::NoInit
1727 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1728 // - Otherwise, the new-initializer is interpreted according to the
1729 // initialization rules of 8.5 for direct-initialization.
1730 : initStyle == CXXNewExpr::ListInit
1731 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1732 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1733 DirectInitRange.getBegin(),
1734 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001735
Richard Smith60437622017-02-09 19:17:44 +00001736 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1737 auto *Deduced = AllocType->getContainedDeducedType();
1738 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1739 if (ArraySize)
1740 return ExprError(Diag(ArraySize->getExprLoc(),
1741 diag::err_deduced_class_template_compound_type)
1742 << /*array*/ 2 << ArraySize->getSourceRange());
1743
1744 InitializedEntity Entity
1745 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1746 AllocType = DeduceTemplateSpecializationFromInitializer(
1747 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1748 if (AllocType.isNull())
1749 return ExprError();
1750 } else if (Deduced) {
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001751 bool Braced = (initStyle == CXXNewExpr::ListInit);
1752 if (NumInits == 1) {
1753 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1754 Inits = p->getInits();
1755 NumInits = p->getNumInits();
1756 Braced = true;
1757 }
1758 }
1759
Sebastian Redl6047f072012-02-16 12:22:20 +00001760 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001761 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1762 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001763 if (NumInits > 1) {
1764 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001765 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001766 diag::err_auto_new_ctor_multiple_expressions)
1767 << AllocType << TypeRange);
1768 }
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001769 if (Braced && !getLangOpts().CPlusPlus17)
1770 Diag(Initializer->getLocStart(), diag::ext_auto_new_list_init)
1771 << AllocType << TypeRange;
Sebastian Redl6047f072012-02-16 12:22:20 +00001772 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001773 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001774 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001775 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001776 << AllocType << Deduce->getType()
1777 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001778 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001779 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001780 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001781 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001782
Douglas Gregorcda95f42010-05-16 16:01:03 +00001783 // Per C++0x [expr.new]p5, the type being constructed may be a
1784 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001785 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001786 if (const ConstantArrayType *Array
1787 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001788 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1789 Context.getSizeType(),
1790 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001791 AllocType = Array->getElementType();
1792 }
1793 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001794
Douglas Gregor3999e152010-10-06 16:00:31 +00001795 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1796 return ExprError();
1797
Craig Topperc3ec1492014-05-26 06:22:03 +00001798 if (initStyle == CXXNewExpr::ListInit &&
1799 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001800 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1801 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001802 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001803 }
1804
Simon Pilgrim75c26882016-09-30 14:25:09 +00001805 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001806 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001807 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1808 AllocType->isObjCLifetimeType()) {
1809 AllocType = Context.getLifetimeQualifiedType(AllocType,
1810 AllocType->getObjCARCImplicitLifetime());
1811 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001812
John McCall31168b02011-06-15 23:02:42 +00001813 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001814
John McCall5e77d762013-04-16 07:28:30 +00001815 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1816 ExprResult result = CheckPlaceholderExpr(ArraySize);
1817 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001818 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001819 }
Richard Smith8dd34252012-02-04 07:07:42 +00001820 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1821 // integral or enumeration type with a non-negative value."
1822 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1823 // enumeration type, or a class type for which a single non-explicit
1824 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001825 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001826 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001827 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001828 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001829 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001830 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001831 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1832
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001833 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1834 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001835
Simon Pilgrim75c26882016-09-30 14:25:09 +00001836 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001837 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001838 // Diagnose the compatibility of this conversion.
1839 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1840 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001841 } else {
1842 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1843 protected:
1844 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001845
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001846 public:
1847 SizeConvertDiagnoser(Expr *ArraySize)
1848 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1849 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001850
1851 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1852 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001853 return S.Diag(Loc, diag::err_array_size_not_integral)
1854 << S.getLangOpts().CPlusPlus11 << T;
1855 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001856
1857 SemaDiagnosticBuilder diagnoseIncomplete(
1858 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001859 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1860 << T << ArraySize->getSourceRange();
1861 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001862
1863 SemaDiagnosticBuilder diagnoseExplicitConv(
1864 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001865 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1866 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001867
1868 SemaDiagnosticBuilder noteExplicitConv(
1869 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001870 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1871 << ConvTy->isEnumeralType() << ConvTy;
1872 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001873
1874 SemaDiagnosticBuilder diagnoseAmbiguous(
1875 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001876 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1877 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001878
1879 SemaDiagnosticBuilder noteAmbiguous(
1880 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001881 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1882 << ConvTy->isEnumeralType() << ConvTy;
1883 }
Richard Smithccc11812013-05-21 19:05:48 +00001884
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001885 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1886 QualType T,
1887 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001888 return S.Diag(Loc,
1889 S.getLangOpts().CPlusPlus11
1890 ? diag::warn_cxx98_compat_array_size_conversion
1891 : diag::ext_array_size_conversion)
1892 << T << ConvTy->isEnumeralType() << ConvTy;
1893 }
1894 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001895
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001896 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1897 SizeDiagnoser);
1898 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001899 if (ConvertedSize.isInvalid())
1900 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001901
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001902 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001903 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001904
Douglas Gregor0bf31402010-10-08 23:50:27 +00001905 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001906 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001907
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001908 // C++98 [expr.new]p7:
1909 // The expression in a direct-new-declarator shall have integral type
1910 // with a non-negative value.
1911 //
Richard Smith0511d232016-10-05 22:41:02 +00001912 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1913 // per CWG1464. Otherwise, if it's not a constant, we must have an
1914 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001915 if (!ArraySize->isValueDependent()) {
1916 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001917 // We've already performed any required implicit conversion to integer or
1918 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001919 // FIXME: Per CWG1464, we are required to check the value prior to
1920 // converting to size_t. This will never find a negative array size in
1921 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001922 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001923 if (Value.isSigned() && Value.isNegative()) {
1924 return ExprError(Diag(ArraySize->getLocStart(),
1925 diag::err_typecheck_negative_array_size)
1926 << ArraySize->getSourceRange());
1927 }
1928
1929 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001930 unsigned ActiveSizeBits =
1931 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00001932 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1933 return ExprError(Diag(ArraySize->getLocStart(),
1934 diag::err_array_too_large)
1935 << Value.toString(10)
1936 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001937 }
Richard Smith0511d232016-10-05 22:41:02 +00001938
1939 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00001940 } else if (TypeIdParens.isValid()) {
1941 // Can't have dynamic array size when the type-id is in parentheses.
1942 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1943 << ArraySize->getSourceRange()
1944 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1945 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001946
Douglas Gregorf2753b32010-07-13 15:54:32 +00001947 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001948 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001949 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001950
John McCall036f2f62011-05-15 07:14:44 +00001951 // Note that we do *not* convert the argument in any way. It can
1952 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001953 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001954
Craig Topperc3ec1492014-05-26 06:22:03 +00001955 FunctionDecl *OperatorNew = nullptr;
1956 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00001957 unsigned Alignment =
1958 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1959 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1960 bool PassAlignment = getLangOpts().AlignedAllocation &&
1961 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001962
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001963 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001964 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001965 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001966 SourceRange(PlacementLParen, PlacementRParen),
Richard Smithb2f0f052016-10-10 18:54:32 +00001967 UseGlobal, AllocType, ArraySize, PassAlignment,
1968 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001969 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001970
1971 // If this is an array allocation, compute whether the usual array
1972 // deallocation function for the type has a size_t parameter.
1973 bool UsualArrayDeleteWantsSize = false;
1974 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00001975 UsualArrayDeleteWantsSize =
1976 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00001977
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001978 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001979 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00001981 OperatorNew->getType()->getAs<FunctionProtoType>();
1982 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1983 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001984
Richard Smithd6f9e732014-05-13 19:56:21 +00001985 // We've already converted the placement args, just fill in any default
1986 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00001987 // argument. Skip the second parameter too if we're passing in the
1988 // alignment; we've already filled it in.
1989 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
1990 PassAlignment ? 2 : 1, PlacementArgs,
1991 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001992 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001993
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001994 if (!AllPlaceArgs.empty())
1995 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00001996
Richard Smithd6f9e732014-05-13 19:56:21 +00001997 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001998 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00001999
2000 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002001
Richard Smithb2f0f052016-10-10 18:54:32 +00002002 // Warn if the type is over-aligned and is being allocated by (unaligned)
2003 // global operator new.
2004 if (PlacementArgs.empty() && !PassAlignment &&
2005 (OperatorNew->isImplicit() ||
2006 (OperatorNew->getLocStart().isValid() &&
2007 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
2008 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00002009 Diag(StartLoc, diag::warn_overaligned_type)
2010 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00002011 << unsigned(Alignment / Context.getCharWidth())
2012 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00002013 }
2014 }
2015
Sebastian Redl6047f072012-02-16 12:22:20 +00002016 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002017 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2018 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002019 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2020 SourceRange InitRange(Inits[0]->getLocStart(),
2021 Inits[NumInits - 1]->getLocEnd());
2022 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2023 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002024 }
2025
Richard Smithdd2ca572012-11-26 08:32:48 +00002026 // If we can perform the initialization, and we've not already done so,
2027 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002028 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002029 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002030 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002031 // The type we initialize is the complete type, including the array bound.
2032 QualType InitType;
2033 if (KnownArraySize)
2034 InitType = Context.getConstantArrayType(
2035 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2036 *KnownArraySize),
2037 ArrayType::Normal, 0);
2038 else if (ArraySize)
2039 InitType =
2040 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2041 else
2042 InitType = AllocType;
2043
Douglas Gregor85dabae2009-12-16 01:38:02 +00002044 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002045 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002046 InitializationSequence InitSeq(*this, Entity, Kind,
2047 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002048 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002049 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002050 if (FullInit.isInvalid())
2051 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002052
Sebastian Redl6047f072012-02-16 12:22:20 +00002053 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2054 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002055 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002056 if (CXXBindTemporaryExpr *Binder =
2057 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002058 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002059
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002060 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002062
Douglas Gregor6642ca22010-02-26 05:06:18 +00002063 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002064 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002065 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2066 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002067 MarkFunctionReferenced(StartLoc, OperatorNew);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002068 diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002069 }
2070 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002071 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2072 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002073 MarkFunctionReferenced(StartLoc, OperatorDelete);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002074 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002075 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002076
John McCall928a2572011-07-13 20:12:57 +00002077 // C++0x [expr.new]p17:
2078 // If the new expression creates an array of objects of class type,
2079 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00002080 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2081 if (ArraySize && !BaseAllocType->isDependentType()) {
2082 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2083 if (CXXDestructorDecl *dtor = LookupDestructor(
2084 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2085 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002086 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002087 PDiag(diag::err_access_dtor)
2088 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002089 if (DiagnoseUseOfDecl(dtor, StartLoc))
2090 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002091 }
John McCall928a2572011-07-13 20:12:57 +00002092 }
2093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002094
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002095 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00002096 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002097 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2098 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2099 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002100}
2101
Sebastian Redl6047f072012-02-16 12:22:20 +00002102/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002103/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002104bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002105 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002106 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2107 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002108 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002109 return Diag(Loc, diag::err_bad_new_type)
2110 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002111 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002112 return Diag(Loc, diag::err_bad_new_type)
2113 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002114 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002115 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002116 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002117 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002118 diag::err_allocation_of_abstract_type))
2119 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002120 else if (AllocType->isVariablyModifiedType())
2121 return Diag(Loc, diag::err_variably_modified_new_type)
2122 << AllocType;
Alexander Richardson6d989432017-10-15 18:48:14 +00002123 else if (AllocType.getAddressSpace() != LangAS::Default)
Douglas Gregor39d1a092011-04-15 19:46:20 +00002124 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002125 << AllocType.getUnqualifiedType()
2126 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002127 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002128 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2129 QualType BaseAllocType = Context.getBaseElementType(AT);
2130 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2131 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002132 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002133 << BaseAllocType;
2134 }
2135 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002136
Sebastian Redlbd150f42008-11-21 19:14:01 +00002137 return false;
2138}
2139
Richard Smithb2f0f052016-10-10 18:54:32 +00002140static bool
2141resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2142 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2143 FunctionDecl *&Operator,
2144 OverloadCandidateSet *AlignedCandidates = nullptr,
2145 Expr *AlignArg = nullptr) {
2146 OverloadCandidateSet Candidates(R.getNameLoc(),
2147 OverloadCandidateSet::CSK_Normal);
2148 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2149 Alloc != AllocEnd; ++Alloc) {
2150 // Even member operator new/delete are implicitly treated as
2151 // static, so don't use AddMemberCandidate.
2152 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2153
2154 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2155 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2156 /*ExplicitTemplateArgs=*/nullptr, Args,
2157 Candidates,
2158 /*SuppressUserConversions=*/false);
2159 continue;
2160 }
2161
2162 FunctionDecl *Fn = cast<FunctionDecl>(D);
2163 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2164 /*SuppressUserConversions=*/false);
2165 }
2166
2167 // Do the resolution.
2168 OverloadCandidateSet::iterator Best;
2169 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2170 case OR_Success: {
2171 // Got one!
2172 FunctionDecl *FnDecl = Best->Function;
2173 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2174 Best->FoundDecl) == Sema::AR_inaccessible)
2175 return true;
2176
2177 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002178 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002179 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002180
Richard Smithb2f0f052016-10-10 18:54:32 +00002181 case OR_No_Viable_Function:
2182 // C++17 [expr.new]p13:
2183 // If no matching function is found and the allocated object type has
2184 // new-extended alignment, the alignment argument is removed from the
2185 // argument list, and overload resolution is performed again.
2186 if (PassAlignment) {
2187 PassAlignment = false;
2188 AlignArg = Args[1];
2189 Args.erase(Args.begin() + 1);
2190 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2191 Operator, &Candidates, AlignArg);
2192 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002193
Richard Smithb2f0f052016-10-10 18:54:32 +00002194 // MSVC will fall back on trying to find a matching global operator new
2195 // if operator new[] cannot be found. Also, MSVC will leak by not
2196 // generating a call to operator delete or operator delete[], but we
2197 // will not replicate that bug.
2198 // FIXME: Find out how this interacts with the std::align_val_t fallback
2199 // once MSVC implements it.
2200 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2201 S.Context.getLangOpts().MSVCCompat) {
2202 R.clear();
2203 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2204 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2205 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2206 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2207 Operator, nullptr);
2208 }
Richard Smith1cdec012013-09-29 04:40:38 +00002209
Richard Smithb2f0f052016-10-10 18:54:32 +00002210 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2211 << R.getLookupName() << Range;
2212
2213 // If we have aligned candidates, only note the align_val_t candidates
2214 // from AlignedCandidates and the non-align_val_t candidates from
2215 // Candidates.
2216 if (AlignedCandidates) {
2217 auto IsAligned = [](OverloadCandidate &C) {
2218 return C.Function->getNumParams() > 1 &&
2219 C.Function->getParamDecl(1)->getType()->isAlignValT();
2220 };
2221 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2222
2223 // This was an overaligned allocation, so list the aligned candidates
2224 // first.
2225 Args.insert(Args.begin() + 1, AlignArg);
2226 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2227 R.getNameLoc(), IsAligned);
2228 Args.erase(Args.begin() + 1);
2229 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2230 IsUnaligned);
2231 } else {
2232 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2233 }
Richard Smith1cdec012013-09-29 04:40:38 +00002234 return true;
2235
Richard Smithb2f0f052016-10-10 18:54:32 +00002236 case OR_Ambiguous:
2237 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2238 << R.getLookupName() << Range;
2239 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2240 return true;
2241
2242 case OR_Deleted: {
2243 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2244 << Best->Function->isDeleted()
2245 << R.getLookupName()
2246 << S.getDeletedOrUnavailableSuffix(Best->Function)
2247 << Range;
2248 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2249 return true;
2250 }
2251 }
2252 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002253}
2254
Richard Smithb2f0f052016-10-10 18:54:32 +00002255
Sebastian Redlfaf68082008-12-03 20:26:15 +00002256/// FindAllocationFunctions - Finds the overloads of operator new and delete
2257/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002258bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2259 bool UseGlobal, QualType AllocType,
Richard Smithb2f0f052016-10-10 18:54:32 +00002260 bool IsArray, bool &PassAlignment,
2261 MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002262 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00002263 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002264 // --- Choosing an allocation function ---
2265 // C++ 5.3.4p8 - 14 & 18
2266 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2267 // in the scope of the allocated class.
2268 // 2) If an array size is given, look for operator new[], else look for
2269 // operator new.
2270 // 3) The first argument is always size_t. Append the arguments from the
2271 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002272
Richard Smithb2f0f052016-10-10 18:54:32 +00002273 SmallVector<Expr*, 8> AllocArgs;
2274 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2275
2276 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002277 // FIXME: Should the Sema create the expression and embed it in the syntax
2278 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002279 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002280 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002281 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002282 Context.getSizeType(),
2283 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002284 AllocArgs.push_back(&Size);
2285
2286 QualType AlignValT = Context.VoidTy;
2287 if (PassAlignment) {
2288 DeclareGlobalNewDelete();
2289 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2290 }
2291 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2292 if (PassAlignment)
2293 AllocArgs.push_back(&Align);
2294
2295 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002296
Douglas Gregor6642ca22010-02-26 05:06:18 +00002297 // C++ [expr.new]p8:
2298 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002299 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002300 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002301 // type, the allocation function's name is operator new[] and the
2302 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002303 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002304 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002305
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002306 QualType AllocElemType = Context.getBaseElementType(AllocType);
2307
Richard Smithb2f0f052016-10-10 18:54:32 +00002308 // Find the allocation function.
2309 {
2310 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2311
2312 // C++1z [expr.new]p9:
2313 // If the new-expression begins with a unary :: operator, the allocation
2314 // function's name is looked up in the global scope. Otherwise, if the
2315 // allocated type is a class type T or array thereof, the allocation
2316 // function's name is looked up in the scope of T.
2317 if (AllocElemType->isRecordType() && !UseGlobal)
2318 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2319
2320 // We can see ambiguity here if the allocation function is found in
2321 // multiple base classes.
2322 if (R.isAmbiguous())
2323 return true;
2324
2325 // If this lookup fails to find the name, or if the allocated type is not
2326 // a class type, the allocation function's name is looked up in the
2327 // global scope.
2328 if (R.empty())
2329 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2330
2331 assert(!R.empty() && "implicitly declared allocation functions not found");
2332 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2333
2334 // We do our own custom access checks below.
2335 R.suppressDiagnostics();
2336
2337 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2338 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002339 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002340 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002341
Richard Smithb2f0f052016-10-10 18:54:32 +00002342 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002343 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002344 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002345 return false;
2346 }
2347
Richard Smithb2f0f052016-10-10 18:54:32 +00002348 // Note, the name of OperatorNew might have been changed from array to
2349 // non-array by resolveAllocationOverload.
2350 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2351 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2352 ? OO_Array_Delete
2353 : OO_Delete);
2354
Douglas Gregor6642ca22010-02-26 05:06:18 +00002355 // C++ [expr.new]p19:
2356 //
2357 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002358 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002359 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002360 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002361 // the scope of T. If this lookup fails to find the name, or if
2362 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002363 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002364 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002365 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002366 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002367 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002368 LookupQualifiedName(FoundDelete, RD);
2369 }
John McCallfb6f5262010-03-18 08:19:33 +00002370 if (FoundDelete.isAmbiguous())
2371 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002372
Richard Smithb2f0f052016-10-10 18:54:32 +00002373 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002374 if (FoundDelete.empty()) {
2375 DeclareGlobalNewDelete();
2376 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2377 }
2378
2379 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002380
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002381 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002382
John McCalld3be2c82010-09-14 21:34:24 +00002383 // Whether we're looking for a placement operator delete is dictated
2384 // by whether we selected a placement operator new, not by whether
2385 // we had explicit placement arguments. This matters for things like
2386 // struct A { void *operator new(size_t, int = 0); ... };
2387 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002388 //
2389 // We don't have any definition for what a "placement allocation function"
2390 // is, but we assume it's any allocation function whose
2391 // parameter-declaration-clause is anything other than (size_t).
2392 //
2393 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2394 // This affects whether an exception from the constructor of an overaligned
2395 // type uses the sized or non-sized form of aligned operator delete.
2396 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2397 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002398
2399 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002400 // C++ [expr.new]p20:
2401 // A declaration of a placement deallocation function matches the
2402 // declaration of a placement allocation function if it has the
2403 // same number of parameters and, after parameter transformations
2404 // (8.3.5), all parameter types except the first are
2405 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002406 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002407 // To perform this comparison, we compute the function type that
2408 // the deallocation function should have, and use that type both
2409 // for template argument deduction and for comparison purposes.
2410 QualType ExpectedFunctionType;
2411 {
2412 const FunctionProtoType *Proto
2413 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002414
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002415 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002416 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002417 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2418 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002419
John McCalldb40c7f2010-12-14 08:05:40 +00002420 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002421 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002422 EPI.Variadic = Proto->isVariadic();
2423
Douglas Gregor6642ca22010-02-26 05:06:18 +00002424 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002425 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002426 }
2427
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002428 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002429 DEnd = FoundDelete.end();
2430 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002431 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002432 if (FunctionTemplateDecl *FnTmpl =
2433 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002434 // Perform template argument deduction to try to match the
2435 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002436 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002437 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2438 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002439 continue;
2440 } else
2441 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2442
Richard Smithbaa47832016-12-01 02:11:49 +00002443 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2444 ExpectedFunctionType,
2445 /*AdjustExcpetionSpec*/true),
2446 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002447 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002448 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002449
Richard Smithb2f0f052016-10-10 18:54:32 +00002450 if (getLangOpts().CUDA)
2451 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2452 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002453 // C++1y [expr.new]p22:
2454 // For a non-placement allocation function, the normal deallocation
2455 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002456 //
2457 // Per [expr.delete]p10, this lookup prefers a member operator delete
2458 // without a size_t argument, but prefers a non-member operator delete
2459 // with a size_t where possible (which it always is in this case).
2460 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2461 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2462 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2463 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2464 &BestDeallocFns);
2465 if (Selected)
2466 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2467 else {
2468 // If we failed to select an operator, all remaining functions are viable
2469 // but ambiguous.
2470 for (auto Fn : BestDeallocFns)
2471 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002472 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002473 }
2474
2475 // C++ [expr.new]p20:
2476 // [...] If the lookup finds a single matching deallocation
2477 // function, that function will be called; otherwise, no
2478 // deallocation function will be called.
2479 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002480 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002481
Richard Smithb2f0f052016-10-10 18:54:32 +00002482 // C++1z [expr.new]p23:
2483 // If the lookup finds a usual deallocation function (3.7.4.2)
2484 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002485 // as a placement deallocation function, would have been
2486 // selected as a match for the allocation function, the program
2487 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002488 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002489 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002490 UsualDeallocFnInfo Info(*this,
2491 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002492 // Core issue, per mail to core reflector, 2016-10-09:
2493 // If this is a member operator delete, and there is a corresponding
2494 // non-sized member operator delete, this isn't /really/ a sized
2495 // deallocation function, it just happens to have a size_t parameter.
2496 bool IsSizedDelete = Info.HasSizeT;
2497 if (IsSizedDelete && !FoundGlobalDelete) {
2498 auto NonSizedDelete =
2499 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2500 /*WantAlign*/Info.HasAlignValT);
2501 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2502 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2503 IsSizedDelete = false;
2504 }
2505
2506 if (IsSizedDelete) {
2507 SourceRange R = PlaceArgs.empty()
2508 ? SourceRange()
2509 : SourceRange(PlaceArgs.front()->getLocStart(),
2510 PlaceArgs.back()->getLocEnd());
2511 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2512 if (!OperatorDelete->isImplicit())
2513 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2514 << DeleteName;
2515 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002516 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002517
2518 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2519 Matches[0].first);
2520 } else if (!Matches.empty()) {
2521 // We found multiple suitable operators. Per [expr.new]p20, that means we
2522 // call no 'operator delete' function, but we should at least warn the user.
2523 // FIXME: Suppress this warning if the construction cannot throw.
2524 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2525 << DeleteName << AllocElemType;
2526
2527 for (auto &Match : Matches)
2528 Diag(Match.second->getLocation(),
2529 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002530 }
2531
Sebastian Redlfaf68082008-12-03 20:26:15 +00002532 return false;
2533}
2534
2535/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2536/// delete. These are:
2537/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002538/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002539/// void* operator new(std::size_t) throw(std::bad_alloc);
2540/// void* operator new[](std::size_t) throw(std::bad_alloc);
2541/// void operator delete(void *) throw();
2542/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002543/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002544/// void* operator new(std::size_t);
2545/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002546/// void operator delete(void *) noexcept;
2547/// void operator delete[](void *) noexcept;
2548/// // C++1y:
2549/// void* operator new(std::size_t);
2550/// void* operator new[](std::size_t);
2551/// void operator delete(void *) noexcept;
2552/// void operator delete[](void *) noexcept;
2553/// void operator delete(void *, std::size_t) noexcept;
2554/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002555/// @endcode
2556/// Note that the placement and nothrow forms of new are *not* implicitly
2557/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002558void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002559 if (GlobalNewDeleteDeclared)
2560 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002561
Douglas Gregor87f54062009-09-15 22:30:29 +00002562 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002563 // [...] The following allocation and deallocation functions (18.4) are
2564 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002565 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002566 //
Sebastian Redl37588092011-03-14 18:08:30 +00002567 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002568 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002569 // void* operator new[](std::size_t) throw(std::bad_alloc);
2570 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002571 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002572 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002573 // void* operator new(std::size_t);
2574 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002575 // void operator delete(void*) noexcept;
2576 // void operator delete[](void*) noexcept;
2577 // C++1y:
2578 // void* operator new(std::size_t);
2579 // void* operator new[](std::size_t);
2580 // void operator delete(void*) noexcept;
2581 // void operator delete[](void*) noexcept;
2582 // void operator delete(void*, std::size_t) noexcept;
2583 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002584 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002585 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002586 // new, operator new[], operator delete, operator delete[].
2587 //
2588 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2589 // "std" or "bad_alloc" as necessary to form the exception specification.
2590 // However, we do not make these implicit declarations visible to name
2591 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002592 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002593 // The "std::bad_alloc" class has not yet been declared, so build it
2594 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002595 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2596 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002597 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002598 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002599 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002600 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002601 }
Richard Smith59139022016-09-30 22:41:36 +00002602 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002603 // The "std::align_val_t" enum class has not yet been declared, so build it
2604 // implicitly.
2605 auto *AlignValT = EnumDecl::Create(
2606 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2607 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2608 AlignValT->setIntegerType(Context.getSizeType());
2609 AlignValT->setPromotionType(Context.getSizeType());
2610 AlignValT->setImplicit(true);
2611 StdAlignValT = AlignValT;
2612 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002613
Sebastian Redlfaf68082008-12-03 20:26:15 +00002614 GlobalNewDeleteDeclared = true;
2615
2616 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2617 QualType SizeT = Context.getSizeType();
2618
Richard Smith96269c52016-09-29 22:49:46 +00002619 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2620 QualType Return, QualType Param) {
2621 llvm::SmallVector<QualType, 3> Params;
2622 Params.push_back(Param);
2623
2624 // Create up to four variants of the function (sized/aligned).
2625 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2626 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002627 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002628
2629 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2630 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2631 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002632 if (Sized)
2633 Params.push_back(SizeT);
2634
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002635 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002636 if (Aligned)
2637 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2638
2639 DeclareGlobalAllocationFunction(
2640 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2641
2642 if (Aligned)
2643 Params.pop_back();
2644 }
2645 }
2646 };
2647
2648 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2649 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2650 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2651 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002652}
2653
2654/// DeclareGlobalAllocationFunction - Declares a single implicit global
2655/// allocation function if it doesn't already exist.
2656void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002657 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002658 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002659 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2660
2661 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002662 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2663 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2664 Alloc != AllocEnd; ++Alloc) {
2665 // Only look at non-template functions, as it is the predefined,
2666 // non-templated allocation function we are trying to declare here.
2667 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002668 if (Func->getNumParams() == Params.size()) {
2669 llvm::SmallVector<QualType, 3> FuncParams;
2670 for (auto *P : Func->parameters())
2671 FuncParams.push_back(
2672 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2673 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002674 // Make the function visible to name lookup, even if we found it in
2675 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002676 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002677 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002678 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002679 }
Chandler Carruth93538422010-02-03 11:02:14 +00002680 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002681 }
2682 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002683
Richard Smithc015bc22014-02-07 22:39:53 +00002684 FunctionProtoType::ExtProtoInfo EPI;
2685
Richard Smithf8b417c2014-02-08 00:42:45 +00002686 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002687 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002688 = (Name.getCXXOverloadedOperator() == OO_New ||
2689 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002690 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002691 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002692 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002693 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002694 EPI.ExceptionSpec.Type = EST_Dynamic;
2695 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002696 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002697 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002698 EPI.ExceptionSpec =
2699 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002700 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002701
Artem Belevich07db5cf2016-10-21 20:34:05 +00002702 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2703 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2704 FunctionDecl *Alloc = FunctionDecl::Create(
2705 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2706 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2707 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002708 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002709 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002710
Artem Belevich07db5cf2016-10-21 20:34:05 +00002711 // Implicit sized deallocation functions always have default visibility.
2712 Alloc->addAttr(
2713 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002714
Artem Belevich07db5cf2016-10-21 20:34:05 +00002715 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2716 for (QualType T : Params) {
2717 ParamDecls.push_back(ParmVarDecl::Create(
2718 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2719 /*TInfo=*/nullptr, SC_None, nullptr));
2720 ParamDecls.back()->setImplicit();
2721 }
2722 Alloc->setParams(ParamDecls);
2723 if (ExtraAttr)
2724 Alloc->addAttr(ExtraAttr);
2725 Context.getTranslationUnitDecl()->addDecl(Alloc);
2726 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2727 };
2728
2729 if (!LangOpts.CUDA)
2730 CreateAllocationFunctionDecl(nullptr);
2731 else {
2732 // Host and device get their own declaration so each can be
2733 // defined or re-declared independently.
2734 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2735 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002736 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002737}
2738
Richard Smith1cdec012013-09-29 04:40:38 +00002739FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2740 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002741 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002742 DeclarationName Name) {
2743 DeclareGlobalNewDelete();
2744
2745 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2746 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2747
Richard Smithb2f0f052016-10-10 18:54:32 +00002748 // FIXME: It's possible for this to result in ambiguity, through a
2749 // user-declared variadic operator delete or the enable_if attribute. We
2750 // should probably not consider those cases to be usual deallocation
2751 // functions. But for now we just make an arbitrary choice in that case.
2752 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2753 Overaligned);
2754 assert(Result.FD && "operator delete missing from global scope?");
2755 return Result.FD;
2756}
Richard Smith1cdec012013-09-29 04:40:38 +00002757
Richard Smithb2f0f052016-10-10 18:54:32 +00002758FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2759 CXXRecordDecl *RD) {
2760 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002761
Richard Smithb2f0f052016-10-10 18:54:32 +00002762 FunctionDecl *OperatorDelete = nullptr;
2763 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2764 return nullptr;
2765 if (OperatorDelete)
2766 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002767
Richard Smithb2f0f052016-10-10 18:54:32 +00002768 // If there's no class-specific operator delete, look up the global
2769 // non-array delete.
2770 return FindUsualDeallocationFunction(
2771 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2772 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002773}
2774
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002775bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2776 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002777 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002778 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002779 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002780 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002781
John McCall27b18f82009-11-17 02:14:36 +00002782 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002783 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002784
Chandler Carruthb6f99172010-06-28 00:30:51 +00002785 Found.suppressDiagnostics();
2786
Richard Smithb2f0f052016-10-10 18:54:32 +00002787 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002788
Richard Smithb2f0f052016-10-10 18:54:32 +00002789 // C++17 [expr.delete]p10:
2790 // If the deallocation functions have class scope, the one without a
2791 // parameter of type std::size_t is selected.
2792 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2793 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2794 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002795
Richard Smithb2f0f052016-10-10 18:54:32 +00002796 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002797 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002798 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002799
Richard Smithb2f0f052016-10-10 18:54:32 +00002800 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002801 if (Operator->isDeleted()) {
2802 if (Diagnose) {
2803 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002804 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002805 }
2806 return true;
2807 }
2808
Richard Smith921bd202012-02-26 09:11:52 +00002809 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002810 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002811 return true;
2812
John McCall66a87592010-08-04 00:31:26 +00002813 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002814 }
John McCall66a87592010-08-04 00:31:26 +00002815
Richard Smithb2f0f052016-10-10 18:54:32 +00002816 // We found multiple suitable operators; complain about the ambiguity.
2817 // FIXME: The standard doesn't say to do this; it appears that the intent
2818 // is that this should never happen.
2819 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002820 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002821 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2822 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002823 for (auto &Match : Matches)
2824 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002825 }
John McCall66a87592010-08-04 00:31:26 +00002826 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002827 }
2828
2829 // We did find operator delete/operator delete[] declarations, but
2830 // none of them were suitable.
2831 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002832 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002833 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2834 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002835
Richard Smithb2f0f052016-10-10 18:54:32 +00002836 for (NamedDecl *D : Found)
2837 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002838 diag::note_member_declared_here) << Name;
2839 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002840 return true;
2841 }
2842
Craig Topperc3ec1492014-05-26 06:22:03 +00002843 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002844 return false;
2845}
2846
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002847namespace {
2848/// \brief Checks whether delete-expression, and new-expression used for
2849/// initializing deletee have the same array form.
2850class MismatchingNewDeleteDetector {
2851public:
2852 enum MismatchResult {
2853 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2854 NoMismatch,
2855 /// Indicates that variable is initialized with mismatching form of \a new.
2856 VarInitMismatches,
2857 /// Indicates that member is initialized with mismatching form of \a new.
2858 MemberInitMismatches,
2859 /// Indicates that 1 or more constructors' definitions could not been
2860 /// analyzed, and they will be checked again at the end of translation unit.
2861 AnalyzeLater
2862 };
2863
2864 /// \param EndOfTU True, if this is the final analysis at the end of
2865 /// translation unit. False, if this is the initial analysis at the point
2866 /// delete-expression was encountered.
2867 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002868 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002869 HasUndefinedConstructors(false) {}
2870
2871 /// \brief Checks whether pointee of a delete-expression is initialized with
2872 /// matching form of new-expression.
2873 ///
2874 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2875 /// point where delete-expression is encountered, then a warning will be
2876 /// issued immediately. If return value is \c AnalyzeLater at the point where
2877 /// delete-expression is seen, then member will be analyzed at the end of
2878 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2879 /// couldn't be analyzed. If at least one constructor initializes the member
2880 /// with matching type of new, the return value is \c NoMismatch.
2881 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2882 /// \brief Analyzes a class member.
2883 /// \param Field Class member to analyze.
2884 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2885 /// for deleting the \p Field.
2886 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002887 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002888 /// List of mismatching new-expressions used for initialization of the pointee
2889 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2890 /// Indicates whether delete-expression was in array form.
2891 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002892
2893private:
2894 const bool EndOfTU;
2895 /// \brief Indicates that there is at least one constructor without body.
2896 bool HasUndefinedConstructors;
2897 /// \brief Returns \c CXXNewExpr from given initialization expression.
2898 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002899 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002900 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2901 /// \brief Returns whether member is initialized with mismatching form of
2902 /// \c new either by the member initializer or in-class initialization.
2903 ///
2904 /// If bodies of all constructors are not visible at the end of translation
2905 /// unit or at least one constructor initializes member with the matching
2906 /// form of \c new, mismatch cannot be proven, and this function will return
2907 /// \c NoMismatch.
2908 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2909 /// \brief Returns whether variable is initialized with mismatching form of
2910 /// \c new.
2911 ///
2912 /// If variable is initialized with matching form of \c new or variable is not
2913 /// initialized with a \c new expression, this function will return true.
2914 /// If variable is initialized with mismatching form of \c new, returns false.
2915 /// \param D Variable to analyze.
2916 bool hasMatchingVarInit(const DeclRefExpr *D);
2917 /// \brief Checks whether the constructor initializes pointee with mismatching
2918 /// form of \c new.
2919 ///
2920 /// Returns true, if member is initialized with matching form of \c new in
2921 /// member initializer list. Returns false, if member is initialized with the
2922 /// matching form of \c new in this constructor's initializer or given
2923 /// constructor isn't defined at the point where delete-expression is seen, or
2924 /// member isn't initialized by the constructor.
2925 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2926 /// \brief Checks whether member is initialized with matching form of
2927 /// \c new in member initializer list.
2928 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2929 /// Checks whether member is initialized with mismatching form of \c new by
2930 /// in-class initializer.
2931 MismatchResult analyzeInClassInitializer();
2932};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002933}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002934
2935MismatchingNewDeleteDetector::MismatchResult
2936MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2937 NewExprs.clear();
2938 assert(DE && "Expected delete-expression");
2939 IsArrayForm = DE->isArrayForm();
2940 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2941 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2942 return analyzeMemberExpr(ME);
2943 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2944 if (!hasMatchingVarInit(D))
2945 return VarInitMismatches;
2946 }
2947 return NoMismatch;
2948}
2949
2950const CXXNewExpr *
2951MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2952 assert(E != nullptr && "Expected a valid initializer expression");
2953 E = E->IgnoreParenImpCasts();
2954 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2955 if (ILE->getNumInits() == 1)
2956 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2957 }
2958
2959 return dyn_cast_or_null<const CXXNewExpr>(E);
2960}
2961
2962bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2963 const CXXCtorInitializer *CI) {
2964 const CXXNewExpr *NE = nullptr;
2965 if (Field == CI->getMember() &&
2966 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2967 if (NE->isArray() == IsArrayForm)
2968 return true;
2969 else
2970 NewExprs.push_back(NE);
2971 }
2972 return false;
2973}
2974
2975bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2976 const CXXConstructorDecl *CD) {
2977 if (CD->isImplicit())
2978 return false;
2979 const FunctionDecl *Definition = CD;
2980 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2981 HasUndefinedConstructors = true;
2982 return EndOfTU;
2983 }
2984 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2985 if (hasMatchingNewInCtorInit(CI))
2986 return true;
2987 }
2988 return false;
2989}
2990
2991MismatchingNewDeleteDetector::MismatchResult
2992MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2993 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00002994 const Expr *InitExpr = Field->getInClassInitializer();
2995 if (!InitExpr)
2996 return EndOfTU ? NoMismatch : AnalyzeLater;
2997 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002998 if (NE->isArray() != IsArrayForm) {
2999 NewExprs.push_back(NE);
3000 return MemberInitMismatches;
3001 }
3002 }
3003 return NoMismatch;
3004}
3005
3006MismatchingNewDeleteDetector::MismatchResult
3007MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3008 bool DeleteWasArrayForm) {
3009 assert(Field != nullptr && "Analysis requires a valid class member.");
3010 this->Field = Field;
3011 IsArrayForm = DeleteWasArrayForm;
3012 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3013 for (const auto *CD : RD->ctors()) {
3014 if (hasMatchingNewInCtor(CD))
3015 return NoMismatch;
3016 }
3017 if (HasUndefinedConstructors)
3018 return EndOfTU ? NoMismatch : AnalyzeLater;
3019 if (!NewExprs.empty())
3020 return MemberInitMismatches;
3021 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3022 : NoMismatch;
3023}
3024
3025MismatchingNewDeleteDetector::MismatchResult
3026MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3027 assert(ME != nullptr && "Expected a member expression");
3028 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3029 return analyzeField(F, IsArrayForm);
3030 return NoMismatch;
3031}
3032
3033bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3034 const CXXNewExpr *NE = nullptr;
3035 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3036 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3037 NE->isArray() != IsArrayForm) {
3038 NewExprs.push_back(NE);
3039 }
3040 }
3041 return NewExprs.empty();
3042}
3043
3044static void
3045DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3046 const MismatchingNewDeleteDetector &Detector) {
3047 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3048 FixItHint H;
3049 if (!Detector.IsArrayForm)
3050 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3051 else {
3052 SourceLocation RSquare = Lexer::findLocationAfterToken(
3053 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3054 SemaRef.getLangOpts(), true);
3055 if (RSquare.isValid())
3056 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3057 }
3058 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3059 << Detector.IsArrayForm << H;
3060
3061 for (const auto *NE : Detector.NewExprs)
3062 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3063 << Detector.IsArrayForm;
3064}
3065
3066void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3067 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3068 return;
3069 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3070 switch (Detector.analyzeDeleteExpr(DE)) {
3071 case MismatchingNewDeleteDetector::VarInitMismatches:
3072 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3073 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
3074 break;
3075 }
3076 case MismatchingNewDeleteDetector::AnalyzeLater: {
3077 DeleteExprs[Detector.Field].push_back(
3078 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
3079 break;
3080 }
3081 case MismatchingNewDeleteDetector::NoMismatch:
3082 break;
3083 }
3084}
3085
3086void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3087 bool DeleteWasArrayForm) {
3088 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3089 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3090 case MismatchingNewDeleteDetector::VarInitMismatches:
3091 llvm_unreachable("This analysis should have been done for class members.");
3092 case MismatchingNewDeleteDetector::AnalyzeLater:
3093 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3094 "translation unit.");
3095 case MismatchingNewDeleteDetector::MemberInitMismatches:
3096 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3097 break;
3098 case MismatchingNewDeleteDetector::NoMismatch:
3099 break;
3100 }
3101}
3102
Sebastian Redlbd150f42008-11-21 19:14:01 +00003103/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3104/// @code ::delete ptr; @endcode
3105/// or
3106/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003107ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003108Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003109 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003110 // C++ [expr.delete]p1:
3111 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003112 // non-explicit conversion function to a pointer type. The result has type
3113 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003114 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003115 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3116
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003117 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003118 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003119 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003120 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003121
John Wiegley01296292011-04-08 18:41:53 +00003122 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003123 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003124 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003125 if (Ex.isInvalid())
3126 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003127
John Wiegley01296292011-04-08 18:41:53 +00003128 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003129
Richard Smithccc11812013-05-21 19:05:48 +00003130 class DeleteConverter : public ContextualImplicitConverter {
3131 public:
3132 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003133
Craig Toppere14c0f82014-03-12 04:55:44 +00003134 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003135 // FIXME: If we have an operator T* and an operator void*, we must pick
3136 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003137 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003138 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003139 return true;
3140 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003141 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003142
Richard Smithccc11812013-05-21 19:05:48 +00003143 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003144 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003145 return S.Diag(Loc, diag::err_delete_operand) << T;
3146 }
3147
3148 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003149 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003150 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3151 }
3152
3153 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003154 QualType T,
3155 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003156 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3157 }
3158
3159 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003160 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003161 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3162 << ConvTy;
3163 }
3164
3165 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003166 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003167 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3168 }
3169
3170 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003171 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003172 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3173 << ConvTy;
3174 }
3175
3176 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003177 QualType T,
3178 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003179 llvm_unreachable("conversion functions are permitted");
3180 }
3181 } Converter;
3182
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003183 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003184 if (Ex.isInvalid())
3185 return ExprError();
3186 Type = Ex.get()->getType();
3187 if (!Converter.match(Type))
3188 // FIXME: PerformContextualImplicitConversion should return ExprError
3189 // itself in this case.
3190 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003191
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003192 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003193 QualType PointeeElem = Context.getBaseElementType(Pointee);
3194
Alexander Richardson6d989432017-10-15 18:48:14 +00003195 if (Pointee.getAddressSpace() != LangAS::Default)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003196 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003197 diag::err_address_space_qualified_delete)
Yaxun Liub34ec822017-04-11 17:24:23 +00003198 << Pointee.getUnqualifiedType()
3199 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003200
Craig Topperc3ec1492014-05-26 06:22:03 +00003201 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003202 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003203 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003204 // effectively bans deletion of "void*". However, most compilers support
3205 // this, so we treat it as a warning unless we're in a SFINAE context.
3206 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003207 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003208 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003209 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003210 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003211 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003212 // FIXME: This can result in errors if the definition was imported from a
3213 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003214 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003215 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003216 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3217 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3218 }
3219 }
3220
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003221 if (Pointee->isArrayType() && !ArrayForm) {
3222 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003223 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003224 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003225 ArrayForm = true;
3226 }
3227
Anders Carlssona471db02009-08-16 20:29:29 +00003228 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3229 ArrayForm ? OO_Array_Delete : OO_Delete);
3230
Eli Friedmanae4280f2011-07-26 22:25:31 +00003231 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003232 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003233 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3234 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003235 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003236
John McCall284c48f2011-01-27 09:37:56 +00003237 // If we're allocating an array of records, check whether the
3238 // usual operator delete[] has a size_t parameter.
3239 if (ArrayForm) {
3240 // If the user specifically asked to use the global allocator,
3241 // we'll need to do the lookup into the class.
3242 if (UseGlobal)
3243 UsualArrayDeleteWantsSize =
3244 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3245
3246 // Otherwise, the usual operator delete[] should be the
3247 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003248 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003249 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003250 UsualDeallocFnInfo(*this,
3251 DeclAccessPair::make(OperatorDelete, AS_public))
3252 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003253 }
3254
Richard Smitheec915d62012-02-18 04:13:32 +00003255 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003256 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003257 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003258 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003259 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3260 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003261 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003262
Nico Weber5a9259c2016-01-15 21:45:31 +00003263 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3264 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3265 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3266 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003268
Richard Smithb2f0f052016-10-10 18:54:32 +00003269 if (!OperatorDelete) {
3270 bool IsComplete = isCompleteType(StartLoc, Pointee);
3271 bool CanProvideSize =
3272 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3273 Pointee.isDestructedType());
3274 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3275
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003276 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003277 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3278 Overaligned, DeleteName);
3279 }
Mike Stump11289f42009-09-09 15:08:12 +00003280
Eli Friedmanfa0df832012-02-02 03:46:19 +00003281 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003282
Richard Smith5b349582017-10-13 01:55:36 +00003283 // Check access and ambiguity of destructor if we're going to call it.
3284 // Note that this is required even for a virtual delete.
3285 bool IsVirtualDelete = false;
Eli Friedmanae4280f2011-07-26 22:25:31 +00003286 if (PointeeRD) {
3287 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Richard Smith5b349582017-10-13 01:55:36 +00003288 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3289 PDiag(diag::err_access_dtor) << PointeeElem);
3290 IsVirtualDelete = Dtor->isVirtual();
Douglas Gregorfa778132011-02-01 15:50:11 +00003291 }
3292 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003293
3294 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true,
3295 *this);
Richard Smith5b349582017-10-13 01:55:36 +00003296
3297 // Convert the operand to the type of the first parameter of operator
3298 // delete. This is only necessary if we selected a destroying operator
3299 // delete that we are going to call (non-virtually); converting to void*
3300 // is trivial and left to AST consumers to handle.
3301 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3302 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
Richard Smith25172012017-12-05 23:54:25 +00003303 Qualifiers Qs = Pointee.getQualifiers();
3304 if (Qs.hasCVRQualifiers()) {
3305 // Qualifiers are irrelevant to this conversion; we're only looking
3306 // for access and ambiguity.
3307 Qs.removeCVRQualifiers();
3308 QualType Unqual = Context.getPointerType(
3309 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3310 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3311 }
Richard Smith5b349582017-10-13 01:55:36 +00003312 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3313 if (Ex.isInvalid())
3314 return ExprError();
3315 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003316 }
3317
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003318 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003319 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3320 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003321 AnalyzeDeleteExprMismatch(Result);
3322 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003323}
3324
Nico Weber5a9259c2016-01-15 21:45:31 +00003325void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3326 bool IsDelete, bool CallCanBeVirtual,
3327 bool WarnOnNonAbstractTypes,
3328 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003329 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003330 return;
3331
3332 // C++ [expr.delete]p3:
3333 // In the first alternative (delete object), if the static type of the
3334 // object to be deleted is different from its dynamic type, the static
3335 // type shall be a base class of the dynamic type of the object to be
3336 // deleted and the static type shall have a virtual destructor or the
3337 // behavior is undefined.
3338 //
3339 const CXXRecordDecl *PointeeRD = dtor->getParent();
3340 // Note: a final class cannot be derived from, no issue there
3341 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3342 return;
3343
Nico Weberbf2260c2017-08-31 06:17:08 +00003344 // If the superclass is in a system header, there's nothing that can be done.
3345 // The `delete` (where we emit the warning) can be in a system header,
3346 // what matters for this warning is where the deleted type is defined.
3347 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3348 return;
3349
Nico Weber5a9259c2016-01-15 21:45:31 +00003350 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3351 if (PointeeRD->isAbstract()) {
3352 // If the class is abstract, we warn by default, because we're
3353 // sure the code has undefined behavior.
3354 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3355 << ClassType;
3356 } else if (WarnOnNonAbstractTypes) {
3357 // Otherwise, if this is not an array delete, it's a bit suspect,
3358 // but not necessarily wrong.
3359 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3360 << ClassType;
3361 }
3362 if (!IsDelete) {
3363 std::string TypeStr;
3364 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3365 Diag(DtorLoc, diag::note_delete_non_virtual)
3366 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3367 }
3368}
3369
Richard Smith03a4aa32016-06-23 19:02:52 +00003370Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3371 SourceLocation StmtLoc,
3372 ConditionKind CK) {
3373 ExprResult E =
3374 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3375 if (E.isInvalid())
3376 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003377 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3378 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003379}
3380
Douglas Gregor633caca2009-11-23 23:44:04 +00003381/// \brief Check the use of the given variable as a C++ condition in an if,
3382/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003383ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003384 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003385 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003386 if (ConditionVar->isInvalidDecl())
3387 return ExprError();
3388
Douglas Gregor633caca2009-11-23 23:44:04 +00003389 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003390
Douglas Gregor633caca2009-11-23 23:44:04 +00003391 // C++ [stmt.select]p2:
3392 // The declarator shall not specify a function or an array.
3393 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003394 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003395 diag::err_invalid_use_of_function_type)
3396 << ConditionVar->getSourceRange());
3397 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003398 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003399 diag::err_invalid_use_of_array_type)
3400 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003401
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003402 ExprResult Condition = DeclRefExpr::Create(
3403 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3404 /*enclosing*/ false, ConditionVar->getLocation(),
3405 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003406
Eli Friedmanfa0df832012-02-02 03:46:19 +00003407 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003408
Richard Smith03a4aa32016-06-23 19:02:52 +00003409 switch (CK) {
3410 case ConditionKind::Boolean:
3411 return CheckBooleanCondition(StmtLoc, Condition.get());
3412
Richard Smithb130fe72016-06-23 19:16:49 +00003413 case ConditionKind::ConstexprIf:
3414 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3415
Richard Smith03a4aa32016-06-23 19:02:52 +00003416 case ConditionKind::Switch:
3417 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003418 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419
Richard Smith03a4aa32016-06-23 19:02:52 +00003420 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003421}
3422
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003423/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003424ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003425 // C++ 6.4p4:
3426 // The value of a condition that is an initialized declaration in a statement
3427 // other than a switch statement is the value of the declared variable
3428 // implicitly converted to type bool. If that conversion is ill-formed, the
3429 // program is ill-formed.
3430 // The value of a condition that is an expression is the value of the
3431 // expression, implicitly converted to bool.
3432 //
Richard Smithb130fe72016-06-23 19:16:49 +00003433 // FIXME: Return this value to the caller so they don't need to recompute it.
3434 llvm::APSInt Value(/*BitWidth*/1);
3435 return (IsConstexpr && !CondExpr->isValueDependent())
3436 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3437 CCEK_ConstexprIf)
3438 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003439}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003440
3441/// Helper function to determine whether this is the (deprecated) C++
3442/// conversion from a string literal to a pointer to non-const char or
3443/// non-const wchar_t (for narrow and wide string literals,
3444/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003445bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003446Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3447 // Look inside the implicit cast, if it exists.
3448 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3449 From = Cast->getSubExpr();
3450
3451 // A string literal (2.13.4) that is not a wide string literal can
3452 // be converted to an rvalue of type "pointer to char"; a wide
3453 // string literal can be converted to an rvalue of type "pointer
3454 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003455 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003456 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003457 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003458 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003459 // This conversion is considered only when there is an
3460 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003461 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3462 switch (StrLit->getKind()) {
3463 case StringLiteral::UTF8:
3464 case StringLiteral::UTF16:
3465 case StringLiteral::UTF32:
3466 // We don't allow UTF literals to be implicitly converted
3467 break;
3468 case StringLiteral::Ascii:
3469 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3470 ToPointeeType->getKind() == BuiltinType::Char_S);
3471 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003472 return Context.typesAreCompatible(Context.getWideCharType(),
3473 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003474 }
3475 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003476 }
3477
3478 return false;
3479}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003480
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003481static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003482 SourceLocation CastLoc,
3483 QualType Ty,
3484 CastKind Kind,
3485 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003486 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003487 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003488 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003489 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003490 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003491 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003492 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003493 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003494
Richard Smith72d74052013-07-20 19:41:36 +00003495 if (S.RequireNonAbstractType(CastLoc, Ty,
3496 diag::err_allocation_of_abstract_type))
3497 return ExprError();
3498
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003499 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003500 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501
Richard Smith5179eb72016-06-28 19:03:57 +00003502 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3503 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003504 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003505 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003506
Richard Smithf8adcdc2014-07-17 05:12:35 +00003507 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003508 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003509 ConstructorArgs, HadMultipleCandidates,
3510 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3511 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003512 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003513 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003514
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003515 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003517
John McCalle3027922010-08-25 11:45:40 +00003518 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003519 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003520
Richard Smithd3f2d322015-02-24 21:16:19 +00003521 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003522 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003523 return ExprError();
3524
Douglas Gregora4253922010-04-16 22:17:36 +00003525 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003526 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3527 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003528 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003529 if (Result.isInvalid())
3530 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003531 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003532 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3533 CK_UserDefinedConversion, Result.get(),
3534 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535
Douglas Gregor668443e2011-01-20 00:18:04 +00003536 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003537 }
3538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539}
Douglas Gregora4253922010-04-16 22:17:36 +00003540
Douglas Gregor5fb53972009-01-14 15:45:31 +00003541/// PerformImplicitConversion - Perform an implicit conversion of the
3542/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003543/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003544/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003545/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003546ExprResult
3547Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003548 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003549 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003550 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003551 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003552 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003553 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3554 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003555 if (Res.isInvalid())
3556 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003557 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003558 break;
John Wiegley01296292011-04-08 18:41:53 +00003559 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003560
Anders Carlsson110b07b2009-09-15 06:28:28 +00003561 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003562
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003563 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003564 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003565 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003566 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003567 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003568 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003569
Anders Carlsson110b07b2009-09-15 06:28:28 +00003570 // If the user-defined conversion is specified by a conversion function,
3571 // the initial standard conversion sequence converts the source type to
3572 // the implicit object parameter of the conversion function.
3573 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003574 } else {
3575 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003576 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003577 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003578 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003579 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003580 // initial standard conversion sequence converts the source type to
3581 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003582 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003584 }
Richard Smith72d74052013-07-20 19:41:36 +00003585 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003586 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003587 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003588 PerformImplicitConversion(From, BeforeToType,
3589 ICS.UserDefined.Before, AA_Converting,
3590 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003591 if (Res.isInvalid())
3592 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003593 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003595
3596 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003597 = BuildCXXCastArgument(*this,
3598 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003599 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003600 CastKind, cast<CXXMethodDecl>(FD),
3601 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003602 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003603 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003604
3605 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003606 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003607
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003608 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003609
Richard Smith507840d2011-11-29 22:48:16 +00003610 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3611 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003612 }
John McCall0d1da222010-01-12 00:44:57 +00003613
3614 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003615 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003616 PDiag(diag::err_typecheck_ambiguous_condition)
3617 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003618 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003619
Douglas Gregor39c16d42008-10-24 04:54:22 +00003620 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003621 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003622
3623 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003624 bool Diagnosed =
3625 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3626 From->getType(), From, Action);
3627 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003628 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003629 }
3630
3631 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003632 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003633}
3634
Richard Smith507840d2011-11-29 22:48:16 +00003635/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003636/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003637/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003638/// expression. Flavor is the context in which we're performing this
3639/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003640ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003641Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003642 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003643 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003644 CheckedConversionKind CCK) {
3645 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003646
Mike Stump87c57ac2009-05-16 07:39:55 +00003647 // Overall FIXME: we are recomputing too many types here and doing far too
3648 // much extra work. What this means is that we need to keep track of more
3649 // information that is computed when we try the implicit conversion initially,
3650 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003651 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003652
Douglas Gregor2fe98832008-11-03 19:09:14 +00003653 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003654 // FIXME: When can ToType be a reference type?
3655 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003656 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003657 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003658 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003659 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003660 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003661 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003662 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003663 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3664 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003665 ConstructorArgs, /*HadMultipleCandidates*/ false,
3666 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3667 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003668 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003669 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003670 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3671 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003672 From, /*HadMultipleCandidates*/ false,
3673 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3674 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003675 }
3676
Douglas Gregor980fb162010-04-29 18:24:40 +00003677 // Resolve overloaded function references.
3678 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3679 DeclAccessPair Found;
3680 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3681 true, Found);
3682 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003683 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003684
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003685 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003686 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003687
Douglas Gregor980fb162010-04-29 18:24:40 +00003688 From = FixOverloadedFunctionReference(From, Found, Fn);
3689 FromType = From->getType();
3690 }
3691
Richard Smitha23ab512013-05-23 00:30:41 +00003692 // If we're converting to an atomic type, first convert to the corresponding
3693 // non-atomic type.
3694 QualType ToAtomicType;
3695 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3696 ToAtomicType = ToType;
3697 ToType = ToAtomic->getValueType();
3698 }
3699
George Burgess IV8d141e02015-12-14 22:00:49 +00003700 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003701 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003702 switch (SCS.First) {
3703 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003704 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3705 FromType = FromAtomic->getValueType().getUnqualifiedType();
3706 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3707 From, /*BasePath=*/nullptr, VK_RValue);
3708 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003709 break;
3710
Eli Friedman946b7b52012-01-24 22:51:26 +00003711 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003712 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003713 ExprResult FromRes = DefaultLvalueConversion(From);
3714 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003715 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003716 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003717 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003718 }
John McCall34376a62010-12-04 03:47:34 +00003719
Douglas Gregor39c16d42008-10-24 04:54:22 +00003720 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003721 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003722 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003723 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003724 break;
3725
3726 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003727 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003728 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003729 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003730 break;
3731
3732 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003733 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003734 }
3735
Richard Smith507840d2011-11-29 22:48:16 +00003736 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003737 switch (SCS.Second) {
3738 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003739 // C++ [except.spec]p5:
3740 // [For] assignment to and initialization of pointers to functions,
3741 // pointers to member functions, and references to functions: the
3742 // target entity shall allow at least the exceptions allowed by the
3743 // source value in the assignment or initialization.
3744 switch (Action) {
3745 case AA_Assigning:
3746 case AA_Initializing:
3747 // Note, function argument passing and returning are initialization.
3748 case AA_Passing:
3749 case AA_Returning:
3750 case AA_Sending:
3751 case AA_Passing_CFAudited:
3752 if (CheckExceptionSpecCompatibility(From, ToType))
3753 return ExprError();
3754 break;
3755
3756 case AA_Casting:
3757 case AA_Converting:
3758 // Casts and implicit conversions are not initialization, so are not
3759 // checked for exception specification mismatches.
3760 break;
3761 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003762 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003763 break;
3764
3765 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003766 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003767 if (ToType->isBooleanType()) {
3768 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3769 SCS.Second == ICK_Integral_Promotion &&
3770 "only enums with fixed underlying type can promote to bool");
3771 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003772 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003773 } else {
3774 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003775 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003776 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003777 break;
3778
3779 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003780 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003781 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003782 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003783 break;
3784
3785 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003786 case ICK_Complex_Conversion: {
3787 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3788 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3789 CastKind CK;
3790 if (FromEl->isRealFloatingType()) {
3791 if (ToEl->isRealFloatingType())
3792 CK = CK_FloatingComplexCast;
3793 else
3794 CK = CK_FloatingComplexToIntegralComplex;
3795 } else if (ToEl->isRealFloatingType()) {
3796 CK = CK_IntegralComplexToFloatingComplex;
3797 } else {
3798 CK = CK_IntegralComplexCast;
3799 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003800 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003801 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003802 break;
John McCall8cb679e2010-11-15 09:13:47 +00003803 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003804
Douglas Gregor39c16d42008-10-24 04:54:22 +00003805 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003806 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003807 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003808 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003809 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00003810 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003811 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003812 break;
3813
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003814 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003815 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003816 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003817 break;
3818
John McCall31168b02011-06-15 23:02:42 +00003819 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003820 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003821 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003822 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00003823 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003824 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003825 diag::ext_typecheck_convert_incompatible_pointer)
3826 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003827 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003828 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003829 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003830 diag::ext_typecheck_convert_incompatible_pointer)
3831 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003832 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00003833
Douglas Gregor33823722011-06-11 01:09:30 +00003834 if (From->getType()->isObjCObjectPointerType() &&
3835 ToType->isObjCObjectPointerType())
3836 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00003837 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
3838 !CheckObjCARCUnavailableWeakConversion(ToType,
3839 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00003840 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003841 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003842 diag::err_arc_weak_unavailable_assign);
3843 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003844 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00003845 diag::err_arc_convesion_of_weak_unavailable)
3846 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00003847 << From->getSourceRange();
3848 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003849
Richard Smith354abec2017-12-08 23:29:59 +00003850 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00003851 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003852 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003853 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00003854
3855 // Make sure we extend blocks if necessary.
3856 // FIXME: doing this here is really ugly.
3857 if (Kind == CK_BlockPointerToObjCPointerCast) {
3858 ExprResult E = From;
3859 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003860 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00003861 }
Brian Kelley11352a82017-03-29 18:09:02 +00003862 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
3863 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00003864 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003865 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003866 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003868
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003869 case ICK_Pointer_Member: {
Richard Smith354abec2017-12-08 23:29:59 +00003870 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00003871 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003872 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003873 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00003874 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003875 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00003876
3877 // We may not have been able to figure out what this member pointer resolved
3878 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00003879 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003880 (void)isCompleteType(From->getExprLoc(), From->getType());
3881 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00003882 }
David Majnemerd96b9972014-08-08 00:10:39 +00003883
Richard Smith507840d2011-11-29 22:48:16 +00003884 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003885 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003886 break;
3887 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003888
Abramo Bagnara7ccce982011-04-07 09:26:19 +00003889 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003890 // Perform half-to-boolean conversion via float.
3891 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003892 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003893 FromType = Context.FloatTy;
3894 }
3895
Richard Smith507840d2011-11-29 22:48:16 +00003896 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003897 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003898 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003899 break;
3900
Douglas Gregor88d292c2010-05-13 16:44:06 +00003901 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00003902 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003903 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003904 ToType.getNonReferenceType(),
3905 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003906 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003907 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00003908 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003909 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00003910
Richard Smith507840d2011-11-29 22:48:16 +00003911 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3912 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003913 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003914 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00003915 }
3916
Douglas Gregor46188682010-05-18 22:42:18 +00003917 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003918 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003919 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003920 break;
3921
George Burgess IVdf1ed002016-01-13 01:52:39 +00003922 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00003923 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00003924 Expr *Elem = prepareVectorSplat(ToType, From).get();
3925 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3926 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003927 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00003928 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003929
Douglas Gregor46188682010-05-18 22:42:18 +00003930 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00003931 // Case 1. x -> _Complex y
3932 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3933 QualType ElType = ToComplex->getElementType();
3934 bool isFloatingComplex = ElType->isRealFloatingType();
3935
3936 // x -> y
3937 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3938 // do nothing
3939 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003940 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003941 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00003942 } else {
3943 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003944 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003945 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00003946 }
3947 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00003948 From = ImpCastExprToType(From, ToType,
3949 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003950 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00003951
3952 // Case 2. _Complex x -> y
3953 } else {
3954 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3955 assert(FromComplex);
3956
3957 QualType ElType = FromComplex->getElementType();
3958 bool isFloatingComplex = ElType->isRealFloatingType();
3959
3960 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00003961 From = ImpCastExprToType(From, ElType,
3962 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00003963 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003964 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003965
3966 // x -> y
3967 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3968 // do nothing
3969 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003970 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003971 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003972 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003973 } else {
3974 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003975 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003976 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003977 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003978 }
3979 }
Douglas Gregor46188682010-05-18 22:42:18 +00003980 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00003981
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00003982 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003983 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003984 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00003985 break;
3986 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003987
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003988 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003989 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003990 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00003991 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3992 if (FromRes.isInvalid())
3993 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003994 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003995 assert ((ConvTy == Sema::Compatible) &&
3996 "Improper transparent union conversion");
3997 (void)ConvTy;
3998 break;
3999 }
4000
Guy Benyei259f9f42013-02-07 16:05:33 +00004001 case ICK_Zero_Event_Conversion:
4002 From = ImpCastExprToType(From, ToType,
4003 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004004 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00004005 break;
4006
Egor Churaev89831422016-12-23 14:55:49 +00004007 case ICK_Zero_Queue_Conversion:
4008 From = ImpCastExprToType(From, ToType,
4009 CK_ZeroToOCLQueue,
4010 From->getValueKind()).get();
4011 break;
4012
Douglas Gregor46188682010-05-18 22:42:18 +00004013 case ICK_Lvalue_To_Rvalue:
4014 case ICK_Array_To_Pointer:
4015 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004016 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00004017 case ICK_Qualification:
4018 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00004019 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00004020 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004021 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004022 }
4023
4024 switch (SCS.Third) {
4025 case ICK_Identity:
4026 // Nothing to do.
4027 break;
4028
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004029 case ICK_Function_Conversion:
4030 // If both sides are functions (or pointers/references to them), there could
4031 // be incompatible exception declarations.
4032 if (CheckExceptionSpecCompatibility(From, ToType))
4033 return ExprError();
4034
4035 From = ImpCastExprToType(From, ToType, CK_NoOp,
4036 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4037 break;
4038
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004039 case ICK_Qualification: {
4040 // The qualification keeps the category of the inner expression, unless the
4041 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00004042 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00004043 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00004044 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004045 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004046
Douglas Gregore981bb02011-03-14 16:13:32 +00004047 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004048 !getLangOpts().WritableStrings) {
4049 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
4050 ? diag::ext_deprecated_string_literal_conversion
4051 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00004052 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004053 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004054
Douglas Gregor39c16d42008-10-24 04:54:22 +00004055 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004056 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004057
Douglas Gregor39c16d42008-10-24 04:54:22 +00004058 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004059 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004060 }
4061
Douglas Gregor298f43d2012-04-12 20:42:30 +00004062 // If this conversion sequence involved a scalar -> atomic conversion, perform
4063 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004064 if (!ToAtomicType.isNull()) {
4065 assert(Context.hasSameType(
4066 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4067 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004068 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004069 }
4070
George Burgess IV8d141e02015-12-14 22:00:49 +00004071 // If this conversion sequence succeeded and involved implicitly converting a
4072 // _Nullable type to a _Nonnull one, complain.
4073 if (CCK == CCK_ImplicitConversion)
4074 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4075 From->getLocStart());
4076
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004077 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004078}
4079
Chandler Carruth8e172c62011-05-01 06:51:22 +00004080/// \brief Check the completeness of a type in a unary type trait.
4081///
4082/// If the particular type trait requires a complete type, tries to complete
4083/// it. If completing the type fails, a diagnostic is emitted and false
4084/// returned. If completing the type succeeds or no completion was required,
4085/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004086static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004087 SourceLocation Loc,
4088 QualType ArgTy) {
4089 // C++0x [meta.unary.prop]p3:
4090 // For all of the class templates X declared in this Clause, instantiating
4091 // that template with a template argument that is a class template
4092 // specialization may result in the implicit instantiation of the template
4093 // argument if and only if the semantics of X require that the argument
4094 // must be a complete type.
4095 // We apply this rule to all the type trait expressions used to implement
4096 // these class templates. We also try to follow any GCC documented behavior
4097 // in these expressions to ensure portability of standard libraries.
4098 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004099 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004100 // is_complete_type somewhat obviously cannot require a complete type.
4101 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004102 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004103
4104 // These traits are modeled on the type predicates in C++0x
4105 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4106 // requiring a complete type, as whether or not they return true cannot be
4107 // impacted by the completeness of the type.
4108 case UTT_IsVoid:
4109 case UTT_IsIntegral:
4110 case UTT_IsFloatingPoint:
4111 case UTT_IsArray:
4112 case UTT_IsPointer:
4113 case UTT_IsLvalueReference:
4114 case UTT_IsRvalueReference:
4115 case UTT_IsMemberFunctionPointer:
4116 case UTT_IsMemberObjectPointer:
4117 case UTT_IsEnum:
4118 case UTT_IsUnion:
4119 case UTT_IsClass:
4120 case UTT_IsFunction:
4121 case UTT_IsReference:
4122 case UTT_IsArithmetic:
4123 case UTT_IsFundamental:
4124 case UTT_IsObject:
4125 case UTT_IsScalar:
4126 case UTT_IsCompound:
4127 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004128 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004129
4130 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4131 // which requires some of its traits to have the complete type. However,
4132 // the completeness of the type cannot impact these traits' semantics, and
4133 // so they don't require it. This matches the comments on these traits in
4134 // Table 49.
4135 case UTT_IsConst:
4136 case UTT_IsVolatile:
4137 case UTT_IsSigned:
4138 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004139
4140 // This type trait always returns false, checking the type is moot.
4141 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004142 return true;
4143
David Majnemer213bea32015-11-16 06:58:51 +00004144 // C++14 [meta.unary.prop]:
4145 // If T is a non-union class type, T shall be a complete type.
4146 case UTT_IsEmpty:
4147 case UTT_IsPolymorphic:
4148 case UTT_IsAbstract:
4149 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4150 if (!RD->isUnion())
4151 return !S.RequireCompleteType(
4152 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4153 return true;
4154
4155 // C++14 [meta.unary.prop]:
4156 // If T is a class type, T shall be a complete type.
4157 case UTT_IsFinal:
4158 case UTT_IsSealed:
4159 if (ArgTy->getAsCXXRecordDecl())
4160 return !S.RequireCompleteType(
4161 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4162 return true;
4163
Richard Smithf03e9082017-06-01 00:28:16 +00004164 // C++1z [meta.unary.prop]:
4165 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004166 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004167 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004168 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004169 case UTT_IsStandardLayout:
4170 case UTT_IsPOD:
4171 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004172 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4173 // or an array of unknown bound. But GCC actually imposes the same constraints
4174 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004175 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004176 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004177 case UTT_HasNothrowConstructor:
4178 case UTT_HasNothrowCopy:
4179 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004180 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004181 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004182 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004183 case UTT_HasTrivialCopy:
4184 case UTT_HasTrivialDestructor:
4185 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004186 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4187 LLVM_FALLTHROUGH;
4188
4189 // C++1z [meta.unary.prop]:
4190 // T shall be a complete type, cv void, or an array of unknown bound.
4191 case UTT_IsDestructible:
4192 case UTT_IsNothrowDestructible:
4193 case UTT_IsTriviallyDestructible:
Erich Keanee63e9d72017-10-24 21:31:50 +00004194 case UTT_HasUniqueObjectRepresentations:
Richard Smithf03e9082017-06-01 00:28:16 +00004195 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004196 return true;
4197
4198 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004199 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004200 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004201}
4202
Joao Matosc9523d42013-03-27 01:34:16 +00004203static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4204 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004205 bool (CXXRecordDecl::*HasTrivial)() const,
4206 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004207 bool (CXXMethodDecl::*IsDesiredOp)() const)
4208{
4209 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4210 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4211 return true;
4212
4213 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4214 DeclarationNameInfo NameInfo(Name, KeyLoc);
4215 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4216 if (Self.LookupQualifiedName(Res, RD)) {
4217 bool FoundOperator = false;
4218 Res.suppressDiagnostics();
4219 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4220 Op != OpEnd; ++Op) {
4221 if (isa<FunctionTemplateDecl>(*Op))
4222 continue;
4223
4224 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4225 if((Operator->*IsDesiredOp)()) {
4226 FoundOperator = true;
4227 const FunctionProtoType *CPT =
4228 Operator->getType()->getAs<FunctionProtoType>();
4229 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Alp Toker73287bf2014-01-20 00:24:09 +00004230 if (!CPT || !CPT->isNothrow(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004231 return false;
4232 }
4233 }
4234 return FoundOperator;
4235 }
4236 return false;
4237}
4238
Alp Toker95e7ff22014-01-01 05:57:51 +00004239static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004240 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004241 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004242
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004243 ASTContext &C = Self.Context;
4244 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004245 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004246 // Type trait expressions corresponding to the primary type category
4247 // predicates in C++0x [meta.unary.cat].
4248 case UTT_IsVoid:
4249 return T->isVoidType();
4250 case UTT_IsIntegral:
4251 return T->isIntegralType(C);
4252 case UTT_IsFloatingPoint:
4253 return T->isFloatingType();
4254 case UTT_IsArray:
4255 return T->isArrayType();
4256 case UTT_IsPointer:
4257 return T->isPointerType();
4258 case UTT_IsLvalueReference:
4259 return T->isLValueReferenceType();
4260 case UTT_IsRvalueReference:
4261 return T->isRValueReferenceType();
4262 case UTT_IsMemberFunctionPointer:
4263 return T->isMemberFunctionPointerType();
4264 case UTT_IsMemberObjectPointer:
4265 return T->isMemberDataPointerType();
4266 case UTT_IsEnum:
4267 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004268 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004269 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004270 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004271 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004272 case UTT_IsFunction:
4273 return T->isFunctionType();
4274
4275 // Type trait expressions which correspond to the convenient composition
4276 // predicates in C++0x [meta.unary.comp].
4277 case UTT_IsReference:
4278 return T->isReferenceType();
4279 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004280 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004281 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004282 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004283 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004284 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004285 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004286 // Note: semantic analysis depends on Objective-C lifetime types to be
4287 // considered scalar types. However, such types do not actually behave
4288 // like scalar types at run time (since they may require retain/release
4289 // operations), so we report them as non-scalar.
4290 if (T->isObjCLifetimeType()) {
4291 switch (T.getObjCLifetime()) {
4292 case Qualifiers::OCL_None:
4293 case Qualifiers::OCL_ExplicitNone:
4294 return true;
4295
4296 case Qualifiers::OCL_Strong:
4297 case Qualifiers::OCL_Weak:
4298 case Qualifiers::OCL_Autoreleasing:
4299 return false;
4300 }
4301 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004302
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004303 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004304 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004305 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004306 case UTT_IsMemberPointer:
4307 return T->isMemberPointerType();
4308
4309 // Type trait expressions which correspond to the type property predicates
4310 // in C++0x [meta.unary.prop].
4311 case UTT_IsConst:
4312 return T.isConstQualified();
4313 case UTT_IsVolatile:
4314 return T.isVolatileQualified();
4315 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004316 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004317 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004318 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004319 case UTT_IsStandardLayout:
4320 return T->isStandardLayoutType();
4321 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004322 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004323 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004324 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004325 case UTT_IsEmpty:
4326 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4327 return !RD->isUnion() && RD->isEmpty();
4328 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004329 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004330 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004331 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004332 return false;
4333 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004334 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004335 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004336 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004337 case UTT_IsAggregate:
4338 // Report vector extensions and complex types as aggregates because they
4339 // support aggregate initialization. GCC mirrors this behavior for vectors
4340 // but not _Complex.
4341 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4342 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004343 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4344 // even then only when it is used with the 'interface struct ...' syntax
4345 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004346 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004347 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004348 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004349 case UTT_IsSealed:
4350 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004351 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004352 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004353 case UTT_IsSigned:
4354 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004355 case UTT_IsUnsigned:
4356 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004357
4358 // Type trait expressions which query classes regarding their construction,
4359 // destruction, and copying. Rather than being based directly on the
4360 // related type predicates in the standard, they are specified by both
4361 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4362 // specifications.
4363 //
4364 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4365 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004366 //
4367 // Note that these builtins do not behave as documented in g++: if a class
4368 // has both a trivial and a non-trivial special member of a particular kind,
4369 // they return false! For now, we emulate this behavior.
4370 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4371 // does not correctly compute triviality in the presence of multiple special
4372 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004373 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004374 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4375 // If __is_pod (type) is true then the trait is true, else if type is
4376 // a cv class or union type (or array thereof) with a trivial default
4377 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004378 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004379 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004380 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4381 return RD->hasTrivialDefaultConstructor() &&
4382 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004383 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004384 case UTT_HasTrivialMoveConstructor:
4385 // This trait is implemented by MSVC 2012 and needed to parse the
4386 // standard library headers. Specifically this is used as the logic
4387 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004388 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004389 return true;
4390 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4391 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4392 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004393 case UTT_HasTrivialCopy:
4394 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4395 // If __is_pod (type) is true or type is a reference type then
4396 // the trait is true, else if type is a cv class or union type
4397 // with a trivial copy constructor ([class.copy]) then the trait
4398 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004399 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004400 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004401 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4402 return RD->hasTrivialCopyConstructor() &&
4403 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004404 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004405 case UTT_HasTrivialMoveAssign:
4406 // This trait is implemented by MSVC 2012 and needed to parse the
4407 // standard library headers. Specifically it is used as the logic
4408 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004409 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004410 return true;
4411 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4412 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4413 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004414 case UTT_HasTrivialAssign:
4415 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4416 // If type is const qualified or is a reference type then the
4417 // trait is false. Otherwise if __is_pod (type) is true then the
4418 // trait is true, else if type is a cv class or union type with
4419 // a trivial copy assignment ([class.copy]) then the trait is
4420 // true, else it is false.
4421 // Note: the const and reference restrictions are interesting,
4422 // given that const and reference members don't prevent a class
4423 // from having a trivial copy assignment operator (but do cause
4424 // errors if the copy assignment operator is actually used, q.v.
4425 // [class.copy]p12).
4426
Richard Smith92f241f2012-12-08 02:53:02 +00004427 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004428 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004429 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004430 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004431 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4432 return RD->hasTrivialCopyAssignment() &&
4433 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004434 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004435 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004436 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004437 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004438 // C++14 [meta.unary.prop]:
4439 // For reference types, is_destructible<T>::value is true.
4440 if (T->isReferenceType())
4441 return true;
4442
4443 // Objective-C++ ARC: autorelease types don't require destruction.
4444 if (T->isObjCLifetimeType() &&
4445 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4446 return true;
4447
4448 // C++14 [meta.unary.prop]:
4449 // For incomplete types and function types, is_destructible<T>::value is
4450 // false.
4451 if (T->isIncompleteType() || T->isFunctionType())
4452 return false;
4453
Richard Smithf03e9082017-06-01 00:28:16 +00004454 // A type that requires destruction (via a non-trivial destructor or ARC
4455 // lifetime semantics) is not trivially-destructible.
4456 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4457 return false;
4458
David Majnemerac73de92015-08-11 03:03:28 +00004459 // C++14 [meta.unary.prop]:
4460 // For object types and given U equal to remove_all_extents_t<T>, if the
4461 // expression std::declval<U&>().~U() is well-formed when treated as an
4462 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4463 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4464 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4465 if (!Destructor)
4466 return false;
4467 // C++14 [dcl.fct.def.delete]p2:
4468 // A program that refers to a deleted function implicitly or
4469 // explicitly, other than to declare it, is ill-formed.
4470 if (Destructor->isDeleted())
4471 return false;
4472 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4473 return false;
4474 if (UTT == UTT_IsNothrowDestructible) {
4475 const FunctionProtoType *CPT =
4476 Destructor->getType()->getAs<FunctionProtoType>();
4477 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4478 if (!CPT || !CPT->isNothrow(C))
4479 return false;
4480 }
4481 }
4482 return true;
4483
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004484 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004485 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004486 // If __is_pod (type) is true or type is a reference type
4487 // then the trait is true, else if type is a cv class or union
4488 // type (or array thereof) with a trivial destructor
4489 // ([class.dtor]) then the trait is true, else it is
4490 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004491 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004492 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004493
John McCall31168b02011-06-15 23:02:42 +00004494 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004495 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004496 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4497 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004498
Richard Smith92f241f2012-12-08 02:53:02 +00004499 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4500 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004501 return false;
4502 // TODO: Propagate nothrowness for implicitly declared special members.
4503 case UTT_HasNothrowAssign:
4504 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4505 // If type is const qualified or is a reference type then the
4506 // trait is false. Otherwise if __has_trivial_assign (type)
4507 // is true then the trait is true, else if type is a cv class
4508 // or union type with copy assignment operators that are known
4509 // not to throw an exception then the trait is true, else it is
4510 // false.
4511 if (C.getBaseElementType(T).isConstQualified())
4512 return false;
4513 if (T->isReferenceType())
4514 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004515 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004516 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004517
Joao Matosc9523d42013-03-27 01:34:16 +00004518 if (const RecordType *RT = T->getAs<RecordType>())
4519 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4520 &CXXRecordDecl::hasTrivialCopyAssignment,
4521 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4522 &CXXMethodDecl::isCopyAssignmentOperator);
4523 return false;
4524 case UTT_HasNothrowMoveAssign:
4525 // This trait is implemented by MSVC 2012 and needed to parse the
4526 // standard library headers. Specifically this is used as the logic
4527 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004528 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004529 return true;
4530
4531 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4532 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4533 &CXXRecordDecl::hasTrivialMoveAssignment,
4534 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4535 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004536 return false;
4537 case UTT_HasNothrowCopy:
4538 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4539 // If __has_trivial_copy (type) is true then the trait is true, else
4540 // if type is a cv class or union type with copy constructors that are
4541 // known not to throw an exception then the trait is true, else it is
4542 // false.
John McCall31168b02011-06-15 23:02:42 +00004543 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004544 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004545 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4546 if (RD->hasTrivialCopyConstructor() &&
4547 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004548 return true;
4549
4550 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004551 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004552 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004553 // A template constructor is never a copy constructor.
4554 // FIXME: However, it may actually be selected at the actual overload
4555 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004556 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004557 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004558 // UsingDecl itself is not a constructor
4559 if (isa<UsingDecl>(ND))
4560 continue;
4561 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004562 if (Constructor->isCopyConstructor(FoundTQs)) {
4563 FoundConstructor = true;
4564 const FunctionProtoType *CPT
4565 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004566 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4567 if (!CPT)
4568 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004569 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004570 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004571 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004572 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004573 }
4574 }
4575
Richard Smith938f40b2011-06-11 17:19:42 +00004576 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004577 }
4578 return false;
4579 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004580 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004581 // If __has_trivial_constructor (type) is true then the trait is
4582 // true, else if type is a cv class or union type (or array
4583 // thereof) with a default constructor that is known not to
4584 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004585 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004586 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004587 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4588 if (RD->hasTrivialDefaultConstructor() &&
4589 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004590 return true;
4591
Alp Tokerb4bca412014-01-20 00:23:47 +00004592 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004593 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004594 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004595 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004596 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004597 // UsingDecl itself is not a constructor
4598 if (isa<UsingDecl>(ND))
4599 continue;
4600 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004601 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004602 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004603 const FunctionProtoType *CPT
4604 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004605 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4606 if (!CPT)
4607 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004608 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004609 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004610 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004611 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004612 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004613 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004614 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004615 }
4616 return false;
4617 case UTT_HasVirtualDestructor:
4618 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4619 // If type is a class type with a virtual destructor ([class.dtor])
4620 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004621 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004622 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004623 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004624 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004625
4626 // These type trait expressions are modeled on the specifications for the
4627 // Embarcadero C++0x type trait functions:
4628 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4629 case UTT_IsCompleteType:
4630 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4631 // Returns True if and only if T is a complete type at the point of the
4632 // function call.
4633 return !T->isIncompleteType();
Erich Keanee63e9d72017-10-24 21:31:50 +00004634 case UTT_HasUniqueObjectRepresentations:
Erich Keane8a6b7402017-11-30 16:37:02 +00004635 return C.hasUniqueObjectRepresentations(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004636 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004637}
Sebastian Redl5822f082009-02-07 20:10:22 +00004638
Alp Tokercbb90342013-12-13 20:49:58 +00004639static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4640 QualType RhsT, SourceLocation KeyLoc);
4641
Douglas Gregor29c42f22012-02-24 07:38:34 +00004642static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4643 ArrayRef<TypeSourceInfo *> Args,
4644 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004645 if (Kind <= UTT_Last)
4646 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4647
Alp Tokercbb90342013-12-13 20:49:58 +00004648 if (Kind <= BTT_Last)
4649 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4650 Args[1]->getType(), RParenLoc);
4651
Douglas Gregor29c42f22012-02-24 07:38:34 +00004652 switch (Kind) {
Alp Toker73287bf2014-01-20 00:24:09 +00004653 case clang::TT_IsConstructible:
4654 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004655 case clang::TT_IsTriviallyConstructible: {
4656 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004657 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004658 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004659 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004660 // definition for is_constructible, as defined below, is known to call
4661 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004662 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004663 // The predicate condition for a template specialization
4664 // is_constructible<T, Args...> shall be satisfied if and only if the
4665 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004666 // variable t:
4667 //
4668 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004669 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004670
4671 // Precondition: T and all types in the parameter pack Args shall be
4672 // complete types, (possibly cv-qualified) void, or arrays of
4673 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004674 for (const auto *TSI : Args) {
4675 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004676 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004677 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004678
Simon Pilgrim75c26882016-09-30 14:25:09 +00004679 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004680 diag::err_incomplete_type_used_in_type_trait_expr))
4681 return false;
4682 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004683
David Majnemer9658ecc2015-11-13 05:32:43 +00004684 // Make sure the first argument is not incomplete nor a function type.
4685 QualType T = Args[0]->getType();
4686 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004687 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004688
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004689 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004690 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004691 if (RD && RD->isAbstract())
4692 return false;
4693
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004694 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4695 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004696 ArgExprs.reserve(Args.size() - 1);
4697 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004698 QualType ArgTy = Args[I]->getType();
4699 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4700 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004701 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004702 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4703 ArgTy.getNonLValueExprType(S.Context),
4704 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004705 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004706 for (Expr &E : OpaqueArgExprs)
4707 ArgExprs.push_back(&E);
4708
Simon Pilgrim75c26882016-09-30 14:25:09 +00004709 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004710 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004711 EnterExpressionEvaluationContext Unevaluated(
4712 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004713 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4714 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4715 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4716 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4717 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004718 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004719 if (Init.Failed())
4720 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004721
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004722 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004723 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4724 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004725
Alp Toker73287bf2014-01-20 00:24:09 +00004726 if (Kind == clang::TT_IsConstructible)
4727 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004728
Alp Toker73287bf2014-01-20 00:24:09 +00004729 if (Kind == clang::TT_IsNothrowConstructible)
4730 return S.canThrow(Result.get()) == CT_Cannot;
4731
4732 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004733 // Under Objective-C ARC and Weak, if the destination has non-trivial
4734 // Objective-C lifetime, this is a non-trivial construction.
4735 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00004736 return false;
4737
4738 // The initialization succeeded; now make sure there are no non-trivial
4739 // calls.
4740 return !Result.get()->hasNonTrivialCall(S.Context);
4741 }
4742
4743 llvm_unreachable("unhandled type trait");
4744 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004745 }
Alp Tokercbb90342013-12-13 20:49:58 +00004746 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004747 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004748
Douglas Gregor29c42f22012-02-24 07:38:34 +00004749 return false;
4750}
4751
Simon Pilgrim75c26882016-09-30 14:25:09 +00004752ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4753 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004754 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004755 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004756
Alp Toker95e7ff22014-01-01 05:57:51 +00004757 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4758 *this, Kind, KWLoc, Args[0]->getType()))
4759 return ExprError();
4760
Douglas Gregor29c42f22012-02-24 07:38:34 +00004761 bool Dependent = false;
4762 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4763 if (Args[I]->getType()->isDependentType()) {
4764 Dependent = true;
4765 break;
4766 }
4767 }
Alp Tokercbb90342013-12-13 20:49:58 +00004768
4769 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004770 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004771 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4772
4773 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4774 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004775}
4776
Alp Toker88f64e62013-12-13 21:19:30 +00004777ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4778 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004779 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004780 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004781 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00004782
Douglas Gregor29c42f22012-02-24 07:38:34 +00004783 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4784 TypeSourceInfo *TInfo;
4785 QualType T = GetTypeFromParser(Args[I], &TInfo);
4786 if (!TInfo)
4787 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004788
4789 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004790 }
Alp Tokercbb90342013-12-13 20:49:58 +00004791
Douglas Gregor29c42f22012-02-24 07:38:34 +00004792 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4793}
4794
Alp Tokercbb90342013-12-13 20:49:58 +00004795static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4796 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004797 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4798 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004799
4800 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004801 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004802 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004803 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004804 // Base and Derived are not unions and name the same class type without
4805 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004806
John McCall388ef532011-01-28 22:02:36 +00004807 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00004808 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00004809 if (!rhsRecord || !lhsRecord) {
4810 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
4811 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
4812 if (!LHSObjTy || !RHSObjTy)
4813 return false;
4814
4815 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
4816 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
4817 if (!BaseInterface || !DerivedInterface)
4818 return false;
4819
4820 if (Self.RequireCompleteType(
4821 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
4822 return false;
4823
4824 return BaseInterface->isSuperClassOf(DerivedInterface);
4825 }
John McCall388ef532011-01-28 22:02:36 +00004826
4827 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4828 == (lhsRecord == rhsRecord));
4829
4830 if (lhsRecord == rhsRecord)
4831 return !lhsRecord->getDecl()->isUnion();
4832
4833 // C++0x [meta.rel]p2:
4834 // If Base and Derived are class types and are different types
4835 // (ignoring possible cv-qualifiers) then Derived shall be a
4836 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004837 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00004838 diag::err_incomplete_type_used_in_type_trait_expr))
4839 return false;
4840
4841 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4842 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4843 }
John Wiegley65497cc2011-04-27 23:09:49 +00004844 case BTT_IsSame:
4845 return Self.Context.hasSameType(LhsT, RhsT);
George Burgess IV31ac1fa2017-10-16 22:58:37 +00004846 case BTT_TypeCompatible: {
4847 // GCC ignores cv-qualifiers on arrays for this builtin.
4848 Qualifiers LhsQuals, RhsQuals;
4849 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
4850 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
4851 return Self.Context.typesAreCompatible(Lhs, Rhs);
4852 }
John Wiegley65497cc2011-04-27 23:09:49 +00004853 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00004854 case BTT_IsConvertibleTo: {
4855 // C++0x [meta.rel]p4:
4856 // Given the following function prototype:
4857 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004858 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00004859 // typename add_rvalue_reference<T>::type create();
4860 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004861 // the predicate condition for a template specialization
4862 // is_convertible<From, To> shall be satisfied if and only if
4863 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00004864 // well-formed, including any implicit conversions to the return
4865 // type of the function:
4866 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004867 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00004868 // return create<From>();
4869 // }
4870 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004871 // Access checking is performed as if in a context unrelated to To and
4872 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00004873 // of the return-statement (including conversions to the return type)
4874 // is considered.
4875 //
4876 // We model the initialization as a copy-initialization of a temporary
4877 // of the appropriate type, which for this expression is identical to the
4878 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004879
4880 // Functions aren't allowed to return function or array types.
4881 if (RhsT->isFunctionType() || RhsT->isArrayType())
4882 return false;
4883
4884 // A return statement in a void function must have void type.
4885 if (RhsT->isVoidType())
4886 return LhsT->isVoidType();
4887
4888 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00004889 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004890 return false;
4891
4892 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00004893 if (LhsT->isObjectType() || LhsT->isFunctionType())
4894 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004895
4896 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00004897 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00004898 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00004899 Expr::getValueKindForType(LhsT));
4900 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004901 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00004902 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004903
4904 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00004905 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004906 EnterExpressionEvaluationContext Unevaluated(
4907 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00004908 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4909 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004910 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004911 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00004912 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00004913
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004914 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00004915 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4916 }
Alp Toker73287bf2014-01-20 00:24:09 +00004917
David Majnemerb3d96882016-05-23 17:21:55 +00004918 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00004919 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00004920 case BTT_IsTriviallyAssignable: {
4921 // C++11 [meta.unary.prop]p3:
4922 // is_trivially_assignable is defined as:
4923 // is_assignable<T, U>::value is true and the assignment, as defined by
4924 // is_assignable, is known to call no operation that is not trivial
4925 //
4926 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004927 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00004928 // treated as an unevaluated operand (Clause 5).
4929 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004930 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00004931 // void, or arrays of unknown bound.
4932 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004933 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004934 diag::err_incomplete_type_used_in_type_trait_expr))
4935 return false;
4936 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004937 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004938 diag::err_incomplete_type_used_in_type_trait_expr))
4939 return false;
4940
4941 // cv void is never assignable.
4942 if (LhsT->isVoidType() || RhsT->isVoidType())
4943 return false;
4944
Simon Pilgrim75c26882016-09-30 14:25:09 +00004945 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00004946 // declval<U>().
4947 if (LhsT->isObjectType() || LhsT->isFunctionType())
4948 LhsT = Self.Context.getRValueReferenceType(LhsT);
4949 if (RhsT->isObjectType() || RhsT->isFunctionType())
4950 RhsT = Self.Context.getRValueReferenceType(RhsT);
4951 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4952 Expr::getValueKindForType(LhsT));
4953 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4954 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004955
4956 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00004957 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004958 EnterExpressionEvaluationContext Unevaluated(
4959 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004960 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
Erich Keane1a3b8fd2017-12-12 16:22:31 +00004961 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004962 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4963 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004964 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4965 return false;
4966
David Majnemerb3d96882016-05-23 17:21:55 +00004967 if (BTT == BTT_IsAssignable)
4968 return true;
4969
Alp Toker73287bf2014-01-20 00:24:09 +00004970 if (BTT == BTT_IsNothrowAssignable)
4971 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004972
Alp Toker73287bf2014-01-20 00:24:09 +00004973 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004974 // Under Objective-C ARC and Weak, if the destination has non-trivial
4975 // Objective-C lifetime, this is a non-trivial assignment.
4976 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00004977 return false;
4978
4979 return !Result.get()->hasNonTrivialCall(Self.Context);
4980 }
4981
4982 llvm_unreachable("unhandled type trait");
4983 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00004984 }
Alp Tokercbb90342013-12-13 20:49:58 +00004985 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004986 }
4987 llvm_unreachable("Unknown type trait or not implemented");
4988}
4989
John Wiegley6242b6a2011-04-28 00:16:57 +00004990ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4991 SourceLocation KWLoc,
4992 ParsedType Ty,
4993 Expr* DimExpr,
4994 SourceLocation RParen) {
4995 TypeSourceInfo *TSInfo;
4996 QualType T = GetTypeFromParser(Ty, &TSInfo);
4997 if (!TSInfo)
4998 TSInfo = Context.getTrivialTypeSourceInfo(T);
4999
5000 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5001}
5002
5003static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5004 QualType T, Expr *DimExpr,
5005 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005006 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00005007
5008 switch(ATT) {
5009 case ATT_ArrayRank:
5010 if (T->isArrayType()) {
5011 unsigned Dim = 0;
5012 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5013 ++Dim;
5014 T = AT->getElementType();
5015 }
5016 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00005017 }
John Wiegleyd3522222011-04-28 02:06:46 +00005018 return 0;
5019
John Wiegley6242b6a2011-04-28 00:16:57 +00005020 case ATT_ArrayExtent: {
5021 llvm::APSInt Value;
5022 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00005023 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00005024 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00005025 false).isInvalid())
5026 return 0;
5027 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00005028 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5029 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00005030 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00005031 }
Richard Smithf4c51d92012-02-04 09:53:13 +00005032 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00005033
5034 if (T->isArrayType()) {
5035 unsigned D = 0;
5036 bool Matched = false;
5037 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5038 if (Dim == D) {
5039 Matched = true;
5040 break;
5041 }
5042 ++D;
5043 T = AT->getElementType();
5044 }
5045
John Wiegleyd3522222011-04-28 02:06:46 +00005046 if (Matched && T->isArrayType()) {
5047 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5048 return CAT->getSize().getLimitedValue();
5049 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005050 }
John Wiegleyd3522222011-04-28 02:06:46 +00005051 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005052 }
5053 }
5054 llvm_unreachable("Unknown type trait or not implemented");
5055}
5056
5057ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5058 SourceLocation KWLoc,
5059 TypeSourceInfo *TSInfo,
5060 Expr* DimExpr,
5061 SourceLocation RParen) {
5062 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005063
Chandler Carruthc5276e52011-05-01 08:48:21 +00005064 // FIXME: This should likely be tracked as an APInt to remove any host
5065 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005066 uint64_t Value = 0;
5067 if (!T->isDependentType())
5068 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5069
Chandler Carruthc5276e52011-05-01 08:48:21 +00005070 // While the specification for these traits from the Embarcadero C++
5071 // compiler's documentation says the return type is 'unsigned int', Clang
5072 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5073 // compiler, there is no difference. On several other platforms this is an
5074 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005075 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5076 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005077}
5078
John Wiegleyf9f65842011-04-25 06:54:41 +00005079ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005080 SourceLocation KWLoc,
5081 Expr *Queried,
5082 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005083 // If error parsing the expression, ignore.
5084 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005085 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005086
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005087 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005088
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005089 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005090}
5091
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005092static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5093 switch (ET) {
5094 case ET_IsLValueExpr: return E->isLValue();
5095 case ET_IsRValueExpr: return E->isRValue();
5096 }
5097 llvm_unreachable("Expression trait not covered by switch");
5098}
5099
John Wiegleyf9f65842011-04-25 06:54:41 +00005100ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005101 SourceLocation KWLoc,
5102 Expr *Queried,
5103 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005104 if (Queried->isTypeDependent()) {
5105 // Delay type-checking for type-dependent expressions.
5106 } else if (Queried->getType()->isPlaceholderType()) {
5107 ExprResult PE = CheckPlaceholderExpr(Queried);
5108 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005109 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005110 }
5111
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005112 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005113
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005114 return new (Context)
5115 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005116}
5117
Richard Trieu82402a02011-09-15 21:56:47 +00005118QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005119 ExprValueKind &VK,
5120 SourceLocation Loc,
5121 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005122 assert(!LHS.get()->getType()->isPlaceholderType() &&
5123 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005124 "placeholders should have been weeded out by now");
5125
Richard Smith4baaa5a2016-12-03 01:14:32 +00005126 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5127 // temporary materialization conversion otherwise.
5128 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005129 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005130 else if (LHS.get()->isRValue())
5131 LHS = TemporaryMaterializationConversion(LHS.get());
5132 if (LHS.isInvalid())
5133 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005134
5135 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005136 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005137 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005138
Sebastian Redl5822f082009-02-07 20:10:22 +00005139 const char *OpSpelling = isIndirect ? "->*" : ".*";
5140 // C++ 5.5p2
5141 // The binary operator .* [p3: ->*] binds its second operand, which shall
5142 // be of type "pointer to member of T" (where T is a completely-defined
5143 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005144 QualType RHSType = RHS.get()->getType();
5145 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005146 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005147 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005148 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005149 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005150 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005151
Sebastian Redl5822f082009-02-07 20:10:22 +00005152 QualType Class(MemPtr->getClass(), 0);
5153
Douglas Gregord07ba342010-10-13 20:41:14 +00005154 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5155 // member pointer points must be completely-defined. However, there is no
5156 // reason for this semantic distinction, and the rule is not enforced by
5157 // other compilers. Therefore, we do not check this property, as it is
5158 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005159
Sebastian Redl5822f082009-02-07 20:10:22 +00005160 // C++ 5.5p2
5161 // [...] to its first operand, which shall be of class T or of a class of
5162 // which T is an unambiguous and accessible base class. [p3: a pointer to
5163 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005164 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005165 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005166 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5167 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005168 else {
5169 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005170 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005171 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005172 return QualType();
5173 }
5174 }
5175
Richard Trieu82402a02011-09-15 21:56:47 +00005176 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005177 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005178 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5179 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005180 return QualType();
5181 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005182
Richard Smith0f59cb32015-12-18 21:45:41 +00005183 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005184 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005185 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005186 return QualType();
5187 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005188
5189 CXXCastPath BasePath;
5190 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5191 SourceRange(LHS.get()->getLocStart(),
5192 RHS.get()->getLocEnd()),
5193 &BasePath))
5194 return QualType();
5195
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005196 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005197 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5198 if (isIndirect)
5199 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005200 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005201 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005202 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005203 }
5204
Richard Trieu82402a02011-09-15 21:56:47 +00005205 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005206 // Diagnose use of pointer-to-member type which when used as
5207 // the functional cast in a pointer-to-member expression.
5208 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5209 return QualType();
5210 }
John McCall7decc9e2010-11-18 06:31:45 +00005211
Sebastian Redl5822f082009-02-07 20:10:22 +00005212 // C++ 5.5p2
5213 // The result is an object or a function of the type specified by the
5214 // second operand.
5215 // The cv qualifiers are the union of those in the pointer and the left side,
5216 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005217 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005218 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005219
Douglas Gregor1d042092011-01-26 16:40:18 +00005220 // C++0x [expr.mptr.oper]p6:
5221 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005222 // ill-formed if the second operand is a pointer to member function with
5223 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5224 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005225 // is a pointer to member function with ref-qualifier &&.
5226 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5227 switch (Proto->getRefQualifier()) {
5228 case RQ_None:
5229 // Do nothing
5230 break;
5231
5232 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005233 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5234 // C++2a allows functions with ref-qualifier & if they are also 'const'.
5235 if (Proto->isConst())
5236 Diag(Loc, getLangOpts().CPlusPlus2a
5237 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5238 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5239 else
5240 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5241 << RHSType << 1 << LHS.get()->getSourceRange();
5242 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005243 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005244
Douglas Gregor1d042092011-01-26 16:40:18 +00005245 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005246 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005247 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005248 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005249 break;
5250 }
5251 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005252
John McCall7decc9e2010-11-18 06:31:45 +00005253 // C++ [expr.mptr.oper]p6:
5254 // The result of a .* expression whose second operand is a pointer
5255 // to a data member is of the same value category as its
5256 // first operand. The result of a .* expression whose second
5257 // operand is a pointer to a member function is a prvalue. The
5258 // result of an ->* expression is an lvalue if its second operand
5259 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005260 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005261 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005262 return Context.BoundMemberTy;
5263 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005264 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005265 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005266 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005267 }
John McCall7decc9e2010-11-18 06:31:45 +00005268
Sebastian Redl5822f082009-02-07 20:10:22 +00005269 return Result;
5270}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005271
Richard Smith2414bca2016-04-25 19:30:37 +00005272/// \brief Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005273///
5274/// This is part of the parameter validation for the ? operator. If either
5275/// value operand is a class type, the two operands are attempted to be
5276/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005277/// It returns true if the program is ill-formed and has already been diagnosed
5278/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005279static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5280 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005281 bool &HaveConversion,
5282 QualType &ToType) {
5283 HaveConversion = false;
5284 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005285
5286 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005287 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005288 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005289 // The process for determining whether an operand expression E1 of type T1
5290 // can be converted to match an operand expression E2 of type T2 is defined
5291 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005292 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5293 // implicitly converted to type "lvalue reference to T2", subject to the
5294 // constraint that in the conversion the reference must bind directly to
5295 // an lvalue.
5296 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5297 // implicitly conveted to the type "rvalue reference to R2", subject to
5298 // the constraint that the reference must bind directly.
5299 if (To->isLValue() || To->isXValue()) {
5300 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5301 : Self.Context.getRValueReferenceType(ToType);
5302
Douglas Gregor838fcc32010-03-26 20:14:36 +00005303 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005304
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005305 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005306 if (InitSeq.isDirectReferenceBinding()) {
5307 ToType = T;
5308 HaveConversion = true;
5309 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005311
Douglas Gregor838fcc32010-03-26 20:14:36 +00005312 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005313 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005314 }
John McCall65eb8792010-02-25 01:37:24 +00005315
Sebastian Redl1a99f442009-04-16 17:51:27 +00005316 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5317 // -- if E1 and E2 have class type, and the underlying class types are
5318 // the same or one is a base class of the other:
5319 QualType FTy = From->getType();
5320 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005321 const RecordType *FRec = FTy->getAs<RecordType>();
5322 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005323 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005324 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5325 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5326 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005327 // E1 can be converted to match E2 if the class of T2 is the
5328 // same type as, or a base class of, the class of T1, and
5329 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005330 if (FRec == TRec || FDerivedFromT) {
5331 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005332 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005333 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005334 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005335 HaveConversion = true;
5336 return false;
5337 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005338
Douglas Gregor838fcc32010-03-26 20:14:36 +00005339 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005340 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005341 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005342 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005343
Douglas Gregor838fcc32010-03-26 20:14:36 +00005344 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005345 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005346
Douglas Gregor838fcc32010-03-26 20:14:36 +00005347 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5348 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005349 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005350 // an rvalue).
5351 //
5352 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5353 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005354 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005355
Douglas Gregor838fcc32010-03-26 20:14:36 +00005356 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005357 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005358 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005359 ToType = TTy;
5360 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005361 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005362
Sebastian Redl1a99f442009-04-16 17:51:27 +00005363 return false;
5364}
5365
5366/// \brief Try to find a common type for two according to C++0x 5.16p5.
5367///
5368/// This is part of the parameter validation for the ? operator. If either
5369/// value operand is a class type, overload resolution is used to find a
5370/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005371static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005372 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005373 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005374 OverloadCandidateSet CandidateSet(QuestionLoc,
5375 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005376 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005377 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005378
5379 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005380 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005381 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005382 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005383 ExprResult LHSRes = Self.PerformImplicitConversion(
5384 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5385 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005386 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005387 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005388 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005389
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005390 ExprResult RHSRes = Self.PerformImplicitConversion(
5391 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5392 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005393 if (RHSRes.isInvalid())
5394 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005395 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005396 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005397 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005398 return false;
John Wiegley01296292011-04-08 18:41:53 +00005399 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005400
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005401 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005402
5403 // Emit a better diagnostic if one of the expressions is a null pointer
5404 // constant and the other is a pointer type. In this case, the user most
5405 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005406 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005407 return true;
5408
5409 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005410 << LHS.get()->getType() << RHS.get()->getType()
5411 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005412 return true;
5413
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005414 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005415 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005416 << LHS.get()->getType() << RHS.get()->getType()
5417 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005418 // FIXME: Print the possible common types by printing the return types of
5419 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005420 break;
5421
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005422 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005423 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005424 }
5425 return true;
5426}
5427
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005428/// \brief Perform an "extended" implicit conversion as returned by
5429/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005430static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005431 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005432 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005433 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005434 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005435 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005436 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005437 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005438 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005439
John Wiegley01296292011-04-08 18:41:53 +00005440 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005441 return false;
5442}
5443
Sebastian Redl1a99f442009-04-16 17:51:27 +00005444/// \brief Check the operands of ?: under C++ semantics.
5445///
5446/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5447/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005448QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5449 ExprResult &RHS, ExprValueKind &VK,
5450 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005451 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005452 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5453 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005454
Richard Smith45edb702012-08-07 22:06:48 +00005455 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005456 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005457 //
5458 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5459 // a is that of a integer vector with the same number of elements and
5460 // size as the vectors of b and c. If one of either b or c is a scalar
5461 // it is implicitly converted to match the type of the vector.
5462 // Otherwise the expression is ill-formed. If both b and c are scalars,
5463 // then b and c are checked and converted to the type of a if possible.
5464 // Unlike the OpenCL ?: operator, the expression is evaluated as
5465 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005466 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005467 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005468 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005469 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005470 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005471 }
5472
John McCall7decc9e2010-11-18 06:31:45 +00005473 // Assume r-value.
5474 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005475 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005476
Sebastian Redl1a99f442009-04-16 17:51:27 +00005477 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005478 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005479 return Context.DependentTy;
5480
Richard Smith45edb702012-08-07 22:06:48 +00005481 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005482 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005483 QualType LTy = LHS.get()->getType();
5484 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005485 bool LVoid = LTy->isVoidType();
5486 bool RVoid = RTy->isVoidType();
5487 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005488 // ... one of the following shall hold:
5489 // -- The second or the third operand (but not both) is a (possibly
5490 // parenthesized) throw-expression; the result is of the type
5491 // and value category of the other.
5492 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5493 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5494 if (LThrow != RThrow) {
5495 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5496 VK = NonThrow->getValueKind();
5497 // DR (no number yet): the result is a bit-field if the
5498 // non-throw-expression operand is a bit-field.
5499 OK = NonThrow->getObjectKind();
5500 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005501 }
5502
Sebastian Redl1a99f442009-04-16 17:51:27 +00005503 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005504 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005505 if (LVoid && RVoid)
5506 return Context.VoidTy;
5507
5508 // Neither holds, error.
5509 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5510 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005511 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005512 return QualType();
5513 }
5514
5515 // Neither is void.
5516
Richard Smithf2b084f2012-08-08 06:13:49 +00005517 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005518 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005519 // either has (cv) class type [...] an attempt is made to convert each of
5520 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005521 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005522 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005523 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005524 QualType L2RType, R2LType;
5525 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005526 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005527 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005528 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005529 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005530
Sebastian Redl1a99f442009-04-16 17:51:27 +00005531 // If both can be converted, [...] the program is ill-formed.
5532 if (HaveL2R && HaveR2L) {
5533 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005534 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005535 return QualType();
5536 }
5537
5538 // If exactly one conversion is possible, that conversion is applied to
5539 // the chosen operand and the converted operands are used in place of the
5540 // original operands for the remainder of this section.
5541 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005542 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005543 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005544 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005545 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005546 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005547 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005548 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005549 }
5550 }
5551
Richard Smithf2b084f2012-08-08 06:13:49 +00005552 // C++11 [expr.cond]p3
5553 // if both are glvalues of the same value category and the same type except
5554 // for cv-qualification, an attempt is made to convert each of those
5555 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005556 // FIXME:
5557 // Resolving a defect in P0012R1: we extend this to cover all cases where
5558 // one of the operands is reference-compatible with the other, in order
5559 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005560 ExprValueKind LVK = LHS.get()->getValueKind();
5561 ExprValueKind RVK = RHS.get()->getValueKind();
5562 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005563 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005564 // DerivedToBase was already handled by the class-specific case above.
5565 // FIXME: Should we allow ObjC conversions here?
5566 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5567 if (CompareReferenceRelationship(
5568 QuestionLoc, LTy, RTy, DerivedToBase,
5569 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005570 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5571 // [...] subject to the constraint that the reference must bind
5572 // directly [...]
5573 !RHS.get()->refersToBitField() &&
5574 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005575 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005576 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005577 } else if (CompareReferenceRelationship(
5578 QuestionLoc, RTy, LTy, DerivedToBase,
5579 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005580 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5581 !LHS.get()->refersToBitField() &&
5582 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005583 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5584 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005585 }
5586 }
5587
5588 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005589 // If the second and third operands are glvalues of the same value
5590 // category and have the same type, the result is of that type and
5591 // value category and it is a bit-field if the second or the third
5592 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005593 // We only extend this to bitfields, not to the crazy other kinds of
5594 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005595 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005596 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005597 LHS.get()->isOrdinaryOrBitFieldObject() &&
5598 RHS.get()->isOrdinaryOrBitFieldObject()) {
5599 VK = LHS.get()->getValueKind();
5600 if (LHS.get()->getObjectKind() == OK_BitField ||
5601 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005602 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005603
5604 // If we have function pointer types, unify them anyway to unify their
5605 // exception specifications, if any.
5606 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5607 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005608 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005609 /*ConvertArgs*/false);
5610 LTy = Context.getQualifiedType(LTy, Qs);
5611
5612 assert(!LTy.isNull() && "failed to find composite pointer type for "
5613 "canonically equivalent function ptr types");
5614 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5615 }
5616
John McCall7decc9e2010-11-18 06:31:45 +00005617 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005618 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005619
Richard Smithf2b084f2012-08-08 06:13:49 +00005620 // C++11 [expr.cond]p5
5621 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005622 // do not have the same type, and either has (cv) class type, ...
5623 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5624 // ... overload resolution is used to determine the conversions (if any)
5625 // to be applied to the operands. If the overload resolution fails, the
5626 // program is ill-formed.
5627 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5628 return QualType();
5629 }
5630
Richard Smithf2b084f2012-08-08 06:13:49 +00005631 // C++11 [expr.cond]p6
5632 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005633 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005634 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5635 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005636 if (LHS.isInvalid() || RHS.isInvalid())
5637 return QualType();
5638 LTy = LHS.get()->getType();
5639 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005640
5641 // After those conversions, one of the following shall hold:
5642 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005643 // is of that type. If the operands have class type, the result
5644 // is a prvalue temporary of the result type, which is
5645 // copy-initialized from either the second operand or the third
5646 // operand depending on the value of the first operand.
5647 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5648 if (LTy->isRecordType()) {
5649 // The operands have class type. Make a temporary copy.
5650 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005651
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005652 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5653 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005654 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005655 if (LHSCopy.isInvalid())
5656 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005657
5658 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5659 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005660 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005661 if (RHSCopy.isInvalid())
5662 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005663
John Wiegley01296292011-04-08 18:41:53 +00005664 LHS = LHSCopy;
5665 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005666 }
5667
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005668 // If we have function pointer types, unify them anyway to unify their
5669 // exception specifications, if any.
5670 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5671 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5672 assert(!LTy.isNull() && "failed to find composite pointer type for "
5673 "canonically equivalent function ptr types");
5674 }
5675
Sebastian Redl1a99f442009-04-16 17:51:27 +00005676 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005677 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005678
Douglas Gregor46188682010-05-18 22:42:18 +00005679 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005680 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005681 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5682 /*AllowBothBool*/true,
5683 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005684
Sebastian Redl1a99f442009-04-16 17:51:27 +00005685 // -- The second and third operands have arithmetic or enumeration type;
5686 // the usual arithmetic conversions are performed to bring them to a
5687 // common type, and the result is of that type.
5688 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005689 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005690 if (LHS.isInvalid() || RHS.isInvalid())
5691 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005692 if (ResTy.isNull()) {
5693 Diag(QuestionLoc,
5694 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5695 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5696 return QualType();
5697 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005698
5699 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5700 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5701
5702 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005703 }
5704
5705 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005706 // type and the other is a null pointer constant, or both are null
5707 // pointer constants, at least one of which is non-integral; pointer
5708 // conversions and qualification conversions are performed to bring them
5709 // to their composite pointer type. The result is of the composite
5710 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005711 // -- The second and third operands have pointer to member type, or one has
5712 // pointer to member type and the other is a null pointer constant;
5713 // pointer to member conversions and qualification conversions are
5714 // performed to bring them to a common type, whose cv-qualification
5715 // shall match the cv-qualification of either the second or the third
5716 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005717 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5718 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005719 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005720
Douglas Gregor697a3912010-04-01 22:47:07 +00005721 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005722 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5723 if (!Composite.isNull())
5724 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005725
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005726 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005727 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005728 return QualType();
5729
Sebastian Redl1a99f442009-04-16 17:51:27 +00005730 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005731 << LHS.get()->getType() << RHS.get()->getType()
5732 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005733 return QualType();
5734}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005735
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005736static FunctionProtoType::ExceptionSpecInfo
5737mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5738 FunctionProtoType::ExceptionSpecInfo ESI2,
5739 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5740 ExceptionSpecificationType EST1 = ESI1.Type;
5741 ExceptionSpecificationType EST2 = ESI2.Type;
5742
5743 // If either of them can throw anything, that is the result.
5744 if (EST1 == EST_None) return ESI1;
5745 if (EST2 == EST_None) return ESI2;
5746 if (EST1 == EST_MSAny) return ESI1;
5747 if (EST2 == EST_MSAny) return ESI2;
5748
5749 // If either of them is non-throwing, the result is the other.
5750 if (EST1 == EST_DynamicNone) return ESI2;
5751 if (EST2 == EST_DynamicNone) return ESI1;
5752 if (EST1 == EST_BasicNoexcept) return ESI2;
5753 if (EST2 == EST_BasicNoexcept) return ESI1;
5754
5755 // If either of them is a non-value-dependent computed noexcept, that
5756 // determines the result.
5757 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5758 !ESI2.NoexceptExpr->isValueDependent())
5759 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5760 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5761 !ESI1.NoexceptExpr->isValueDependent())
5762 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5763 // If we're left with value-dependent computed noexcept expressions, we're
5764 // stuck. Before C++17, we can just drop the exception specification entirely,
5765 // since it's not actually part of the canonical type. And this should never
5766 // happen in C++17, because it would mean we were computing the composite
5767 // pointer type of dependent types, which should never happen.
5768 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005769 assert(!S.getLangOpts().CPlusPlus17 &&
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005770 "computing composite pointer type of dependent types");
5771 return FunctionProtoType::ExceptionSpecInfo();
5772 }
5773
5774 // Switch over the possibilities so that people adding new values know to
5775 // update this function.
5776 switch (EST1) {
5777 case EST_None:
5778 case EST_DynamicNone:
5779 case EST_MSAny:
5780 case EST_BasicNoexcept:
5781 case EST_ComputedNoexcept:
5782 llvm_unreachable("handled above");
5783
5784 case EST_Dynamic: {
5785 // This is the fun case: both exception specifications are dynamic. Form
5786 // the union of the two lists.
5787 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5788 llvm::SmallPtrSet<QualType, 8> Found;
5789 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5790 for (QualType E : Exceptions)
5791 if (Found.insert(S.Context.getCanonicalType(E)).second)
5792 ExceptionTypeStorage.push_back(E);
5793
5794 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5795 Result.Exceptions = ExceptionTypeStorage;
5796 return Result;
5797 }
5798
5799 case EST_Unevaluated:
5800 case EST_Uninstantiated:
5801 case EST_Unparsed:
5802 llvm_unreachable("shouldn't see unresolved exception specifications here");
5803 }
5804
5805 llvm_unreachable("invalid ExceptionSpecificationType");
5806}
5807
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005808/// \brief Find a merged pointer type and convert the two expressions to it.
5809///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005810/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005811/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005812/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005813/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005814///
Douglas Gregor19175ff2010-04-16 23:20:25 +00005815/// \param Loc The location of the operator requiring these two expressions to
5816/// be converted to the composite pointer type.
5817///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005818/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005819QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00005820 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005821 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005822 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005823
5824 // C++1z [expr]p14:
5825 // The composite pointer type of two operands p1 and p2 having types T1
5826 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005827 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005828
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005829 // where at least one is a pointer or pointer to member type or
5830 // std::nullptr_t is:
5831 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5832 T1->isNullPtrType();
5833 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5834 T2->isNullPtrType();
5835 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00005836 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005837
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005838 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5839 // This can't actually happen, following the standard, but we also use this
5840 // to implement the end of [expr.conv], which hits this case.
5841 //
5842 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5843 if (T1IsPointerLike &&
5844 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005845 if (ConvertArgs)
5846 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5847 ? CK_NullToMemberPointer
5848 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005849 return T1;
5850 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005851 if (T2IsPointerLike &&
5852 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005853 if (ConvertArgs)
5854 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5855 ? CK_NullToMemberPointer
5856 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005857 return T2;
5858 }
Mike Stump11289f42009-09-09 15:08:12 +00005859
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005860 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005861 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005862 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005863 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
5864 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005865
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005866 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5867 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5868 // the union of cv1 and cv2;
5869 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5870 // "pointer to function", where the function types are otherwise the same,
5871 // "pointer to function";
5872 // FIXME: This rule is defective: it should also permit removing noexcept
5873 // from a pointer to member function. As a Clang extension, we also
5874 // permit removing 'noreturn', so we generalize this rule to;
5875 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5876 // "pointer to member function" and the pointee types can be unified
5877 // by a function pointer conversion, that conversion is applied
5878 // before checking the following rules.
5879 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5880 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5881 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5882 // respectively;
5883 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5884 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5885 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5886 // T1 or the cv-combined type of T1 and T2, respectively;
5887 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5888 // T2;
5889 //
5890 // If looked at in the right way, these bullets all do the same thing.
5891 // What we do here is, we build the two possible cv-combined types, and try
5892 // the conversions in both directions. If only one works, or if the two
5893 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00005894 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005895 //
5896 // Note that this will fail to find a composite pointer type for "pointer
5897 // to void" and "pointer to function". We can't actually perform the final
5898 // conversion in this case, even though a composite pointer type formally
5899 // exists.
5900 SmallVector<unsigned, 4> QualifierUnion;
5901 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005902 QualType Composite1 = T1;
5903 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005904 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005905 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005906 const PointerType *Ptr1, *Ptr2;
5907 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5908 (Ptr2 = Composite2->getAs<PointerType>())) {
5909 Composite1 = Ptr1->getPointeeType();
5910 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005911
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005912 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005913 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005914 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005915 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005916
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005917 QualifierUnion.push_back(
5918 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00005919 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005920 continue;
5921 }
Mike Stump11289f42009-09-09 15:08:12 +00005922
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005923 const MemberPointerType *MemPtr1, *MemPtr2;
5924 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5925 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5926 Composite1 = MemPtr1->getPointeeType();
5927 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005928
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005929 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005930 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005931 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005932 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005933
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005934 QualifierUnion.push_back(
5935 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5936 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5937 MemPtr2->getClass()));
5938 continue;
5939 }
Mike Stump11289f42009-09-09 15:08:12 +00005940
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005941 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00005942
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005943 // Cannot unwrap any more types.
5944 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005945 }
Mike Stump11289f42009-09-09 15:08:12 +00005946
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005947 // Apply the function pointer conversion to unify the types. We've already
5948 // unwrapped down to the function types, and we want to merge rather than
5949 // just convert, so do this ourselves rather than calling
5950 // IsFunctionConversion.
5951 //
5952 // FIXME: In order to match the standard wording as closely as possible, we
5953 // currently only do this under a single level of pointers. Ideally, we would
5954 // allow this in general, and set NeedConstBefore to the relevant depth on
5955 // the side(s) where we changed anything.
5956 if (QualifierUnion.size() == 1) {
5957 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5958 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5959 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5960 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5961
5962 // The result is noreturn if both operands are.
5963 bool Noreturn =
5964 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5965 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5966 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5967
5968 // The result is nothrow if both operands are.
5969 SmallVector<QualType, 8> ExceptionTypeStorage;
5970 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
5971 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
5972 ExceptionTypeStorage);
5973
5974 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
5975 FPT1->getParamTypes(), EPI1);
5976 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
5977 FPT2->getParamTypes(), EPI2);
5978 }
5979 }
5980 }
5981
Richard Smith5e9746f2016-10-21 22:00:42 +00005982 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005983 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005984 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005985 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00005986 for (unsigned I = 0; I != NeedConstBefore; ++I)
5987 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005988 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005989 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005990
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005991 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005992 auto MOC = MemberOfClass.rbegin();
5993 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
5994 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
5995 auto Classes = *MOC++;
5996 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005997 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005998 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005999 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00006000 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006001 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006002 } else {
6003 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006004 Composite1 =
6005 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6006 Composite2 =
6007 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006008 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006009 }
6010
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006011 struct Conversion {
6012 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006013 Expr *&E1, *&E2;
6014 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00006015 InitializedEntity Entity;
6016 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006017 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00006018 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00006019
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006020 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6021 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00006022 : S(S), E1(E1), E2(E2), Composite(Composite),
6023 Entity(InitializedEntity::InitializeTemporary(Composite)),
6024 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6025 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6026 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006027
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006028 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006029 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6030 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006031 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006032 E1 = E1Result.getAs<Expr>();
6033
6034 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6035 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006036 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006037 E2 = E2Result.getAs<Expr>();
6038
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006039 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006040 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006041 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00006042
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006043 // Try to convert to each composite pointer type.
6044 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006045 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6046 if (ConvertArgs && C1.perform())
6047 return QualType();
6048 return C1.Composite;
6049 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006050 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00006051
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006052 if (C1.Viable == C2.Viable) {
6053 // Either Composite1 and Composite2 are viable and are different, or
6054 // neither is viable.
6055 // FIXME: How both be viable and different?
6056 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006057 }
6058
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006059 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006060 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6061 return QualType();
6062
6063 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006064}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006065
John McCalldadc5752010-08-24 06:29:42 +00006066ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006067 if (!E)
6068 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006069
John McCall31168b02011-06-15 23:02:42 +00006070 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6071
6072 // If the result is a glvalue, we shouldn't bind it.
6073 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006074 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006075
John McCall31168b02011-06-15 23:02:42 +00006076 // In ARC, calls that return a retainable type can return retained,
6077 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006078 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006079 E->getType()->isObjCRetainableType()) {
6080
6081 bool ReturnsRetained;
6082
6083 // For actual calls, we compute this by examining the type of the
6084 // called value.
6085 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6086 Expr *Callee = Call->getCallee()->IgnoreParens();
6087 QualType T = Callee->getType();
6088
6089 if (T == Context.BoundMemberTy) {
6090 // Handle pointer-to-members.
6091 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6092 T = BinOp->getRHS()->getType();
6093 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6094 T = Mem->getMemberDecl()->getType();
6095 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006096
John McCall31168b02011-06-15 23:02:42 +00006097 if (const PointerType *Ptr = T->getAs<PointerType>())
6098 T = Ptr->getPointeeType();
6099 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6100 T = Ptr->getPointeeType();
6101 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6102 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006103
John McCall31168b02011-06-15 23:02:42 +00006104 const FunctionType *FTy = T->getAs<FunctionType>();
6105 assert(FTy && "call to value not of function type?");
6106 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6107
6108 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6109 // type always produce a +1 object.
6110 } else if (isa<StmtExpr>(E)) {
6111 ReturnsRetained = true;
6112
Ted Kremeneke65b0862012-03-06 20:05:56 +00006113 // We hit this case with the lambda conversion-to-block optimization;
6114 // we don't want any extra casts here.
6115 } else if (isa<CastExpr>(E) &&
6116 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006117 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006118
John McCall31168b02011-06-15 23:02:42 +00006119 // For message sends and property references, we try to find an
6120 // actual method. FIXME: we should infer retention by selector in
6121 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006122 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006123 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006124 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6125 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006126 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6127 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006128 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006129 // Don't do reclaims if we're using the zero-element array
6130 // constant.
6131 if (ArrayLit->getNumElements() == 0 &&
6132 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6133 return E;
6134
Ted Kremeneke65b0862012-03-06 20:05:56 +00006135 D = ArrayLit->getArrayWithObjectsMethod();
6136 } else if (ObjCDictionaryLiteral *DictLit
6137 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006138 // Don't do reclaims if we're using the zero-element dictionary
6139 // constant.
6140 if (DictLit->getNumElements() == 0 &&
6141 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6142 return E;
6143
Ted Kremeneke65b0862012-03-06 20:05:56 +00006144 D = DictLit->getDictWithObjectsMethod();
6145 }
John McCall31168b02011-06-15 23:02:42 +00006146
6147 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006148
6149 // Don't do reclaims on performSelector calls; despite their
6150 // return type, the invoked method doesn't necessarily actually
6151 // return an object.
6152 if (!ReturnsRetained &&
6153 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006154 return E;
John McCall31168b02011-06-15 23:02:42 +00006155 }
6156
John McCall16de4d22011-11-14 19:53:16 +00006157 // Don't reclaim an object of Class type.
6158 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006159 return E;
John McCall16de4d22011-11-14 19:53:16 +00006160
Tim Shen4a05bb82016-06-21 20:29:17 +00006161 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006162
John McCall2d637d22011-09-10 06:18:15 +00006163 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6164 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006165 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6166 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006167 }
6168
David Blaikiebbafb8a2012-03-11 07:00:24 +00006169 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006170 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006171
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006172 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6173 // a fast path for the common case that the type is directly a RecordType.
6174 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006175 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006176 while (!RT) {
6177 switch (T->getTypeClass()) {
6178 case Type::Record:
6179 RT = cast<RecordType>(T);
6180 break;
6181 case Type::ConstantArray:
6182 case Type::IncompleteArray:
6183 case Type::VariableArray:
6184 case Type::DependentSizedArray:
6185 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6186 break;
6187 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006188 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006189 }
6190 }
Mike Stump11289f42009-09-09 15:08:12 +00006191
Richard Smithfd555f62012-02-22 02:04:18 +00006192 // That should be enough to guarantee that this type is complete, if we're
6193 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006194 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006195 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006196 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006197
6198 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006199 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006200
John McCall31168b02011-06-15 23:02:42 +00006201 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006202 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006203 CheckDestructorAccess(E->getExprLoc(), Destructor,
6204 PDiag(diag::err_access_dtor_temp)
6205 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006206 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6207 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006208
Richard Smithfd555f62012-02-22 02:04:18 +00006209 // If destructor is trivial, we can avoid the extra copy.
6210 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006211 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006212
John McCall28fc7092011-11-10 05:35:25 +00006213 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006214 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006215 }
Richard Smitheec915d62012-02-18 04:13:32 +00006216
6217 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006218 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6219
6220 if (IsDecltype)
6221 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6222
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006223 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006224}
6225
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006226ExprResult
John McCall5d413782010-12-06 08:20:24 +00006227Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006228 if (SubExpr.isInvalid())
6229 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006230
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006231 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006232}
6233
John McCall28fc7092011-11-10 05:35:25 +00006234Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006235 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006236
Eli Friedman3bda6b12012-02-02 23:15:15 +00006237 CleanupVarDeclMarking();
6238
John McCall28fc7092011-11-10 05:35:25 +00006239 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6240 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006241 assert(Cleanup.exprNeedsCleanups() ||
6242 ExprCleanupObjects.size() == FirstCleanup);
6243 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006244 return SubExpr;
6245
Craig Topper5fc8fc22014-08-27 06:28:36 +00006246 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6247 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006248
Tim Shen4a05bb82016-06-21 20:29:17 +00006249 auto *E = ExprWithCleanups::Create(
6250 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006251 DiscardCleanupsInEvaluationContext();
6252
6253 return E;
6254}
6255
John McCall5d413782010-12-06 08:20:24 +00006256Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006257 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006258
Eli Friedman3bda6b12012-02-02 23:15:15 +00006259 CleanupVarDeclMarking();
6260
Tim Shen4a05bb82016-06-21 20:29:17 +00006261 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006262 return SubStmt;
6263
6264 // FIXME: In order to attach the temporaries, wrap the statement into
6265 // a StmtExpr; currently this is only used for asm statements.
6266 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6267 // a new AsmStmtWithTemporaries.
Benjamin Kramer07420902017-12-24 16:24:20 +00006268 CompoundStmt *CompStmt = CompoundStmt::Create(
6269 Context, SubStmt, SourceLocation(), SourceLocation());
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006270 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6271 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006272 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006273}
6274
Richard Smithfd555f62012-02-22 02:04:18 +00006275/// Process the expression contained within a decltype. For such expressions,
6276/// certain semantic checks on temporaries are delayed until this point, and
6277/// are omitted for the 'topmost' call in the decltype expression. If the
6278/// topmost call bound a temporary, strip that temporary off the expression.
6279ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006280 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006281
6282 // C++11 [expr.call]p11:
6283 // If a function call is a prvalue of object type,
6284 // -- if the function call is either
6285 // -- the operand of a decltype-specifier, or
6286 // -- the right operand of a comma operator that is the operand of a
6287 // decltype-specifier,
6288 // a temporary object is not introduced for the prvalue.
6289
6290 // Recursively rebuild ParenExprs and comma expressions to strip out the
6291 // outermost CXXBindTemporaryExpr, if any.
6292 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6293 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6294 if (SubExpr.isInvalid())
6295 return ExprError();
6296 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006297 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006298 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006299 }
6300 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6301 if (BO->getOpcode() == BO_Comma) {
6302 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6303 if (RHS.isInvalid())
6304 return ExprError();
6305 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006306 return E;
6307 return new (Context) BinaryOperator(
6308 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006309 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006310 }
6311 }
6312
6313 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006314 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6315 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006316 if (TopCall)
6317 E = TopCall;
6318 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006319 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006320
6321 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006322 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00006323
Richard Smithf86b0ae2012-07-28 19:54:11 +00006324 // In MS mode, don't perform any extra checking of call return types within a
6325 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006326 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006327 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006328
Richard Smithfd555f62012-02-22 02:04:18 +00006329 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006330 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6331 I != N; ++I) {
6332 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006333 if (Call == TopCall)
6334 continue;
6335
David Majnemerced8bdf2015-02-25 17:36:15 +00006336 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006337 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006338 Call, Call->getDirectCallee()))
6339 return ExprError();
6340 }
6341
6342 // Now all relevant types are complete, check the destructors are accessible
6343 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006344 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6345 I != N; ++I) {
6346 CXXBindTemporaryExpr *Bind =
6347 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006348 if (Bind == TopBind)
6349 continue;
6350
6351 CXXTemporary *Temp = Bind->getTemporary();
6352
6353 CXXRecordDecl *RD =
6354 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6355 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6356 Temp->setDestructor(Destructor);
6357
Richard Smith7d847b12012-05-11 22:20:10 +00006358 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6359 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006360 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006361 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006362 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6363 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006364
6365 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006366 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006367 }
6368
6369 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006370 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006371}
6372
Richard Smith79c927b2013-11-06 19:31:51 +00006373/// Note a set of 'operator->' functions that were used for a member access.
6374static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006375 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006376 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6377 // FIXME: Make this configurable?
6378 unsigned Limit = 9;
6379 if (OperatorArrows.size() > Limit) {
6380 // Produce Limit-1 normal notes and one 'skipping' note.
6381 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6382 SkipCount = OperatorArrows.size() - (Limit - 1);
6383 }
6384
6385 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6386 if (I == SkipStart) {
6387 S.Diag(OperatorArrows[I]->getLocation(),
6388 diag::note_operator_arrows_suppressed)
6389 << SkipCount;
6390 I += SkipCount;
6391 } else {
6392 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6393 << OperatorArrows[I]->getCallResultType();
6394 ++I;
6395 }
6396 }
6397}
6398
Nico Weber964d3322015-02-16 22:35:45 +00006399ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6400 SourceLocation OpLoc,
6401 tok::TokenKind OpKind,
6402 ParsedType &ObjectType,
6403 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006404 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006405 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006406 if (Result.isInvalid()) return ExprError();
6407 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006408
John McCall526ab472011-10-25 17:37:35 +00006409 Result = CheckPlaceholderExpr(Base);
6410 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006411 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006412
John McCallb268a282010-08-23 23:25:46 +00006413 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006414 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006415 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006416 // If we have a pointer to a dependent type and are using the -> operator,
6417 // the object type is the type that the pointer points to. We might still
6418 // have enough information about that type to do something useful.
6419 if (OpKind == tok::arrow)
6420 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6421 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006422
John McCallba7bf592010-08-24 05:47:05 +00006423 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006424 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006425 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006426 }
Mike Stump11289f42009-09-09 15:08:12 +00006427
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006428 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006429 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006430 // returned, with the original second operand.
6431 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006432 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006433 bool NoArrowOperatorFound = false;
6434 bool FirstIteration = true;
6435 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006436 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006437 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006438 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006439 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006440
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006441 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006442 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6443 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006444 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006445 noteOperatorArrows(*this, OperatorArrows);
6446 Diag(OpLoc, diag::note_operator_arrow_depth)
6447 << getLangOpts().ArrowDepth;
6448 return ExprError();
6449 }
6450
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006451 Result = BuildOverloadedArrowExpr(
6452 S, Base, OpLoc,
6453 // When in a template specialization and on the first loop iteration,
6454 // potentially give the default diagnostic (with the fixit in a
6455 // separate note) instead of having the error reported back to here
6456 // and giving a diagnostic with a fixit attached to the error itself.
6457 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006458 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006459 : &NoArrowOperatorFound);
6460 if (Result.isInvalid()) {
6461 if (NoArrowOperatorFound) {
6462 if (FirstIteration) {
6463 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006464 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006465 << FixItHint::CreateReplacement(OpLoc, ".");
6466 OpKind = tok::period;
6467 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006468 }
6469 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6470 << BaseType << Base->getSourceRange();
6471 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006472 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006473 Diag(CD->getLocStart(),
6474 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006475 }
6476 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006477 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006478 }
John McCallb268a282010-08-23 23:25:46 +00006479 Base = Result.get();
6480 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006481 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006482 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006483 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006484 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006485 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6486 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006487 return ExprError();
6488 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006489 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006490 }
Mike Stump11289f42009-09-09 15:08:12 +00006491
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006492 if (OpKind == tok::arrow &&
6493 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006494 BaseType = BaseType->getPointeeType();
6495 }
Mike Stump11289f42009-09-09 15:08:12 +00006496
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006497 // Objective-C properties allow "." access on Objective-C pointer types,
6498 // so adjust the base type to the object type itself.
6499 if (BaseType->isObjCObjectPointerType())
6500 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006501
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006502 // C++ [basic.lookup.classref]p2:
6503 // [...] If the type of the object expression is of pointer to scalar
6504 // type, the unqualified-id is looked up in the context of the complete
6505 // postfix-expression.
6506 //
6507 // This also indicates that we could be parsing a pseudo-destructor-name.
6508 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006509 // expressions or normal member (ivar or property) access expressions, and
6510 // it's legal for the type to be incomplete if this is a pseudo-destructor
6511 // call. We'll do more incomplete-type checks later in the lookup process,
6512 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006513 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006514 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006515 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006516 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006517 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006518 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006519 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006520 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006521 }
Mike Stump11289f42009-09-09 15:08:12 +00006522
Douglas Gregor3024f072012-04-16 07:05:22 +00006523 // The object type must be complete (or dependent), or
6524 // C++11 [expr.prim.general]p3:
6525 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006526 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006527 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006528 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006529 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006530 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006531 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006532
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006533 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006534 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006535 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006536 // type C (or of pointer to a class type C), the unqualified-id is looked
6537 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006538 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006539 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006540}
6541
Simon Pilgrim75c26882016-09-30 14:25:09 +00006542static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006543 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006544 if (Base->hasPlaceholderType()) {
6545 ExprResult result = S.CheckPlaceholderExpr(Base);
6546 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006547 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006548 }
6549 ObjectType = Base->getType();
6550
David Blaikie1d578782011-12-16 16:03:09 +00006551 // C++ [expr.pseudo]p2:
6552 // The left-hand side of the dot operator shall be of scalar type. The
6553 // left-hand side of the arrow operator shall be of pointer to scalar type.
6554 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006555 // Note that this is rather different from the normal handling for the
6556 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006557 if (OpKind == tok::arrow) {
6558 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6559 ObjectType = Ptr->getPointeeType();
6560 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006561 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006562 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6563 << ObjectType << true
6564 << FixItHint::CreateReplacement(OpLoc, ".");
6565 if (S.isSFINAEContext())
6566 return true;
6567
6568 OpKind = tok::period;
6569 }
6570 }
6571
6572 return false;
6573}
6574
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006575/// \brief Check if it's ok to try and recover dot pseudo destructor calls on
6576/// pointer objects.
6577static bool
6578canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6579 QualType DestructedType) {
6580 // If this is a record type, check if its destructor is callable.
6581 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6582 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6583 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6584 return false;
6585 }
6586
6587 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6588 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6589 DestructedType->isVectorType();
6590}
6591
John McCalldadc5752010-08-24 06:29:42 +00006592ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006593 SourceLocation OpLoc,
6594 tok::TokenKind OpKind,
6595 const CXXScopeSpec &SS,
6596 TypeSourceInfo *ScopeTypeInfo,
6597 SourceLocation CCLoc,
6598 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006599 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006600 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006601
Eli Friedman0ce4de42012-01-25 04:35:06 +00006602 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006603 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6604 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006605
Douglas Gregorc5c57342012-09-10 14:57:06 +00006606 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6607 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006608 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006609 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006610 else {
Nico Weber58829272012-01-23 05:50:57 +00006611 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6612 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006613 return ExprError();
6614 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006615 }
6616
6617 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006618 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006619 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006620 if (DestructedTypeInfo) {
6621 QualType DestructedType = DestructedTypeInfo->getType();
6622 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006623 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006624 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6625 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006626 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6627 // Foo *foo;
6628 // foo.~Foo();
6629 if (OpKind == tok::period && ObjectType->isPointerType() &&
6630 Context.hasSameUnqualifiedType(DestructedType,
6631 ObjectType->getPointeeType())) {
6632 auto Diagnostic =
6633 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6634 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006635
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006636 // Issue a fixit only when the destructor is valid.
6637 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6638 *this, DestructedType))
6639 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6640
6641 // Recover by setting the object type to the destructed type and the
6642 // operator to '->'.
6643 ObjectType = DestructedType;
6644 OpKind = tok::arrow;
6645 } else {
6646 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6647 << ObjectType << DestructedType << Base->getSourceRange()
6648 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6649
6650 // Recover by setting the destructed type to the object type.
6651 DestructedType = ObjectType;
6652 DestructedTypeInfo =
6653 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6654 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6655 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006656 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006657 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006658
John McCall31168b02011-06-15 23:02:42 +00006659 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6660 // Okay: just pretend that the user provided the correctly-qualified
6661 // type.
6662 } else {
6663 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6664 << ObjectType << DestructedType << Base->getSourceRange()
6665 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6666 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006667
John McCall31168b02011-06-15 23:02:42 +00006668 // Recover by setting the destructed type to the object type.
6669 DestructedType = ObjectType;
6670 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6671 DestructedTypeStart);
6672 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6673 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006674 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006675 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006676
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006677 // C++ [expr.pseudo]p2:
6678 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6679 // form
6680 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006681 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006682 //
6683 // shall designate the same scalar type.
6684 if (ScopeTypeInfo) {
6685 QualType ScopeType = ScopeTypeInfo->getType();
6686 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006687 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006688
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006689 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006690 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006691 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006692 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006693
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006694 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006695 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006696 }
6697 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006698
John McCallb268a282010-08-23 23:25:46 +00006699 Expr *Result
6700 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6701 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006702 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006703 ScopeTypeInfo,
6704 CCLoc,
6705 TildeLoc,
6706 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006707
David Majnemerced8bdf2015-02-25 17:36:15 +00006708 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006709}
6710
John McCalldadc5752010-08-24 06:29:42 +00006711ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006712 SourceLocation OpLoc,
6713 tok::TokenKind OpKind,
6714 CXXScopeSpec &SS,
6715 UnqualifiedId &FirstTypeName,
6716 SourceLocation CCLoc,
6717 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006718 UnqualifiedId &SecondTypeName) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00006719 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6720 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006721 "Invalid first type name in pseudo-destructor");
Faisal Vali2ab8c152017-12-30 04:15:27 +00006722 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6723 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006724 "Invalid second type name in pseudo-destructor");
6725
Eli Friedman0ce4de42012-01-25 04:35:06 +00006726 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006727 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6728 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006729
6730 // Compute the object type that we should use for name lookup purposes. Only
6731 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006732 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006733 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006734 if (ObjectType->isRecordType())
6735 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006736 else if (ObjectType->isDependentType())
6737 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006738 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006739
6740 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006741 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006742 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006743 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006744 PseudoDestructorTypeStorage Destructed;
Faisal Vali2ab8c152017-12-30 04:15:27 +00006745 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006746 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006747 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006748 S, &SS, true, false, ObjectTypePtrForLookup,
6749 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006750 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006751 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6752 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006753 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006754 // couldn't find anything useful in scope. Just store the identifier and
6755 // it's location, and we'll perform (qualified) name lookup again at
6756 // template instantiation time.
6757 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6758 SecondTypeName.StartLocation);
6759 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006760 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006761 diag::err_pseudo_dtor_destructor_non_type)
6762 << SecondTypeName.Identifier << ObjectType;
6763 if (isSFINAEContext())
6764 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006765
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006766 // Recover by assuming we had the right type all along.
6767 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006768 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006769 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006770 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006771 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006772 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006773 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006774 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006775 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006776 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006777 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006778 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006779 TemplateId->TemplateNameLoc,
6780 TemplateId->LAngleLoc,
6781 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006782 TemplateId->RAngleLoc,
6783 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006784 if (T.isInvalid() || !T.get()) {
6785 // Recover by assuming we had the right type all along.
6786 DestructedType = ObjectType;
6787 } else
6788 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006789 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006790
6791 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006792 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006793 if (!DestructedType.isNull()) {
6794 if (!DestructedTypeInfo)
6795 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006796 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006797 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6798 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006799
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006800 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006801 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006802 QualType ScopeType;
Faisal Vali2ab8c152017-12-30 04:15:27 +00006803 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006804 FirstTypeName.Identifier) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00006805 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006806 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006807 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006808 S, &SS, true, false, ObjectTypePtrForLookup,
6809 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006810 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006811 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006812 diag::err_pseudo_dtor_destructor_non_type)
6813 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006814
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006815 if (isSFINAEContext())
6816 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006817
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006818 // Just drop this type. It's unnecessary anyway.
6819 ScopeType = QualType();
6820 } else
6821 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006822 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006823 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006824 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006825 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006826 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006827 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006828 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006829 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006830 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006831 TemplateId->TemplateNameLoc,
6832 TemplateId->LAngleLoc,
6833 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006834 TemplateId->RAngleLoc,
6835 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006836 if (T.isInvalid() || !T.get()) {
6837 // Recover by dropping this type.
6838 ScopeType = QualType();
6839 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006840 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006841 }
6842 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006843
Douglas Gregor90ad9222010-02-24 23:02:30 +00006844 if (!ScopeType.isNull() && !ScopeTypeInfo)
6845 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6846 FirstTypeName.StartLocation);
6847
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006848
John McCallb268a282010-08-23 23:25:46 +00006849 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00006850 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006851 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00006852}
6853
David Blaikie1d578782011-12-16 16:03:09 +00006854ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6855 SourceLocation OpLoc,
6856 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006857 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006858 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00006859 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006860 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6861 return ExprError();
6862
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006863 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6864 false);
David Blaikie1d578782011-12-16 16:03:09 +00006865
6866 TypeLocBuilder TLB;
6867 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6868 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6869 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6870 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6871
6872 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006873 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006874 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00006875}
6876
John Wiegley01296292011-04-08 18:41:53 +00006877ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00006878 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006879 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00006880 if (Method->getParent()->isLambda() &&
6881 Method->getConversionType()->isBlockPointerType()) {
6882 // This is a lambda coversion to block pointer; check if the argument
6883 // is a LambdaExpr.
6884 Expr *SubE = E;
6885 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6886 if (CE && CE->getCastKind() == CK_NoOp)
6887 SubE = CE->getSubExpr();
6888 SubE = SubE->IgnoreParens();
6889 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6890 SubE = BE->getSubExpr();
6891 if (isa<LambdaExpr>(SubE)) {
6892 // For the conversion to block pointer on a lambda expression, we
6893 // construct a special BlockLiteral instead; this doesn't really make
6894 // a difference in ARC, but outside of ARC the resulting block literal
6895 // follows the normal lifetime rules for block literals instead of being
6896 // autoreleased.
6897 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00006898 PushExpressionEvaluationContext(
6899 ExpressionEvaluationContext::PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00006900 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6901 E->getExprLoc(),
6902 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006903 PopExpressionEvaluationContext();
6904
Eli Friedman98b01ed2012-03-01 04:01:32 +00006905 if (Exp.isInvalid())
6906 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6907 return Exp;
6908 }
6909 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00006910
Craig Topperc3ec1492014-05-26 06:22:03 +00006911 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006912 FoundDecl, Method);
6913 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00006914 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00006915
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00006916 MemberExpr *ME = new (Context) MemberExpr(
6917 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6918 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006919 if (HadMultipleCandidates)
6920 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00006921 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006922
Alp Toker314cc812014-01-25 16:55:45 +00006923 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00006924 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6925 ResultType = ResultType.getNonLValueExprType(Context);
6926
Douglas Gregor27381f32009-11-23 12:27:39 +00006927 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006928 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00006929 Exp.get()->getLocEnd());
George Burgess IVce6284b2017-01-28 02:19:40 +00006930
6931 if (CheckFunctionCall(Method, CE,
6932 Method->getType()->castAs<FunctionProtoType>()))
6933 return ExprError();
6934
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006935 return CE;
6936}
6937
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006938ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6939 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00006940 // If the operand is an unresolved lookup expression, the expression is ill-
6941 // formed per [over.over]p1, because overloaded function names cannot be used
6942 // without arguments except in explicit contexts.
6943 ExprResult R = CheckPlaceholderExpr(Operand);
6944 if (R.isInvalid())
6945 return R;
6946
6947 // The operand may have been modified when checking the placeholder type.
6948 Operand = R.get();
6949
Richard Smith51ec0cf2017-02-21 01:17:38 +00006950 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006951 // The expression operand for noexcept is in an unevaluated expression
6952 // context, so side effects could result in unintended consequences.
6953 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6954 }
6955
Richard Smithf623c962012-04-17 00:58:00 +00006956 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006957 return new (Context)
6958 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006959}
6960
6961ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6962 Expr *Operand, SourceLocation RParen) {
6963 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00006964}
6965
Eli Friedmanf798f652012-05-24 22:04:19 +00006966static bool IsSpecialDiscardedValue(Expr *E) {
6967 // In C++11, discarded-value expressions of a certain form are special,
6968 // according to [expr]p10:
6969 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6970 // expression is an lvalue of volatile-qualified type and it has
6971 // one of the following forms:
6972 E = E->IgnoreParens();
6973
Eli Friedmanc49c2262012-05-24 22:36:31 +00006974 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006975 if (isa<DeclRefExpr>(E))
6976 return true;
6977
Eli Friedmanc49c2262012-05-24 22:36:31 +00006978 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006979 if (isa<ArraySubscriptExpr>(E))
6980 return true;
6981
Eli Friedmanc49c2262012-05-24 22:36:31 +00006982 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006983 if (isa<MemberExpr>(E))
6984 return true;
6985
Eli Friedmanc49c2262012-05-24 22:36:31 +00006986 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006987 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6988 if (UO->getOpcode() == UO_Deref)
6989 return true;
6990
6991 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00006992 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006993 if (BO->isPtrMemOp())
6994 return true;
6995
Eli Friedmanc49c2262012-05-24 22:36:31 +00006996 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00006997 if (BO->getOpcode() == BO_Comma)
6998 return IsSpecialDiscardedValue(BO->getRHS());
6999 }
7000
Eli Friedmanc49c2262012-05-24 22:36:31 +00007001 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00007002 // operands are one of the above, or
7003 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7004 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7005 IsSpecialDiscardedValue(CO->getFalseExpr());
7006 // The related edge case of "*x ?: *x".
7007 if (BinaryConditionalOperator *BCO =
7008 dyn_cast<BinaryConditionalOperator>(E)) {
7009 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7010 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7011 IsSpecialDiscardedValue(BCO->getFalseExpr());
7012 }
7013
7014 // Objective-C++ extensions to the rule.
7015 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7016 return true;
7017
7018 return false;
7019}
7020
John McCall34376a62010-12-04 03:47:34 +00007021/// Perform the conversions required for an expression used in a
7022/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00007023ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00007024 if (E->hasPlaceholderType()) {
7025 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007026 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007027 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00007028 }
7029
John McCallfee942d2010-12-02 02:07:15 +00007030 // C99 6.3.2.1:
7031 // [Except in specific positions,] an lvalue that does not have
7032 // array type is converted to the value stored in the
7033 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00007034 if (E->isRValue()) {
7035 // In C, function designators (i.e. expressions of function type)
7036 // are r-values, but we still want to do function-to-pointer decay
7037 // on them. This is both technically correct and convenient for
7038 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007039 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00007040 return DefaultFunctionArrayConversion(E);
7041
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007042 return E;
John McCalld68b2d02011-06-27 21:24:11 +00007043 }
John McCallfee942d2010-12-02 02:07:15 +00007044
Eli Friedmanf798f652012-05-24 22:04:19 +00007045 if (getLangOpts().CPlusPlus) {
7046 // The C++11 standard defines the notion of a discarded-value expression;
7047 // normally, we don't need to do anything to handle it, but if it is a
7048 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7049 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007050 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00007051 E->getType().isVolatileQualified() &&
7052 IsSpecialDiscardedValue(E)) {
7053 ExprResult Res = DefaultLvalueConversion(E);
7054 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007055 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007056 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007057 }
Richard Smith122f88d2016-12-06 23:52:28 +00007058
7059 // C++1z:
7060 // If the expression is a prvalue after this optional conversion, the
7061 // temporary materialization conversion is applied.
7062 //
7063 // We skip this step: IR generation is able to synthesize the storage for
7064 // itself in the aggregate case, and adding the extra node to the AST is
7065 // just clutter.
7066 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7067 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007068 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007069 }
John McCall34376a62010-12-04 03:47:34 +00007070
7071 // GCC seems to also exclude expressions of incomplete enum type.
7072 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7073 if (!T->getDecl()->isComplete()) {
7074 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007075 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007076 return E;
John McCall34376a62010-12-04 03:47:34 +00007077 }
7078 }
7079
John Wiegley01296292011-04-08 18:41:53 +00007080 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7081 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007082 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007083 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007084
John McCallca61b652010-12-04 12:29:11 +00007085 if (!E->getType()->isVoidType())
7086 RequireCompleteType(E->getExprLoc(), E->getType(),
7087 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007088 return E;
John McCall34376a62010-12-04 03:47:34 +00007089}
7090
Faisal Valia17d19f2013-11-07 05:17:06 +00007091// If we can unambiguously determine whether Var can never be used
7092// in a constant expression, return true.
7093// - if the variable and its initializer are non-dependent, then
7094// we can unambiguously check if the variable is a constant expression.
7095// - if the initializer is not value dependent - we can determine whether
7096// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007097// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007098// never be a constant expression.
7099// - FXIME: if the initializer is dependent, we can still do some analysis and
7100// identify certain cases unambiguously as non-const by using a Visitor:
7101// - such as those that involve odr-use of a ParmVarDecl, involve a new
7102// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007103static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007104 ASTContext &Context) {
7105 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007106 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007107
7108 // If there is no initializer - this can not be a constant expression.
7109 if (!Var->getAnyInitializer(DefVD)) return true;
7110 assert(DefVD);
7111 if (DefVD->isWeak()) return false;
7112 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007113
Faisal Valia17d19f2013-11-07 05:17:06 +00007114 Expr *Init = cast<Expr>(Eval->Value);
7115
7116 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007117 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7118 // of value-dependent expressions, and use it here to determine whether the
7119 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007120 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007121 }
7122
Simon Pilgrim75c26882016-09-30 14:25:09 +00007123 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007124}
7125
Simon Pilgrim75c26882016-09-30 14:25:09 +00007126/// \brief Check if the current lambda has any potential captures
7127/// that must be captured by any of its enclosing lambdas that are ready to
7128/// capture. If there is a lambda that can capture a nested
7129/// potential-capture, go ahead and do so. Also, check to see if any
7130/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007131/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007132
Faisal Valiab3d6462013-12-07 20:22:44 +00007133static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7134 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7135
Simon Pilgrim75c26882016-09-30 14:25:09 +00007136 assert(!S.isUnevaluatedContext());
7137 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007138#ifndef NDEBUG
7139 DeclContext *DC = S.CurContext;
7140 while (DC && isa<CapturedDecl>(DC))
7141 DC = DC->getParent();
7142 assert(
7143 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007144 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007145#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007146
7147 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7148
7149 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
7150 S.FunctionScopes.data(), S.FunctionScopes.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00007151
Faisal Valiab3d6462013-12-07 20:22:44 +00007152 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007153 // lambda (within a generic outer lambda), must be captured by an
7154 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007155 const unsigned NumPotentialCaptures =
7156 CurrentLSI->getNumPotentialVariableCaptures();
7157 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007158 Expr *VarExpr = nullptr;
7159 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007160 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007161 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007162 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007163 // need to check enclosing lambda's for speculative captures.
7164 // For e.g.:
7165 // Even though 'x' is not odr-used, it should be captured.
7166 // int test() {
7167 // const int x = 10;
7168 // auto L = [=](auto a) {
7169 // (void) +x + a;
7170 // };
7171 // }
7172 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007173 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007174 continue;
7175
7176 // If we have a capture-capable lambda for the variable, go ahead and
7177 // capture the variable in that lambda (and all its enclosing lambdas).
7178 if (const Optional<unsigned> Index =
7179 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7180 FunctionScopesArrayRef, Var, S)) {
7181 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7182 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7183 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007184 }
7185 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007186 VariableCanNeverBeAConstantExpression(Var, S.Context);
7187 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7188 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007189 // can not be used in a constant expression - which means
7190 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007191 // capture violation early, if the variable is un-captureable.
7192 // This is purely for diagnosing errors early. Otherwise, this
7193 // error would get diagnosed when the lambda becomes capture ready.
7194 QualType CaptureType, DeclRefType;
7195 SourceLocation ExprLoc = VarExpr->getExprLoc();
7196 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007197 /*EllipsisLoc*/ SourceLocation(),
7198 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007199 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007200 // We will never be able to capture this variable, and we need
7201 // to be able to in any and all instantiations, so diagnose it.
7202 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007203 /*EllipsisLoc*/ SourceLocation(),
7204 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007205 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007206 }
7207 }
7208 }
7209
Faisal Valiab3d6462013-12-07 20:22:44 +00007210 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007211 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007212 // If we have a capture-capable lambda for 'this', go ahead and capture
7213 // 'this' in that lambda (and all its enclosing lambdas).
7214 if (const Optional<unsigned> Index =
7215 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Craig Topperc3ec1492014-05-26 06:22:03 +00007216 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007217 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7218 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7219 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7220 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007221 }
7222 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007223
7224 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007225 CurrentLSI->clearPotentialCaptures();
7226}
7227
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007228static ExprResult attemptRecovery(Sema &SemaRef,
7229 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007230 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007231 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7232 Consumer.getLookupResult().getLookupKind());
7233 const CXXScopeSpec *SS = Consumer.getSS();
7234 CXXScopeSpec NewSS;
7235
7236 // Use an approprate CXXScopeSpec for building the expr.
7237 if (auto *NNS = TC.getCorrectionSpecifier())
7238 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7239 else if (SS && !TC.WillReplaceSpecifier())
7240 NewSS = *SS;
7241
Richard Smithde6d6c42015-12-29 19:43:10 +00007242 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007243 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007244 R.addDecl(ND);
7245 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007246 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007247 CXXRecordDecl *Record = nullptr;
7248 if (auto *NNS = TC.getCorrectionSpecifier())
7249 Record = NNS->getAsType()->getAsCXXRecordDecl();
7250 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007251 Record =
7252 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7253 if (Record)
7254 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007255
7256 // Detect and handle the case where the decl might be an implicit
7257 // member.
7258 bool MightBeImplicitMember;
7259 if (!Consumer.isAddressOfOperand())
7260 MightBeImplicitMember = true;
7261 else if (!NewSS.isEmpty())
7262 MightBeImplicitMember = false;
7263 else if (R.isOverloadedResult())
7264 MightBeImplicitMember = false;
7265 else if (R.isUnresolvableResult())
7266 MightBeImplicitMember = true;
7267 else
7268 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7269 isa<IndirectFieldDecl>(ND) ||
7270 isa<MSPropertyDecl>(ND);
7271
7272 if (MightBeImplicitMember)
7273 return SemaRef.BuildPossibleImplicitMemberExpr(
7274 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007275 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007276 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7277 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7278 Ivar->getIdentifier());
7279 }
7280 }
7281
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007282 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7283 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007284}
7285
Kaelyn Takata6c759512014-10-27 18:07:37 +00007286namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007287class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7288 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7289
7290public:
7291 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7292 : TypoExprs(TypoExprs) {}
7293 bool VisitTypoExpr(TypoExpr *TE) {
7294 TypoExprs.insert(TE);
7295 return true;
7296 }
7297};
7298
Kaelyn Takata6c759512014-10-27 18:07:37 +00007299class TransformTypos : public TreeTransform<TransformTypos> {
7300 typedef TreeTransform<TransformTypos> BaseTransform;
7301
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007302 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7303 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007304 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007305 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007306 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007307 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007308
7309 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7310 /// If the TypoExprs were successfully corrected, then the diagnostics should
7311 /// suggest the corrections. Otherwise the diagnostics will not suggest
7312 /// anything (having been passed an empty TypoCorrection).
7313 void EmitAllDiagnostics() {
7314 for (auto E : TypoExprs) {
7315 TypoExpr *TE = cast<TypoExpr>(E);
7316 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007317 if (State.DiagHandler) {
7318 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7319 ExprResult Replacement = TransformCache[TE];
7320
7321 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7322 // TypoCorrection, replacing the existing decls. This ensures the right
7323 // NamedDecl is used in diagnostics e.g. in the case where overload
7324 // resolution was used to select one from several possible decls that
7325 // had been stored in the TypoCorrection.
7326 if (auto *ND = getDeclFromExpr(
7327 Replacement.isInvalid() ? nullptr : Replacement.get()))
7328 TC.setCorrectionDecl(ND);
7329
7330 State.DiagHandler(TC);
7331 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007332 SemaRef.clearDelayedTypo(TE);
7333 }
7334 }
7335
7336 /// \brief If corrections for the first TypoExpr have been exhausted for a
7337 /// given combination of the other TypoExprs, retry those corrections against
7338 /// the next combination of substitutions for the other TypoExprs by advancing
7339 /// to the next potential correction of the second TypoExpr. For the second
7340 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7341 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7342 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7343 /// TransformCache). Returns true if there is still any untried combinations
7344 /// of corrections.
7345 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7346 for (auto TE : TypoExprs) {
7347 auto &State = SemaRef.getTypoExprState(TE);
7348 TransformCache.erase(TE);
7349 if (!State.Consumer->finished())
7350 return true;
7351 State.Consumer->resetCorrectionStream();
7352 }
7353 return false;
7354 }
7355
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007356 NamedDecl *getDeclFromExpr(Expr *E) {
7357 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7358 E = OverloadResolution[OE];
7359
7360 if (!E)
7361 return nullptr;
7362 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007363 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007364 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007365 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007366 // FIXME: Add any other expr types that could be be seen by the delayed typo
7367 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007368 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007369 return nullptr;
7370 }
7371
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007372 ExprResult TryTransform(Expr *E) {
7373 Sema::SFINAETrap Trap(SemaRef);
7374 ExprResult Res = TransformExpr(E);
7375 if (Trap.hasErrorOccurred() || Res.isInvalid())
7376 return ExprError();
7377
7378 return ExprFilter(Res.get());
7379 }
7380
Kaelyn Takata6c759512014-10-27 18:07:37 +00007381public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007382 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7383 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007384
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007385 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7386 MultiExprArg Args,
7387 SourceLocation RParenLoc,
7388 Expr *ExecConfig = nullptr) {
7389 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7390 RParenLoc, ExecConfig);
7391 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007392 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007393 Expr *ResultCall = Result.get();
7394 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7395 ResultCall = BE->getSubExpr();
7396 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7397 OverloadResolution[OE] = CE->getCallee();
7398 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007399 }
7400 return Result;
7401 }
7402
Kaelyn Takata6c759512014-10-27 18:07:37 +00007403 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7404
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007405 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7406
Kaelyn Takata6c759512014-10-27 18:07:37 +00007407 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007408 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007409 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007410 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007411
Kaelyn Takata6c759512014-10-27 18:07:37 +00007412 // Exit if either the transform was valid or if there were no TypoExprs
7413 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007414 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007415 !CheckAndAdvanceTypoExprCorrectionStreams())
7416 break;
7417 }
7418
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007419 // Ensure none of the TypoExprs have multiple typo correction candidates
7420 // with the same edit length that pass all the checks and filters.
7421 // TODO: Properly handle various permutations of possible corrections when
7422 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007423 // Also, disable typo correction while attempting the transform when
7424 // handling potentially ambiguous typo corrections as any new TypoExprs will
7425 // have been introduced by the application of one of the correction
7426 // candidates and add little to no value if corrected.
7427 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007428 while (!AmbiguousTypoExprs.empty()) {
7429 auto TE = AmbiguousTypoExprs.back();
7430 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007431 auto &State = SemaRef.getTypoExprState(TE);
7432 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007433 TransformCache.erase(TE);
7434 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007435 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007436 TransformCache.erase(TE);
7437 Res = ExprError();
7438 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007439 }
7440 AmbiguousTypoExprs.remove(TE);
7441 State.Consumer->restoreSavedPosition();
7442 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007443 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007444 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007445
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007446 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007447 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007448 FindTypoExprs(TypoExprs).TraverseStmt(E);
7449
Kaelyn Takata6c759512014-10-27 18:07:37 +00007450 EmitAllDiagnostics();
7451
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007452 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007453 }
7454
7455 ExprResult TransformTypoExpr(TypoExpr *E) {
7456 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7457 // cached transformation result if there is one and the TypoExpr isn't the
7458 // first one that was encountered.
7459 auto &CacheEntry = TransformCache[E];
7460 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7461 return CacheEntry;
7462 }
7463
7464 auto &State = SemaRef.getTypoExprState(E);
7465 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7466
7467 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7468 // typo correction and return it.
7469 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007470 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007471 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007472 // FIXME: If we would typo-correct to an invalid declaration, it's
7473 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007474 ExprResult NE = State.RecoveryHandler ?
7475 State.RecoveryHandler(SemaRef, E, TC) :
7476 attemptRecovery(SemaRef, *State.Consumer, TC);
7477 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007478 // Check whether there may be a second viable correction with the same
7479 // edit distance; if so, remember this TypoExpr may have an ambiguous
7480 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007481 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007482 if ((Next = State.Consumer->peekNextCorrection()) &&
7483 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7484 AmbiguousTypoExprs.insert(E);
7485 } else {
7486 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007487 }
7488 assert(!NE.isUnset() &&
7489 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007490 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007491 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007492 }
7493 return CacheEntry = ExprError();
7494 }
7495};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007496}
Faisal Valia17d19f2013-11-07 05:17:06 +00007497
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007498ExprResult
7499Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7500 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007501 // If the current evaluation context indicates there are uncorrected typos
7502 // and the current expression isn't guaranteed to not have typos, try to
7503 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007504 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007505 (E->isTypeDependent() || E->isValueDependent() ||
7506 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007507 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7508 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7509 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007510 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007511 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007512 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007513 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007514 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007515 ExprEvalContexts.back().NumTypos -= TyposResolved;
7516 return Result;
7517 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007518 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007519 }
7520 return E;
7521}
7522
Richard Smith945f8d32013-01-14 22:39:08 +00007523ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007524 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007525 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007526 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007527 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007528
7529 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007530 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007531
7532 // If we are an init-expression in a lambdas init-capture, we should not
7533 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007534 // containing full-expression is done).
7535 // template<class ... Ts> void test(Ts ... t) {
7536 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7537 // return a;
7538 // }() ...);
7539 // }
7540 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7541 // when we parse the lambda introducer, and teach capturing (but not
7542 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7543 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7544 // lambda where we've entered the introducer but not the body, or represent a
7545 // lambda where we've entered the body, depending on where the
7546 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007547 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007548 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007549 return ExprError();
7550
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007551 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007552 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007553 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007554 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007555 if (FullExpr.isInvalid())
7556 return ExprError();
7557 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007558
Richard Smith945f8d32013-01-14 22:39:08 +00007559 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007560 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007561 if (FullExpr.isInvalid())
7562 return ExprError();
7563
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007564 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007565 if (FullExpr.isInvalid())
7566 return ExprError();
7567 }
John Wiegley01296292011-04-08 18:41:53 +00007568
Kaelyn Takata49d84322014-11-11 23:26:56 +00007569 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7570 if (FullExpr.isInvalid())
7571 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007572
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007573 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007574
Simon Pilgrim75c26882016-09-30 14:25:09 +00007575 // At the end of this full expression (which could be a deeply nested
7576 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007577 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007578 // Consider the following code:
7579 // void f(int, int);
7580 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007581 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007582 // const int x = 10, y = 20;
7583 // auto L = [=](auto a) {
7584 // auto M = [=](auto b) {
7585 // f(x, b); <-- requires x to be captured by L and M
7586 // f(y, a); <-- requires y to be captured by L, but not all Ms
7587 // };
7588 // };
7589 // }
7590
Simon Pilgrim75c26882016-09-30 14:25:09 +00007591 // FIXME: Also consider what happens for something like this that involves
7592 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007593 // void f() {
7594 // const int n = 0;
7595 // auto L = [&](auto a) {
7596 // +n + ({ 0; a; });
7597 // };
7598 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007599 //
7600 // Here, we see +n, and then the full-expression 0; ends, so we don't
7601 // capture n (and instead remove it from our list of potential captures),
7602 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007603 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007604
Alexey Bataev31939e32016-11-11 12:36:20 +00007605 LambdaScopeInfo *const CurrentLSI =
7606 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007607 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007608 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007609 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007610 // By ensuring we are in the context of a lambda's call operator
7611 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007612 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007613 // PR, a proper fix would entail :
7614 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007615 // - Add to Sema an integer holding the smallest (outermost) scope
7616 // index that we are *lexically* within, and save/restore/set to
7617 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007618 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007619 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007620 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007621 DeclContext *DC = CurContext;
7622 while (DC && isa<CapturedDecl>(DC))
7623 DC = DC->getParent();
7624 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007625 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007626 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007627 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7628 *this);
John McCall5d413782010-12-06 08:20:24 +00007629 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007630}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007631
7632StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7633 if (!FullStmt) return StmtError();
7634
John McCall5d413782010-12-06 08:20:24 +00007635 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007636}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007637
Simon Pilgrim75c26882016-09-30 14:25:09 +00007638Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007639Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7640 CXXScopeSpec &SS,
7641 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007642 DeclarationName TargetName = TargetNameInfo.getName();
7643 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007644 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007645
Douglas Gregor43edb322011-10-24 22:31:10 +00007646 // If the name itself is dependent, then the result is dependent.
7647 if (TargetName.isDependentName())
7648 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007649
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007650 // Do the redeclaration lookup in the current scope.
7651 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7652 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007653 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007654 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007655
Douglas Gregor43edb322011-10-24 22:31:10 +00007656 switch (R.getResultKind()) {
7657 case LookupResult::Found:
7658 case LookupResult::FoundOverloaded:
7659 case LookupResult::FoundUnresolvedValue:
7660 case LookupResult::Ambiguous:
7661 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007662
Douglas Gregor43edb322011-10-24 22:31:10 +00007663 case LookupResult::NotFound:
7664 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007665
Douglas Gregor43edb322011-10-24 22:31:10 +00007666 case LookupResult::NotFoundInCurrentInstantiation:
7667 return IER_Dependent;
7668 }
David Blaikie8a40f702012-01-17 06:56:22 +00007669
7670 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007671}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007672
Simon Pilgrim75c26882016-09-30 14:25:09 +00007673Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007674Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7675 bool IsIfExists, CXXScopeSpec &SS,
7676 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007677 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007678
Richard Smith151c4562016-12-20 21:35:28 +00007679 // Check for an unexpanded parameter pack.
7680 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7681 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7682 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007683 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007684
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007685 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7686}