blob: b5a0344a5fd53684867c86dfab31bc7cb56e9158 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
James Dennett84053fb2012-06-22 05:14:59 +00009///
10/// \file
11/// \brief Implements semantic analysis for C++ expressions.
12///
13//===----------------------------------------------------------------------===//
Chris Lattner29375652006-12-04 18:06:35 +000014
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Kaelyn Takata6c759512014-10-27 18:07:37 +000016#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "TypeLocBuilder.h"
Steve Naroffaac94152007-08-25 14:02:58 +000018#include "clang/AST/ASTContext.h"
Faisal Vali47d9ed42014-05-30 04:39:37 +000019#include "clang/AST/ASTLambda.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/CharUnits.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000036#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000038#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000040#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000041using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000042using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000043
Richard Smith7447af42013-03-26 01:15:19 +000044/// \brief Handle the result of the special case name lookup for inheriting
45/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46/// constructor names in member using declarations, even if 'X' is not the
47/// name of the corresponding type.
48ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49 SourceLocation NameLoc,
50 IdentifierInfo &Name) {
51 NestedNameSpecifier *NNS = SS.getScopeRep();
52
53 // Convert the nested-name-specifier into a type.
54 QualType Type;
55 switch (NNS->getKind()) {
56 case NestedNameSpecifier::TypeSpec:
57 case NestedNameSpecifier::TypeSpecWithTemplate:
58 Type = QualType(NNS->getAsType(), 0);
59 break;
60
61 case NestedNameSpecifier::Identifier:
62 // Strip off the last layer of the nested-name-specifier and build a
63 // typename type for it.
64 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66 NNS->getAsIdentifier());
67 break;
68
69 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000070 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000071 case NestedNameSpecifier::Namespace:
72 case NestedNameSpecifier::NamespaceAlias:
73 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
74 }
75
76 // This reference to the type is located entirely at the location of the
77 // final identifier in the qualified-id.
78 return CreateParsedType(Type,
79 Context.getTrivialTypeSourceInfo(Type, NameLoc));
80}
81
John McCallba7bf592010-08-24 05:47:05 +000082ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000083 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000084 SourceLocation NameLoc,
85 Scope *S, CXXScopeSpec &SS,
86 ParsedType ObjectTypePtr,
87 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000088 // Determine where to perform name lookup.
89
90 // FIXME: This area of the standard is very messy, and the current
91 // wording is rather unclear about which scopes we search for the
92 // destructor name; see core issues 399 and 555. Issue 399 in
93 // particular shows where the current description of destructor name
94 // lookup is completely out of line with existing practice, e.g.,
95 // this appears to be ill-formed:
96 //
97 // namespace N {
98 // template <typename T> struct S {
99 // ~S();
100 // };
101 // }
102 //
103 // void f(N::S<int>* s) {
104 // s->N::S<int>::~S();
105 // }
106 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000107 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000108 // For this reason, we're currently only doing the C++03 version of this
109 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000110 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000111 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000112 bool isDependent = false;
113 bool LookInScope = false;
114
Richard Smith64e033f2015-01-15 00:48:52 +0000115 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000116 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000117
Douglas Gregorfe17d252010-02-16 19:09:40 +0000118 // If we have an object type, it's because we are in a
119 // pseudo-destructor-expression or a member access expression, and
120 // we know what type we're looking for.
121 if (ObjectTypePtr)
122 SearchType = GetTypeFromParser(ObjectTypePtr);
123
124 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000125 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000126
Douglas Gregor46841e12010-02-23 00:15:22 +0000127 bool AlreadySearched = false;
128 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000129 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000130 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000131 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000132 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000133 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000134 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000135 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000136 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000137 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000138 // Here, we determine whether the code below is permitted to look at the
139 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000140 DeclContext *DC = computeDeclContext(SS, EnteringContext);
141 if (DC && DC->isFileContext()) {
142 AlreadySearched = true;
143 LookupCtx = DC;
144 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000145 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000146 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000147 LookInScope = true;
148 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000149
Sebastian Redla771d222010-07-07 23:17:38 +0000150 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000151 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000152 if (AlreadySearched) {
153 // Nothing left to do.
154 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
155 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000156 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000157 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
158 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000159 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000160 LookupCtx = computeDeclContext(SearchType);
161 isDependent = SearchType->isDependentType();
162 } else {
163 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000164 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000165 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000166 } else if (ObjectTypePtr) {
167 // C++ [basic.lookup.classref]p3:
168 // If the unqualified-id is ~type-name, the type-name is looked up
169 // in the context of the entire postfix-expression. If the type T
170 // of the object expression is of a class type C, the type-name is
171 // also looked up in the scope of class C. At least one of the
172 // lookups shall find a name that refers to (possibly
173 // cv-qualified) T.
174 LookupCtx = computeDeclContext(SearchType);
175 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000176 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000177 "Caller should have completed object type");
178
179 LookInScope = true;
180 } else {
181 // Perform lookup into the current scope (only).
182 LookInScope = true;
183 }
184
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000186 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
187 for (unsigned Step = 0; Step != 2; ++Step) {
188 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000189 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000190 // we're allowed to look there).
191 Found.clear();
192 if (Step == 0 && LookupCtx)
193 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000194 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000195 LookupName(Found, S);
196 else
197 continue;
198
199 // FIXME: Should we be suppressing ambiguities here?
200 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000201 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000202
203 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
204 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000205 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000206
207 if (SearchType.isNull() || SearchType->isDependentType() ||
208 Context.hasSameUnqualifiedType(T, SearchType)) {
209 // We found our type!
210
Richard Smithc278c002014-01-22 00:30:17 +0000211 return CreateParsedType(T,
212 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000213 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000214
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000215 if (!SearchType.isNull())
216 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000217 }
218
219 // If the name that we found is a class template name, and it is
220 // the same name as the template name in the last part of the
221 // nested-name-specifier (if present) or the object type, then
222 // this is the destructor for that class.
223 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000225 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
226 QualType MemberOfType;
227 if (SS.isSet()) {
228 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
229 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000230 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
231 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000232 }
233 }
234 if (MemberOfType.isNull())
235 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000236
Douglas Gregorfe17d252010-02-16 19:09:40 +0000237 if (MemberOfType.isNull())
238 continue;
239
240 // We're referring into a class template specialization. If the
241 // class template we found is the same as the template being
242 // specialized, we found what we are looking for.
243 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
244 if (ClassTemplateSpecializationDecl *Spec
245 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
246 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
247 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000248 return CreateParsedType(
249 MemberOfType,
250 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000251 }
252
253 continue;
254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000255
Douglas Gregorfe17d252010-02-16 19:09:40 +0000256 // We're referring to an unresolved class template
257 // specialization. Determine whether we class template we found
258 // is the same as the template being specialized or, if we don't
259 // know which template is being specialized, that it at least
260 // has the same name.
261 if (const TemplateSpecializationType *SpecType
262 = MemberOfType->getAs<TemplateSpecializationType>()) {
263 TemplateName SpecName = SpecType->getTemplateName();
264
265 // The class template we found is the same template being
266 // specialized.
267 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
268 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000269 return CreateParsedType(
270 MemberOfType,
271 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000272
273 continue;
274 }
275
276 // The class template we found has the same name as the
277 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000279 = SpecName.getAsDependentTemplateName()) {
280 if (DepTemplate->isIdentifier() &&
281 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000282 return CreateParsedType(
283 MemberOfType,
284 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000285
286 continue;
287 }
288 }
289 }
290 }
291
292 if (isDependent) {
293 // We didn't find our type, but that's okay: it's dependent
294 // anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000295
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000296 // FIXME: What if we have no nested-name-specifier?
297 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
298 SS.getWithLocInContext(Context),
299 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000300 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000301 }
302
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000303 if (NonMatchingTypeDecl) {
304 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
305 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
306 << T << SearchType;
307 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
308 << T;
309 } else if (ObjectTypePtr)
310 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000311 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000312 else {
313 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
314 diag::err_destructor_class_name);
315 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000316 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000317 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
318 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
319 Class->getNameAsString());
320 }
321 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000322
David Blaikieefdccaa2016-01-15 23:43:34 +0000323 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000324}
325
David Blaikieecd8a942011-12-08 16:13:53 +0000326ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie08608f62011-12-12 04:13:55 +0000327 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikieefdccaa2016-01-15 23:43:34 +0000328 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000329 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
David Blaikieecd8a942011-12-08 16:13:53 +0000330 && "only get destructor types from declspecs");
331 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
332 QualType SearchType = GetTypeFromParser(ObjectType);
333 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
334 return ParsedType::make(T);
335 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000336
David Blaikieecd8a942011-12-08 16:13:53 +0000337 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
338 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000339 return nullptr;
David Blaikieecd8a942011-12-08 16:13:53 +0000340}
341
Richard Smithd091dc12013-12-05 00:58:33 +0000342bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
343 const UnqualifiedId &Name) {
344 assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
345
346 if (!SS.isValid())
347 return false;
348
349 switch (SS.getScopeRep()->getKind()) {
350 case NestedNameSpecifier::Identifier:
351 case NestedNameSpecifier::TypeSpec:
352 case NestedNameSpecifier::TypeSpecWithTemplate:
353 // Per C++11 [over.literal]p2, literal operators can only be declared at
354 // namespace scope. Therefore, this unqualified-id cannot name anything.
355 // Reject it early, because we have no AST representation for this in the
356 // case where the scope is dependent.
357 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
358 << SS.getScopeRep();
359 return true;
360
361 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000362 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000363 case NestedNameSpecifier::Namespace:
364 case NestedNameSpecifier::NamespaceAlias:
365 return false;
366 }
367
368 llvm_unreachable("unknown nested name specifier kind");
369}
370
Douglas Gregor9da64192010-04-26 22:37:10 +0000371/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000372ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000373 SourceLocation TypeidLoc,
374 TypeSourceInfo *Operand,
375 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000376 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000377 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000378 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000379 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000380 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000381 Qualifiers Quals;
382 QualType T
383 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
384 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000385 if (T->getAs<RecordType>() &&
386 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
387 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388
David Majnemer6f3150a2014-11-21 21:09:12 +0000389 if (T->isVariablyModifiedType())
390 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
391
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000392 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
393 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000394}
395
396/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000397ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000398 SourceLocation TypeidLoc,
399 Expr *E,
400 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000401 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000402 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000403 if (E->getType()->isPlaceholderType()) {
404 ExprResult result = CheckPlaceholderExpr(E);
405 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000406 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000407 }
408
Douglas Gregor9da64192010-04-26 22:37:10 +0000409 QualType T = E->getType();
410 if (const RecordType *RecordT = T->getAs<RecordType>()) {
411 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
412 // C++ [expr.typeid]p3:
413 // [...] If the type of the expression is a class type, the class
414 // shall be completely-defined.
415 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
416 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417
Douglas Gregor9da64192010-04-26 22:37:10 +0000418 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000419 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000420 // polymorphic class type [...] [the] expression is an unevaluated
421 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000422 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000423 // The subexpression is potentially evaluated; switch the context
424 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000425 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000426 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000427 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000428
429 // We require a vtable to query the type at run time.
430 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000431 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000432 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000433 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000434
Douglas Gregor9da64192010-04-26 22:37:10 +0000435 // C++ [expr.typeid]p4:
436 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000437 // cv-qualified type, the result of the typeid expression refers to a
438 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000439 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000440 Qualifiers Quals;
441 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
442 if (!Context.hasSameType(T, UnqualT)) {
443 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000444 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000445 }
446 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000447
David Majnemer6f3150a2014-11-21 21:09:12 +0000448 if (E->getType()->isVariablyModifiedType())
449 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
450 << E->getType());
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000451 else if (ActiveTemplateInstantiations.empty() &&
452 E->HasSideEffects(Context, WasEvaluated)) {
453 // The expression operand for typeid is in an unevaluated expression
454 // context, so side effects could result in unintended consequences.
455 Diag(E->getExprLoc(), WasEvaluated
456 ? diag::warn_side_effects_typeid
457 : diag::warn_side_effects_unevaluated_context);
458 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000459
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000460 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
461 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000462}
463
464/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000465ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000466Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
467 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000468 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000469 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000470 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000471
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000472 if (!CXXTypeInfoDecl) {
473 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
474 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
475 LookupQualifiedName(R, getStdNamespace());
476 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000477 // Microsoft's typeinfo doesn't have type_info in std but in the global
478 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000479 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000480 LookupQualifiedName(R, Context.getTranslationUnitDecl());
481 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
482 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000483 if (!CXXTypeInfoDecl)
484 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000486
Nico Weber1b7f39d2012-05-20 01:27:21 +0000487 if (!getLangOpts().RTTI) {
488 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
489 }
490
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000491 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000492
Douglas Gregor9da64192010-04-26 22:37:10 +0000493 if (isType) {
494 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000495 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000496 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
497 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000498 if (T.isNull())
499 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
Douglas Gregor9da64192010-04-26 22:37:10 +0000501 if (!TInfo)
502 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000503
Douglas Gregor9da64192010-04-26 22:37:10 +0000504 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000505 }
Mike Stump11289f42009-09-09 15:08:12 +0000506
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000508 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000509}
510
David Majnemer1dbc7a72016-03-27 04:46:07 +0000511/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
512/// a single GUID.
513static void
514getUuidAttrOfType(Sema &SemaRef, QualType QT,
515 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
516 // Optionally remove one level of pointer, reference or array indirection.
517 const Type *Ty = QT.getTypePtr();
518 if (QT->isPointerType() || QT->isReferenceType())
519 Ty = QT->getPointeeType().getTypePtr();
520 else if (QT->isArrayType())
521 Ty = Ty->getBaseElementTypeUnsafe();
522
Reid Klecknere516eab2016-12-13 18:58:09 +0000523 const auto *TD = Ty->getAsTagDecl();
524 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000525 return;
526
Reid Klecknere516eab2016-12-13 18:58:09 +0000527 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000528 UuidAttrs.insert(Uuid);
529 return;
530 }
531
532 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000533 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000534 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
535 for (const TemplateArgument &TA : TAL.asArray()) {
536 const UuidAttr *UuidForTA = nullptr;
537 if (TA.getKind() == TemplateArgument::Type)
538 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
539 else if (TA.getKind() == TemplateArgument::Declaration)
540 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
541
542 if (UuidForTA)
543 UuidAttrs.insert(UuidForTA);
544 }
545 }
546}
547
Francois Pichet9f4f2072010-09-08 12:20:18 +0000548/// \brief Build a Microsoft __uuidof expression with a type operand.
549ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
550 SourceLocation TypeidLoc,
551 TypeSourceInfo *Operand,
552 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000553 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000554 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000555 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
556 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
557 if (UuidAttrs.empty())
558 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
559 if (UuidAttrs.size() > 1)
560 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000561 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000562 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
David Majnemer2041b462016-03-28 03:19:50 +0000564 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000565 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000566}
567
568/// \brief Build a Microsoft __uuidof expression with an expression operand.
569ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
570 SourceLocation TypeidLoc,
571 Expr *E,
572 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000573 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000574 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000575 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
576 UuidStr = "00000000-0000-0000-0000-000000000000";
577 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000578 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
579 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
580 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000581 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000582 if (UuidAttrs.size() > 1)
583 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000584 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000585 }
Francois Pichetb7577652010-12-27 01:32:00 +0000586 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000587
David Majnemer2041b462016-03-28 03:19:50 +0000588 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000589 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000590}
591
592/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
593ExprResult
594Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
595 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000596 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000597 if (!MSVCGuidDecl) {
598 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
599 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
600 LookupQualifiedName(R, Context.getTranslationUnitDecl());
601 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
602 if (!MSVCGuidDecl)
603 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604 }
605
Francois Pichet9f4f2072010-09-08 12:20:18 +0000606 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
Francois Pichet9f4f2072010-09-08 12:20:18 +0000608 if (isType) {
609 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000610 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000611 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
612 &TInfo);
613 if (T.isNull())
614 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000615
Francois Pichet9f4f2072010-09-08 12:20:18 +0000616 if (!TInfo)
617 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
618
619 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
620 }
621
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000623 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
624}
625
Steve Naroff66356bd2007-09-16 14:56:35 +0000626/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000627ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000628Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000629 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000630 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000631 return new (Context)
632 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000633}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000634
Sebastian Redl576fd422009-05-10 18:38:11 +0000635/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000636ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000637Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000638 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000639}
640
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000641/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000642ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000643Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
644 bool IsThrownVarInScope = false;
645 if (Ex) {
646 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000647 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000648 // copy/move construction of a class object [...]
649 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000650 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000651 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000652 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000653 // innermost enclosing try-block (if there is one), the copy/move
654 // operation from the operand to the exception object (15.1) can be
655 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000656 // exception object
657 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
658 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
659 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
660 for( ; S; S = S->getParent()) {
661 if (S->isDeclScope(Var)) {
662 IsThrownVarInScope = true;
663 break;
664 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000665
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000666 if (S->getFlags() &
667 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
668 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
669 Scope::TryScope))
670 break;
671 }
672 }
673 }
674 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000675
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000676 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
677}
678
Simon Pilgrim75c26882016-09-30 14:25:09 +0000679ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000680 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000681 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000682 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000683 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000684 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000685
Justin Lebar2a8db342016-09-28 22:45:54 +0000686 // Exceptions aren't allowed in CUDA device code.
687 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000688 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
689 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000690
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000691 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
692 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
693
John Wiegley01296292011-04-08 18:41:53 +0000694 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000695 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
696 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000697 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000698
699 // Initialize the exception result. This implicitly weeds out
700 // abstract types or types with inaccessible copy constructors.
701
702 // C++0x [class.copymove]p31:
703 // When certain criteria are met, an implementation is allowed to omit the
704 // copy/move construction of a class object [...]
705 //
706 // - in a throw-expression, when the operand is the name of a
707 // non-volatile automatic object (other than a function or
708 // catch-clause
709 // parameter) whose scope does not extend beyond the end of the
710 // innermost enclosing try-block (if there is one), the copy/move
711 // operation from the operand to the exception object (15.1) can be
712 // omitted by constructing the automatic object directly into the
713 // exception object
714 const VarDecl *NRVOVariable = nullptr;
715 if (IsThrownVarInScope)
716 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
717
718 InitializedEntity Entity = InitializedEntity::InitializeException(
719 OpLoc, ExceptionObjectTy,
720 /*NRVO=*/NRVOVariable != nullptr);
721 ExprResult Res = PerformMoveOrCopyInitialization(
722 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
723 if (Res.isInvalid())
724 return ExprError();
725 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000726 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000727
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000728 return new (Context)
729 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000730}
731
David Majnemere7a818f2015-03-06 18:53:55 +0000732static void
733collectPublicBases(CXXRecordDecl *RD,
734 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
735 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
736 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
737 bool ParentIsPublic) {
738 for (const CXXBaseSpecifier &BS : RD->bases()) {
739 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
740 bool NewSubobject;
741 // Virtual bases constitute the same subobject. Non-virtual bases are
742 // always distinct subobjects.
743 if (BS.isVirtual())
744 NewSubobject = VBases.insert(BaseDecl).second;
745 else
746 NewSubobject = true;
747
748 if (NewSubobject)
749 ++SubobjectsSeen[BaseDecl];
750
751 // Only add subobjects which have public access throughout the entire chain.
752 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
753 if (PublicPath)
754 PublicSubobjectsSeen.insert(BaseDecl);
755
756 // Recurse on to each base subobject.
757 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
758 PublicPath);
759 }
760}
761
762static void getUnambiguousPublicSubobjects(
763 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
764 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
765 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
766 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
767 SubobjectsSeen[RD] = 1;
768 PublicSubobjectsSeen.insert(RD);
769 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
770 /*ParentIsPublic=*/true);
771
772 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
773 // Skip ambiguous objects.
774 if (SubobjectsSeen[PublicSubobject] > 1)
775 continue;
776
777 Objects.push_back(PublicSubobject);
778 }
779}
780
Sebastian Redl4de47b42009-04-27 20:27:31 +0000781/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000782bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
783 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000784 // If the type of the exception would be an incomplete type or a pointer
785 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000786 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000787 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000788 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000789 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000790 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000791 }
792 if (!isPointer || !Ty->isVoidType()) {
793 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000794 isPointer ? diag::err_throw_incomplete_ptr
795 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000796 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000797 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000798
David Majnemerd09a51c2015-03-03 01:50:05 +0000799 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000800 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000801 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000802 }
803
Eli Friedman91a3d272010-06-03 20:39:03 +0000804 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000805 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
806 if (!RD)
807 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000808
Douglas Gregor88d292c2010-05-13 16:44:06 +0000809 // If we are throwing a polymorphic class type or pointer thereof,
810 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000811 MarkVTableUsed(ThrowLoc, RD);
812
Eli Friedman36ebbec2010-10-12 20:32:36 +0000813 // If a pointer is thrown, the referenced object will not be destroyed.
814 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000815 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000816
Richard Smitheec915d62012-02-18 04:13:32 +0000817 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000818 if (!RD->hasIrrelevantDestructor()) {
819 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
820 MarkFunctionReferenced(E->getExprLoc(), Destructor);
821 CheckDestructorAccess(E->getExprLoc(), Destructor,
822 PDiag(diag::err_access_dtor_exception) << Ty);
823 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000824 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000825 }
826 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000827
David Majnemerdfa6d202015-03-11 18:36:39 +0000828 // The MSVC ABI creates a list of all types which can catch the exception
829 // object. This list also references the appropriate copy constructor to call
830 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000831 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000832 // We are only interested in the public, unambiguous bases contained within
833 // the exception object. Bases which are ambiguous or otherwise
834 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000835 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
836 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000837
David Majnemere7a818f2015-03-06 18:53:55 +0000838 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000839 // Attempt to lookup the copy constructor. Various pieces of machinery
840 // will spring into action, like template instantiation, which means this
841 // cannot be a simple walk of the class's decls. Instead, we must perform
842 // lookup and overload resolution.
843 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
844 if (!CD)
845 continue;
846
847 // Mark the constructor referenced as it is used by this throw expression.
848 MarkFunctionReferenced(E->getExprLoc(), CD);
849
850 // Skip this copy constructor if it is trivial, we don't need to record it
851 // in the catchable type data.
852 if (CD->isTrivial())
853 continue;
854
855 // The copy constructor is non-trivial, create a mapping from this class
856 // type to this constructor.
857 // N.B. The selection of copy constructor is not sensitive to this
858 // particular throw-site. Lookup will be performed at the catch-site to
859 // ensure that the copy constructor is, in fact, accessible (via
860 // friendship or any other means).
861 Context.addCopyConstructorForExceptionObject(Subobject, CD);
862
863 // We don't keep the instantiated default argument expressions around so
864 // we must rebuild them here.
865 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000866 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
867 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000868 }
869 }
870 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000871
David Majnemerba3e5ec2015-03-13 18:26:17 +0000872 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000873}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000874
Faisal Vali67b04462016-06-11 16:41:54 +0000875static QualType adjustCVQualifiersForCXXThisWithinLambda(
876 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
877 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
878
879 QualType ClassType = ThisTy->getPointeeType();
880 LambdaScopeInfo *CurLSI = nullptr;
881 DeclContext *CurDC = CurSemaContext;
882
883 // Iterate through the stack of lambdas starting from the innermost lambda to
884 // the outermost lambda, checking if '*this' is ever captured by copy - since
885 // that could change the cv-qualifiers of the '*this' object.
886 // The object referred to by '*this' starts out with the cv-qualifiers of its
887 // member function. We then start with the innermost lambda and iterate
888 // outward checking to see if any lambda performs a by-copy capture of '*this'
889 // - and if so, any nested lambda must respect the 'constness' of that
890 // capturing lamdbda's call operator.
891 //
892
893 // The issue is that we cannot rely entirely on the FunctionScopeInfo stack
894 // since ScopeInfos are pushed on during parsing and treetransforming. But
895 // since a generic lambda's call operator can be instantiated anywhere (even
896 // end of the TU) we need to be able to examine its enclosing lambdas and so
897 // we use the DeclContext to get a hold of the closure-class and query it for
898 // capture information. The reason we don't just resort to always using the
899 // DeclContext chain is that it is only mature for lambda expressions
900 // enclosing generic lambda's call operators that are being instantiated.
901
902 for (int I = FunctionScopes.size();
903 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]);
904 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
905 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000906
907 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +0000908 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000909
Faisal Vali67b04462016-06-11 16:41:54 +0000910 auto C = CurLSI->getCXXThisCapture();
911
912 if (C.isCopyCapture()) {
913 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
914 if (CurLSI->CallOperator->isConst())
915 ClassType.addConst();
916 return ASTCtx.getPointerType(ClassType);
917 }
918 }
919 // We've run out of ScopeInfos but check if CurDC is a lambda (which can
920 // happen during instantiation of generic lambdas)
921 if (isLambdaCallOperator(CurDC)) {
922 assert(CurLSI);
923 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator));
924 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +0000925
Faisal Vali67b04462016-06-11 16:41:54 +0000926 auto IsThisCaptured =
927 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
928 IsConst = false;
929 IsByCopy = false;
930 for (auto &&C : Closure->captures()) {
931 if (C.capturesThis()) {
932 if (C.getCaptureKind() == LCK_StarThis)
933 IsByCopy = true;
934 if (Closure->getLambdaCallOperator()->isConst())
935 IsConst = true;
936 return true;
937 }
938 }
939 return false;
940 };
941
942 bool IsByCopyCapture = false;
943 bool IsConstCapture = false;
944 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
945 while (Closure &&
946 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
947 if (IsByCopyCapture) {
948 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
949 if (IsConstCapture)
950 ClassType.addConst();
951 return ASTCtx.getPointerType(ClassType);
952 }
953 Closure = isLambdaCallOperator(Closure->getParent())
954 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
955 : nullptr;
956 }
957 }
958 return ASTCtx.getPointerType(ClassType);
959}
960
Eli Friedman73a04092012-01-07 04:59:52 +0000961QualType Sema::getCurrentThisType() {
962 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +0000963 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000964
Richard Smith938f40b2011-06-11 17:19:42 +0000965 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
966 if (method && method->isInstance())
967 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000968 }
Faisal Validc6b5962016-03-21 09:25:37 +0000969
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000970 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
971 !ActiveTemplateInstantiations.empty()) {
Faisal Validc6b5962016-03-21 09:25:37 +0000972
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000973 assert(isa<CXXRecordDecl>(DC) &&
974 "Trying to get 'this' type from static method?");
975
976 // This is a lambda call operator that is being instantiated as a default
977 // initializer. DC must point to the enclosing class type, so we can recover
978 // the 'this' type from it.
979
980 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
981 // There are no cv-qualifiers for 'this' within default initializers,
982 // per [expr.prim.general]p4.
983 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +0000984 }
Faisal Vali67b04462016-06-11 16:41:54 +0000985
986 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
987 // might need to be adjusted if the lambda or any of its enclosing lambda's
988 // captures '*this' by copy.
989 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
990 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
991 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000992 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +0000993}
994
Simon Pilgrim75c26882016-09-30 14:25:09 +0000995Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +0000996 Decl *ContextDecl,
997 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +0000998 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +0000999 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1000{
1001 if (!Enabled || !ContextDecl)
1002 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001003
1004 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001005 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1006 Record = Template->getTemplatedDecl();
1007 else
1008 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001009
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001010 // We care only for CVR qualifiers here, so cut everything else.
1011 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001012 S.CXXThisTypeOverride
1013 = S.Context.getPointerType(
1014 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001015
Douglas Gregor3024f072012-04-16 07:05:22 +00001016 this->Enabled = true;
1017}
1018
1019
1020Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1021 if (Enabled) {
1022 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1023 }
1024}
1025
Faisal Validc6b5962016-03-21 09:25:37 +00001026static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1027 QualType ThisTy, SourceLocation Loc,
1028 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001029
Faisal Vali67b04462016-06-11 16:41:54 +00001030 QualType AdjustedThisTy = ThisTy;
1031 // The type of the corresponding data member (not a 'this' pointer if 'by
1032 // copy').
1033 QualType CaptureThisFieldTy = ThisTy;
1034 if (ByCopy) {
1035 // If we are capturing the object referred to by '*this' by copy, ignore any
1036 // cv qualifiers inherited from the type of the member function for the type
1037 // of the closure-type's corresponding data member and any use of 'this'.
1038 CaptureThisFieldTy = ThisTy->getPointeeType();
1039 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1040 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1041 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001042
Faisal Vali67b04462016-06-11 16:41:54 +00001043 FieldDecl *Field = FieldDecl::Create(
1044 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1045 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1046 ICIS_NoInit);
1047
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001048 Field->setImplicit(true);
1049 Field->setAccess(AS_private);
1050 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001051 Expr *This =
1052 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001053 if (ByCopy) {
1054 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1055 UO_Deref,
1056 This).get();
1057 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001058 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001059 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1060 InitializationSequence Init(S, Entity, InitKind, StarThis);
1061 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1062 if (ER.isInvalid()) return nullptr;
1063 return ER.get();
1064 }
1065 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001066}
1067
Simon Pilgrim75c26882016-09-30 14:25:09 +00001068bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001069 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1070 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001071 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001072 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001073 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001074
Faisal Validc6b5962016-03-21 09:25:37 +00001075 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001076
Faisal Valia17d19f2013-11-07 05:17:06 +00001077 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
Faisal Validc6b5962016-03-21 09:25:37 +00001078 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001079
Simon Pilgrim75c26882016-09-30 14:25:09 +00001080 // Check that we can capture the *enclosing object* (referred to by '*this')
1081 // by the capturing-entity/closure (lambda/block/etc) at
1082 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1083
1084 // Note: The *enclosing object* can only be captured by-value by a
1085 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001086 // [*this] { ... }.
1087 // Every other capture of the *enclosing object* results in its by-reference
1088 // capture.
1089
1090 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1091 // stack), we can capture the *enclosing object* only if:
1092 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1093 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001094 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001095 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001096 // -- or, there is some enclosing closure 'E' that has already captured the
1097 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001098 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001099 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001100 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001101
1102
Faisal Validc6b5962016-03-21 09:25:37 +00001103 unsigned NumCapturingClosures = 0;
Faisal Valia17d19f2013-11-07 05:17:06 +00001104 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001105 if (CapturingScopeInfo *CSI =
1106 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1107 if (CSI->CXXThisCaptureIndex != 0) {
1108 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001109 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001110 break;
1111 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001112 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1113 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1114 // This context can't implicitly capture 'this'; fail out.
1115 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001116 Diag(Loc, diag::err_this_capture)
1117 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001118 return true;
1119 }
Eli Friedman20139d32012-01-11 02:36:31 +00001120 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001121 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001122 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001123 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001124 (Explicit && idx == MaxFunctionScopesIndex)) {
1125 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1126 // iteration through can be an explicit capture, all enclosing closures,
1127 // if any, must perform implicit captures.
1128
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001129 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001130 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001131 continue;
1132 }
Eli Friedman20139d32012-01-11 02:36:31 +00001133 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001134 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001135 Diag(Loc, diag::err_this_capture)
1136 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001137 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001138 }
Eli Friedman73a04092012-01-07 04:59:52 +00001139 break;
1140 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001141 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001142
1143 // If we got here, then the closure at MaxFunctionScopesIndex on the
1144 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1145 // (including implicit by-reference captures in any enclosing closures).
1146
1147 // In the loop below, respect the ByCopy flag only for the closure requesting
1148 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001149 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001150 // implicitly capturing the *enclosing object* by reference (see loop
1151 // above)).
1152 assert((!ByCopy ||
1153 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1154 "Only a lambda can capture the enclosing object (referred to by "
1155 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001156 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1157 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001158 QualType ThisTy = getCurrentThisType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00001159 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
Faisal Validc6b5962016-03-21 09:25:37 +00001160 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001161 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001162 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001163
Faisal Validc6b5962016-03-21 09:25:37 +00001164 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1165 // For lambda expressions, build a field and an initializing expression,
1166 // and capture the *enclosing object* by copy only if this is the first
1167 // iteration.
1168 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1169 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001170
Faisal Validc6b5962016-03-21 09:25:37 +00001171 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001172 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001173 ThisExpr =
1174 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1175 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001176
Faisal Validc6b5962016-03-21 09:25:37 +00001177 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001178 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001179 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001180 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001181}
1182
Richard Smith938f40b2011-06-11 17:19:42 +00001183ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001184 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1185 /// is a non-lvalue expression whose value is the address of the object for
1186 /// which the function is called.
1187
Douglas Gregor09deffa2011-10-18 16:47:30 +00001188 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001189 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001190
Eli Friedman73a04092012-01-07 04:59:52 +00001191 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001192 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001193}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001194
Douglas Gregor3024f072012-04-16 07:05:22 +00001195bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1196 // If we're outside the body of a member function, then we'll have a specified
1197 // type for 'this'.
1198 if (CXXThisTypeOverride.isNull())
1199 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001200
Douglas Gregor3024f072012-04-16 07:05:22 +00001201 // Determine whether we're looking into a class that's currently being
1202 // defined.
1203 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1204 return Class && Class->isBeingDefined();
1205}
1206
John McCalldadc5752010-08-24 06:29:42 +00001207ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001208Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001209 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001210 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001211 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001212 if (!TypeRep)
1213 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001214
John McCall97513962010-01-15 18:39:57 +00001215 TypeSourceInfo *TInfo;
1216 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1217 if (!TInfo)
1218 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001219
Serge Pavlov38526372016-11-12 15:38:55 +00001220 // Handle errors like: int({0})
1221 if (exprs.size() == 1 && !canInitializeWithParenthesizedList(Ty) &&
1222 LParenLoc.isValid() && RParenLoc.isValid())
1223 if (auto IList = dyn_cast<InitListExpr>(exprs[0])) {
1224 Diag(TInfo->getTypeLoc().getLocStart(), diag::err_list_init_in_parens)
1225 << Ty << IList->getSourceRange()
1226 << FixItHint::CreateRemoval(LParenLoc)
1227 << FixItHint::CreateRemoval(RParenLoc);
1228 LParenLoc = RParenLoc = SourceLocation();
1229 }
1230
Richard Smithb8c414c2016-06-30 20:24:30 +00001231 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1232 // Avoid creating a non-type-dependent expression that contains typos.
1233 // Non-type-dependent expressions are liable to be discarded without
1234 // checking for embedded typos.
1235 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1236 !Result.get()->isTypeDependent())
1237 Result = CorrectDelayedTyposInExpr(Result.get());
1238 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001239}
1240
1241/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1242/// Can be interpreted either as function-style casting ("int(x)")
1243/// or class type construction ("ClassType(x,y,z)")
1244/// or creation of a value-initialized type ("int()").
1245ExprResult
1246Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1247 SourceLocation LParenLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001248 MultiExprArg Exprs,
Douglas Gregor2b88c112010-09-08 00:15:04 +00001249 SourceLocation RParenLoc) {
1250 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001251 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001252
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001253 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001254 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1255 RParenLoc);
Douglas Gregor0950e412009-03-13 21:01:28 +00001256 }
1257
Richard Smith600b5262017-01-26 20:40:47 +00001258 // C++1z [expr.type.conv]p1:
1259 // If the type is a placeholder for a deduced class type, [...perform class
1260 // template argument deduction...]
1261 DeducedType *Deduced = Ty->getContainedDeducedType();
1262 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1263 Diag(TyBeginLoc, diag::err_deduced_class_template_not_supported);
1264 return ExprError();
1265 }
1266
Sebastian Redld74dd492012-02-12 18:41:05 +00001267 bool ListInitialization = LParenLoc.isInvalid();
Richard Smith600b5262017-01-26 20:40:47 +00001268 assert((!ListInitialization ||
1269 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1270 "List initialization must have initializer list as expression.");
Sebastian Redld74dd492012-02-12 18:41:05 +00001271 SourceRange FullRange = SourceRange(TyBeginLoc,
1272 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1273
Douglas Gregordd04d332009-01-16 18:33:17 +00001274 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001275 // If the expression list is a single expression, the type conversion
1276 // expression is equivalent (in definedness, and if defined in meaning) to the
1277 // corresponding cast expression.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001278 if (Exprs.size() == 1 && !ListInitialization) {
John McCallb50451a2011-10-05 07:41:44 +00001279 Expr *Arg = Exprs[0];
John McCallb50451a2011-10-05 07:41:44 +00001280 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001281 }
1282
David Majnemer7eddcff2015-09-14 07:05:00 +00001283 // C++14 [expr.type.conv]p2: The expression T(), where T is a
1284 // simple-type-specifier or typename-specifier for a non-array complete
1285 // object type or the (possibly cv-qualified) void type, creates a prvalue
1286 // of the specified type, whose value is that produced by value-initializing
1287 // an object of type T.
Eli Friedman576cbd02012-02-29 00:00:28 +00001288 QualType ElemTy = Ty;
1289 if (Ty->isArrayType()) {
1290 if (!ListInitialization)
1291 return ExprError(Diag(TyBeginLoc,
1292 diag::err_value_init_for_array_type) << FullRange);
1293 ElemTy = Context.getBaseElementType(Ty);
1294 }
1295
David Majnemer7eddcff2015-09-14 07:05:00 +00001296 if (!ListInitialization && Ty->isFunctionType())
1297 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_function_type)
1298 << FullRange);
1299
Eli Friedman576cbd02012-02-29 00:00:28 +00001300 if (!Ty->isVoidType() &&
1301 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001302 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001303 return ExprError();
1304
Douglas Gregor8ec51732010-09-08 21:40:08 +00001305 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001306 InitializationKind Kind =
1307 Exprs.size() ? ListInitialization
1308 ? InitializationKind::CreateDirectList(TyBeginLoc)
1309 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
1310 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1311 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1312 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001313
Richard Smith90061902013-09-23 02:20:00 +00001314 if (Result.isInvalid() || !ListInitialization)
1315 return Result;
1316
1317 Expr *Inner = Result.get();
1318 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1319 Inner = BTE->getSubExpr();
Richard Smith1ae689c2015-01-28 22:06:01 +00001320 if (!isa<CXXTemporaryObjectExpr>(Inner)) {
1321 // If we created a CXXTemporaryObjectExpr, that node also represents the
1322 // functional cast. Otherwise, create an explicit cast to represent
1323 // the syntactic form of a functional-style cast that was used here.
1324 //
1325 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1326 // would give a more consistent AST representation than using a
1327 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1328 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001329 QualType ResultType = Result.get()->getType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001330 Result = CXXFunctionalCastExpr::Create(
Richard Smith90061902013-09-23 02:20:00 +00001331 Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001332 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
Sebastian Redl2b80af42012-02-13 19:55:43 +00001333 }
1334
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001335 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001336}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001337
Richard Smithb2f0f052016-10-10 18:54:32 +00001338/// \brief Determine whether the given function is a non-placement
1339/// deallocation function.
1340static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1341 if (FD->isInvalidDecl())
1342 return false;
1343
1344 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1345 return Method->isUsualDeallocationFunction();
1346
1347 if (FD->getOverloadedOperator() != OO_Delete &&
1348 FD->getOverloadedOperator() != OO_Array_Delete)
1349 return false;
1350
1351 unsigned UsualParams = 1;
1352
1353 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1354 S.Context.hasSameUnqualifiedType(
1355 FD->getParamDecl(UsualParams)->getType(),
1356 S.Context.getSizeType()))
1357 ++UsualParams;
1358
1359 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1360 S.Context.hasSameUnqualifiedType(
1361 FD->getParamDecl(UsualParams)->getType(),
1362 S.Context.getTypeDeclType(S.getStdAlignValT())))
1363 ++UsualParams;
1364
1365 return UsualParams == FD->getNumParams();
1366}
1367
1368namespace {
1369 struct UsualDeallocFnInfo {
1370 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001371 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001372 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smithf75dcbe2016-10-11 00:21:10 +00001373 HasSizeT(false), HasAlignValT(false), CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001374 // A function template declaration is never a usual deallocation function.
1375 if (!FD)
1376 return;
1377 if (FD->getNumParams() == 3)
1378 HasAlignValT = HasSizeT = true;
1379 else if (FD->getNumParams() == 2) {
1380 HasSizeT = FD->getParamDecl(1)->getType()->isIntegerType();
1381 HasAlignValT = !HasSizeT;
1382 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001383
1384 // In CUDA, determine how much we'd like / dislike to call this.
1385 if (S.getLangOpts().CUDA)
1386 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1387 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001388 }
1389
1390 operator bool() const { return FD; }
1391
Richard Smithf75dcbe2016-10-11 00:21:10 +00001392 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1393 bool WantAlign) const {
1394 // C++17 [expr.delete]p10:
1395 // If the type has new-extended alignment, a function with a parameter
1396 // of type std::align_val_t is preferred; otherwise a function without
1397 // such a parameter is preferred
1398 if (HasAlignValT != Other.HasAlignValT)
1399 return HasAlignValT == WantAlign;
1400
1401 if (HasSizeT != Other.HasSizeT)
1402 return HasSizeT == WantSize;
1403
1404 // Use CUDA call preference as a tiebreaker.
1405 return CUDAPref > Other.CUDAPref;
1406 }
1407
Richard Smithb2f0f052016-10-10 18:54:32 +00001408 DeclAccessPair Found;
1409 FunctionDecl *FD;
1410 bool HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001411 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001412 };
1413}
1414
1415/// Determine whether a type has new-extended alignment. This may be called when
1416/// the type is incomplete (for a delete-expression with an incomplete pointee
1417/// type), in which case it will conservatively return false if the alignment is
1418/// not known.
1419static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1420 return S.getLangOpts().AlignedAllocation &&
1421 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1422 S.getASTContext().getTargetInfo().getNewAlign();
1423}
1424
1425/// Select the correct "usual" deallocation function to use from a selection of
1426/// deallocation functions (either global or class-scope).
1427static UsualDeallocFnInfo resolveDeallocationOverload(
1428 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1429 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1430 UsualDeallocFnInfo Best;
1431
Richard Smithb2f0f052016-10-10 18:54:32 +00001432 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001433 UsualDeallocFnInfo Info(S, I.getPair());
1434 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1435 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001436 continue;
1437
1438 if (!Best) {
1439 Best = Info;
1440 if (BestFns)
1441 BestFns->push_back(Info);
1442 continue;
1443 }
1444
Richard Smithf75dcbe2016-10-11 00:21:10 +00001445 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001446 continue;
1447
1448 // If more than one preferred function is found, all non-preferred
1449 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001450 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001451 BestFns->clear();
1452
1453 Best = Info;
1454 if (BestFns)
1455 BestFns->push_back(Info);
1456 }
1457
1458 return Best;
1459}
1460
1461/// Determine whether a given type is a class for which 'delete[]' would call
1462/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1463/// we need to store the array size (even if the type is
1464/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001465static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1466 QualType allocType) {
1467 const RecordType *record =
1468 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1469 if (!record) return false;
1470
1471 // Try to find an operator delete[] in class scope.
1472
1473 DeclarationName deleteName =
1474 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1475 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1476 S.LookupQualifiedName(ops, record->getDecl());
1477
1478 // We're just doing this for information.
1479 ops.suppressDiagnostics();
1480
1481 // Very likely: there's no operator delete[].
1482 if (ops.empty()) return false;
1483
1484 // If it's ambiguous, it should be illegal to call operator delete[]
1485 // on this thing, so it doesn't matter if we allocate extra space or not.
1486 if (ops.isAmbiguous()) return false;
1487
Richard Smithb2f0f052016-10-10 18:54:32 +00001488 // C++17 [expr.delete]p10:
1489 // If the deallocation functions have class scope, the one without a
1490 // parameter of type std::size_t is selected.
1491 auto Best = resolveDeallocationOverload(
1492 S, ops, /*WantSize*/false,
1493 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1494 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001495}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001496
Sebastian Redld74dd492012-02-12 18:41:05 +00001497/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001498///
Sebastian Redld74dd492012-02-12 18:41:05 +00001499/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001500/// @code new (memory) int[size][4] @endcode
1501/// or
1502/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001503///
1504/// \param StartLoc The first location of the expression.
1505/// \param UseGlobal True if 'new' was prefixed with '::'.
1506/// \param PlacementLParen Opening paren of the placement arguments.
1507/// \param PlacementArgs Placement new arguments.
1508/// \param PlacementRParen Closing paren of the placement arguments.
1509/// \param TypeIdParens If the type is in parens, the source range.
1510/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001511/// \param Initializer The initializing expression or initializer-list, or null
1512/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001513ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001514Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001515 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001516 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001517 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001518 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001519 // If the specified type is an array, unwrap it and save the expression.
1520 if (D.getNumTypeObjects() > 0 &&
1521 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001522 DeclaratorChunk &Chunk = D.getTypeObject(0);
1523 if (D.getDeclSpec().containsPlaceholderType())
Richard Smith30482bc2011-02-20 03:19:35 +00001524 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1525 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001526 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001527 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1528 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001529 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001530 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1531 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001532
Sebastian Redl351bb782008-12-02 14:43:59 +00001533 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001534 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001535 }
1536
Douglas Gregor73341c42009-09-11 00:18:58 +00001537 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001538 if (ArraySize) {
1539 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001540 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1541 break;
1542
1543 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1544 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001545 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001546 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001547 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1548 // shall be a converted constant expression (5.19) of type std::size_t
1549 // and shall evaluate to a strictly positive value.
1550 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1551 assert(IntWidth && "Builtin type of size 0?");
1552 llvm::APSInt Value(IntWidth);
1553 Array.NumElts
1554 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1555 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001556 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001557 } else {
1558 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001559 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001560 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001561 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001562 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001563 if (!Array.NumElts)
1564 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001565 }
1566 }
1567 }
1568 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001569
Craig Topperc3ec1492014-05-26 06:22:03 +00001570 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001571 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001572 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001573 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001574
Sebastian Redl6047f072012-02-16 12:22:20 +00001575 SourceRange DirectInitRange;
Serge Pavlov38526372016-11-12 15:38:55 +00001576 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001577 DirectInitRange = List->getSourceRange();
Serge Pavlov38526372016-11-12 15:38:55 +00001578 // Handle errors like: new int a({0})
1579 if (List->getNumExprs() == 1 &&
1580 !canInitializeWithParenthesizedList(AllocType))
1581 if (auto IList = dyn_cast<InitListExpr>(List->getExpr(0))) {
1582 Diag(TInfo->getTypeLoc().getLocStart(), diag::err_list_init_in_parens)
1583 << AllocType << List->getSourceRange()
1584 << FixItHint::CreateRemoval(List->getLocStart())
1585 << FixItHint::CreateRemoval(List->getLocEnd());
1586 DirectInitRange = SourceRange();
1587 Initializer = IList;
1588 }
1589 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001590
David Blaikie7b97aef2012-11-07 00:12:38 +00001591 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001592 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001593 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001594 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001595 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001596 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001597 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001598 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001599 DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001600 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001601}
1602
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001603static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1604 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001605 if (!Init)
1606 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001607 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1608 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001609 if (isa<ImplicitValueInitExpr>(Init))
1610 return true;
1611 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1612 return !CCE->isListInitialization() &&
1613 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001614 else if (Style == CXXNewExpr::ListInit) {
1615 assert(isa<InitListExpr>(Init) &&
1616 "Shouldn't create list CXXConstructExprs for arrays.");
1617 return true;
1618 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001619 return false;
1620}
1621
John McCalldadc5752010-08-24 06:29:42 +00001622ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001623Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001624 SourceLocation PlacementLParen,
1625 MultiExprArg PlacementArgs,
1626 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001627 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001628 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001629 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001630 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001631 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001632 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001633 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001634 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001635
Sebastian Redl6047f072012-02-16 12:22:20 +00001636 CXXNewExpr::InitializationStyle initStyle;
1637 if (DirectInitRange.isValid()) {
1638 assert(Initializer && "Have parens but no initializer.");
1639 initStyle = CXXNewExpr::CallInit;
1640 } else if (Initializer && isa<InitListExpr>(Initializer))
1641 initStyle = CXXNewExpr::ListInit;
1642 else {
1643 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1644 isa<CXXConstructExpr>(Initializer)) &&
1645 "Initializer expression that cannot have been implicitly created.");
1646 initStyle = CXXNewExpr::NoInit;
1647 }
1648
1649 Expr **Inits = &Initializer;
1650 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001651 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1652 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1653 Inits = List->getExprs();
1654 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001655 }
1656
Richard Smith66204ec2014-03-12 17:42:45 +00001657 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith3beb7c62017-01-12 02:27:38 +00001658 if (AllocType->isUndeducedType()) {
Richard Smith600b5262017-01-26 20:40:47 +00001659 if (isa<DeducedTemplateSpecializationType>(
1660 AllocType->getContainedDeducedType()))
1661 return ExprError(Diag(TypeRange.getBegin(),
1662 diag::err_deduced_class_template_not_supported));
1663
Sebastian Redl6047f072012-02-16 12:22:20 +00001664 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001665 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1666 << AllocType << TypeRange);
Richard Smith66204ec2014-03-12 17:42:45 +00001667 if (initStyle == CXXNewExpr::ListInit ||
1668 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001669 return ExprError(Diag(Inits[0]->getLocStart(),
Richard Smith66204ec2014-03-12 17:42:45 +00001670 diag::err_auto_new_list_init)
Sebastian Redl6047f072012-02-16 12:22:20 +00001671 << AllocType << TypeRange);
1672 if (NumInits > 1) {
1673 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001674 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001675 diag::err_auto_new_ctor_multiple_expressions)
1676 << AllocType << TypeRange);
1677 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001678 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001679 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001680 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001681 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001682 << AllocType << Deduce->getType()
1683 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001684 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001685 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001686 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001687 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001688
Douglas Gregorcda95f42010-05-16 16:01:03 +00001689 // Per C++0x [expr.new]p5, the type being constructed may be a
1690 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001691 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001692 if (const ConstantArrayType *Array
1693 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001694 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1695 Context.getSizeType(),
1696 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001697 AllocType = Array->getElementType();
1698 }
1699 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001700
Douglas Gregor3999e152010-10-06 16:00:31 +00001701 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1702 return ExprError();
1703
Craig Topperc3ec1492014-05-26 06:22:03 +00001704 if (initStyle == CXXNewExpr::ListInit &&
1705 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001706 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1707 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001708 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001709 }
1710
Simon Pilgrim75c26882016-09-30 14:25:09 +00001711 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001712 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001713 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1714 AllocType->isObjCLifetimeType()) {
1715 AllocType = Context.getLifetimeQualifiedType(AllocType,
1716 AllocType->getObjCARCImplicitLifetime());
1717 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001718
John McCall31168b02011-06-15 23:02:42 +00001719 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001720
John McCall5e77d762013-04-16 07:28:30 +00001721 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1722 ExprResult result = CheckPlaceholderExpr(ArraySize);
1723 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001724 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001725 }
Richard Smith8dd34252012-02-04 07:07:42 +00001726 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1727 // integral or enumeration type with a non-negative value."
1728 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1729 // enumeration type, or a class type for which a single non-explicit
1730 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001731 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001732 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001733 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001734 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001735 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001736 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001737 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1738
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001739 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1740 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001741
Simon Pilgrim75c26882016-09-30 14:25:09 +00001742 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001743 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001744 // Diagnose the compatibility of this conversion.
1745 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1746 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001747 } else {
1748 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1749 protected:
1750 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001751
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001752 public:
1753 SizeConvertDiagnoser(Expr *ArraySize)
1754 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1755 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001756
1757 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1758 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001759 return S.Diag(Loc, diag::err_array_size_not_integral)
1760 << S.getLangOpts().CPlusPlus11 << T;
1761 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001762
1763 SemaDiagnosticBuilder diagnoseIncomplete(
1764 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001765 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1766 << T << ArraySize->getSourceRange();
1767 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001768
1769 SemaDiagnosticBuilder diagnoseExplicitConv(
1770 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001771 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1772 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001773
1774 SemaDiagnosticBuilder noteExplicitConv(
1775 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001776 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1777 << ConvTy->isEnumeralType() << ConvTy;
1778 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001779
1780 SemaDiagnosticBuilder diagnoseAmbiguous(
1781 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001782 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1783 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001784
1785 SemaDiagnosticBuilder noteAmbiguous(
1786 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001787 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1788 << ConvTy->isEnumeralType() << ConvTy;
1789 }
Richard Smithccc11812013-05-21 19:05:48 +00001790
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001791 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1792 QualType T,
1793 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001794 return S.Diag(Loc,
1795 S.getLangOpts().CPlusPlus11
1796 ? diag::warn_cxx98_compat_array_size_conversion
1797 : diag::ext_array_size_conversion)
1798 << T << ConvTy->isEnumeralType() << ConvTy;
1799 }
1800 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001801
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001802 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1803 SizeDiagnoser);
1804 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001805 if (ConvertedSize.isInvalid())
1806 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001807
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001808 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001809 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001810
Douglas Gregor0bf31402010-10-08 23:50:27 +00001811 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001812 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001813
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001814 // C++98 [expr.new]p7:
1815 // The expression in a direct-new-declarator shall have integral type
1816 // with a non-negative value.
1817 //
Richard Smith0511d232016-10-05 22:41:02 +00001818 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1819 // per CWG1464. Otherwise, if it's not a constant, we must have an
1820 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001821 if (!ArraySize->isValueDependent()) {
1822 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001823 // We've already performed any required implicit conversion to integer or
1824 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001825 // FIXME: Per CWG1464, we are required to check the value prior to
1826 // converting to size_t. This will never find a negative array size in
1827 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001828 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001829 if (Value.isSigned() && Value.isNegative()) {
1830 return ExprError(Diag(ArraySize->getLocStart(),
1831 diag::err_typecheck_negative_array_size)
1832 << ArraySize->getSourceRange());
1833 }
1834
1835 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001836 unsigned ActiveSizeBits =
1837 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00001838 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1839 return ExprError(Diag(ArraySize->getLocStart(),
1840 diag::err_array_too_large)
1841 << Value.toString(10)
1842 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001843 }
Richard Smith0511d232016-10-05 22:41:02 +00001844
1845 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00001846 } else if (TypeIdParens.isValid()) {
1847 // Can't have dynamic array size when the type-id is in parentheses.
1848 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1849 << ArraySize->getSourceRange()
1850 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1851 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001852
Douglas Gregorf2753b32010-07-13 15:54:32 +00001853 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001854 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001855 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001856
John McCall036f2f62011-05-15 07:14:44 +00001857 // Note that we do *not* convert the argument in any way. It can
1858 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001859 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001860
Craig Topperc3ec1492014-05-26 06:22:03 +00001861 FunctionDecl *OperatorNew = nullptr;
1862 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00001863 unsigned Alignment =
1864 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1865 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1866 bool PassAlignment = getLangOpts().AlignedAllocation &&
1867 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001868
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001869 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001870 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001871 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001872 SourceRange(PlacementLParen, PlacementRParen),
Richard Smithb2f0f052016-10-10 18:54:32 +00001873 UseGlobal, AllocType, ArraySize, PassAlignment,
1874 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001875 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001876
1877 // If this is an array allocation, compute whether the usual array
1878 // deallocation function for the type has a size_t parameter.
1879 bool UsualArrayDeleteWantsSize = false;
1880 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00001881 UsualArrayDeleteWantsSize =
1882 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00001883
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001884 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001885 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001886 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00001887 OperatorNew->getType()->getAs<FunctionProtoType>();
1888 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1889 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001890
Richard Smithd6f9e732014-05-13 19:56:21 +00001891 // We've already converted the placement args, just fill in any default
1892 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00001893 // argument. Skip the second parameter too if we're passing in the
1894 // alignment; we've already filled it in.
1895 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
1896 PassAlignment ? 2 : 1, PlacementArgs,
1897 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001898 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001899
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001900 if (!AllPlaceArgs.empty())
1901 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00001902
Richard Smithd6f9e732014-05-13 19:56:21 +00001903 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001904 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00001905
1906 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001907
Richard Smithb2f0f052016-10-10 18:54:32 +00001908 // Warn if the type is over-aligned and is being allocated by (unaligned)
1909 // global operator new.
1910 if (PlacementArgs.empty() && !PassAlignment &&
1911 (OperatorNew->isImplicit() ||
1912 (OperatorNew->getLocStart().isValid() &&
1913 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
1914 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00001915 Diag(StartLoc, diag::warn_overaligned_type)
1916 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00001917 << unsigned(Alignment / Context.getCharWidth())
1918 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00001919 }
1920 }
1921
Sebastian Redl6047f072012-02-16 12:22:20 +00001922 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001923 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1924 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00001925 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
1926 SourceRange InitRange(Inits[0]->getLocStart(),
1927 Inits[NumInits - 1]->getLocEnd());
1928 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1929 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001930 }
1931
Richard Smithdd2ca572012-11-26 08:32:48 +00001932 // If we can perform the initialization, and we've not already done so,
1933 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00001934 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001935 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00001936 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00001937 // The type we initialize is the complete type, including the array bound.
1938 QualType InitType;
1939 if (KnownArraySize)
1940 InitType = Context.getConstantArrayType(
1941 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
1942 *KnownArraySize),
1943 ArrayType::Normal, 0);
1944 else if (ArraySize)
1945 InitType =
1946 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
1947 else
1948 InitType = AllocType;
1949
Sebastian Redld74dd492012-02-12 18:41:05 +00001950 // C++11 [expr.new]p15:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001951 // A new-expression that creates an object of type T initializes that
1952 // object as follows:
1953 InitializationKind Kind
1954 // - If the new-initializer is omitted, the object is default-
1955 // initialized (8.5); if no initialization is performed,
1956 // the object has indeterminate value
Sebastian Redl6047f072012-02-16 12:22:20 +00001957 = initStyle == CXXNewExpr::NoInit
1958 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001960 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +00001961 : initStyle == CXXNewExpr::ListInit
1962 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1963 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1964 DirectInitRange.getBegin(),
1965 DirectInitRange.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001966
Douglas Gregor85dabae2009-12-16 01:38:02 +00001967 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001968 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00001969 InitializationSequence InitSeq(*this, Entity, Kind,
1970 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001971 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00001972 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00001973 if (FullInit.isInvalid())
1974 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001975
Sebastian Redl6047f072012-02-16 12:22:20 +00001976 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1977 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00001978 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00001979 if (CXXBindTemporaryExpr *Binder =
1980 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001981 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001983 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001984 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001985
Douglas Gregor6642ca22010-02-26 05:06:18 +00001986 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00001987 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00001988 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1989 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001990 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00001991 }
1992 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00001993 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1994 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001995 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00001996 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00001997
John McCall928a2572011-07-13 20:12:57 +00001998 // C++0x [expr.new]p17:
1999 // If the new expression creates an array of objects of class type,
2000 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00002001 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2002 if (ArraySize && !BaseAllocType->isDependentType()) {
2003 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2004 if (CXXDestructorDecl *dtor = LookupDestructor(
2005 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2006 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002007 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002008 PDiag(diag::err_access_dtor)
2009 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002010 if (DiagnoseUseOfDecl(dtor, StartLoc))
2011 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002012 }
John McCall928a2572011-07-13 20:12:57 +00002013 }
2014 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002015
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002016 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00002017 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002018 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2019 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2020 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002021}
2022
Sebastian Redl6047f072012-02-16 12:22:20 +00002023/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002024/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002025bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002026 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002027 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2028 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002029 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002030 return Diag(Loc, diag::err_bad_new_type)
2031 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002032 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002033 return Diag(Loc, diag::err_bad_new_type)
2034 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002035 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002036 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002037 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002038 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002039 diag::err_allocation_of_abstract_type))
2040 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002041 else if (AllocType->isVariablyModifiedType())
2042 return Diag(Loc, diag::err_variably_modified_new_type)
2043 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00002044 else if (unsigned AddressSpace = AllocType.getAddressSpace())
2045 return Diag(Loc, diag::err_address_space_qualified_new)
2046 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002047 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002048 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2049 QualType BaseAllocType = Context.getBaseElementType(AT);
2050 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2051 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002052 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002053 << BaseAllocType;
2054 }
2055 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002056
Sebastian Redlbd150f42008-11-21 19:14:01 +00002057 return false;
2058}
2059
Richard Smithb2f0f052016-10-10 18:54:32 +00002060static bool
2061resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2062 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2063 FunctionDecl *&Operator,
2064 OverloadCandidateSet *AlignedCandidates = nullptr,
2065 Expr *AlignArg = nullptr) {
2066 OverloadCandidateSet Candidates(R.getNameLoc(),
2067 OverloadCandidateSet::CSK_Normal);
2068 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2069 Alloc != AllocEnd; ++Alloc) {
2070 // Even member operator new/delete are implicitly treated as
2071 // static, so don't use AddMemberCandidate.
2072 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2073
2074 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2075 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2076 /*ExplicitTemplateArgs=*/nullptr, Args,
2077 Candidates,
2078 /*SuppressUserConversions=*/false);
2079 continue;
2080 }
2081
2082 FunctionDecl *Fn = cast<FunctionDecl>(D);
2083 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2084 /*SuppressUserConversions=*/false);
2085 }
2086
2087 // Do the resolution.
2088 OverloadCandidateSet::iterator Best;
2089 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2090 case OR_Success: {
2091 // Got one!
2092 FunctionDecl *FnDecl = Best->Function;
2093 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2094 Best->FoundDecl) == Sema::AR_inaccessible)
2095 return true;
2096
2097 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002098 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002099 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002100
Richard Smithb2f0f052016-10-10 18:54:32 +00002101 case OR_No_Viable_Function:
2102 // C++17 [expr.new]p13:
2103 // If no matching function is found and the allocated object type has
2104 // new-extended alignment, the alignment argument is removed from the
2105 // argument list, and overload resolution is performed again.
2106 if (PassAlignment) {
2107 PassAlignment = false;
2108 AlignArg = Args[1];
2109 Args.erase(Args.begin() + 1);
2110 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2111 Operator, &Candidates, AlignArg);
2112 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002113
Richard Smithb2f0f052016-10-10 18:54:32 +00002114 // MSVC will fall back on trying to find a matching global operator new
2115 // if operator new[] cannot be found. Also, MSVC will leak by not
2116 // generating a call to operator delete or operator delete[], but we
2117 // will not replicate that bug.
2118 // FIXME: Find out how this interacts with the std::align_val_t fallback
2119 // once MSVC implements it.
2120 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2121 S.Context.getLangOpts().MSVCCompat) {
2122 R.clear();
2123 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2124 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2125 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2126 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2127 Operator, nullptr);
2128 }
Richard Smith1cdec012013-09-29 04:40:38 +00002129
Richard Smithb2f0f052016-10-10 18:54:32 +00002130 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2131 << R.getLookupName() << Range;
2132
2133 // If we have aligned candidates, only note the align_val_t candidates
2134 // from AlignedCandidates and the non-align_val_t candidates from
2135 // Candidates.
2136 if (AlignedCandidates) {
2137 auto IsAligned = [](OverloadCandidate &C) {
2138 return C.Function->getNumParams() > 1 &&
2139 C.Function->getParamDecl(1)->getType()->isAlignValT();
2140 };
2141 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2142
2143 // This was an overaligned allocation, so list the aligned candidates
2144 // first.
2145 Args.insert(Args.begin() + 1, AlignArg);
2146 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2147 R.getNameLoc(), IsAligned);
2148 Args.erase(Args.begin() + 1);
2149 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2150 IsUnaligned);
2151 } else {
2152 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2153 }
Richard Smith1cdec012013-09-29 04:40:38 +00002154 return true;
2155
Richard Smithb2f0f052016-10-10 18:54:32 +00002156 case OR_Ambiguous:
2157 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2158 << R.getLookupName() << Range;
2159 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2160 return true;
2161
2162 case OR_Deleted: {
2163 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2164 << Best->Function->isDeleted()
2165 << R.getLookupName()
2166 << S.getDeletedOrUnavailableSuffix(Best->Function)
2167 << Range;
2168 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2169 return true;
2170 }
2171 }
2172 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002173}
2174
Richard Smithb2f0f052016-10-10 18:54:32 +00002175
Sebastian Redlfaf68082008-12-03 20:26:15 +00002176/// FindAllocationFunctions - Finds the overloads of operator new and delete
2177/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002178bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2179 bool UseGlobal, QualType AllocType,
Richard Smithb2f0f052016-10-10 18:54:32 +00002180 bool IsArray, bool &PassAlignment,
2181 MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002182 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00002183 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002184 // --- Choosing an allocation function ---
2185 // C++ 5.3.4p8 - 14 & 18
2186 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2187 // in the scope of the allocated class.
2188 // 2) If an array size is given, look for operator new[], else look for
2189 // operator new.
2190 // 3) The first argument is always size_t. Append the arguments from the
2191 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002192
Richard Smithb2f0f052016-10-10 18:54:32 +00002193 SmallVector<Expr*, 8> AllocArgs;
2194 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2195
2196 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002197 // FIXME: Should the Sema create the expression and embed it in the syntax
2198 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002199 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002200 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002201 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002202 Context.getSizeType(),
2203 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002204 AllocArgs.push_back(&Size);
2205
2206 QualType AlignValT = Context.VoidTy;
2207 if (PassAlignment) {
2208 DeclareGlobalNewDelete();
2209 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2210 }
2211 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2212 if (PassAlignment)
2213 AllocArgs.push_back(&Align);
2214
2215 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002216
Douglas Gregor6642ca22010-02-26 05:06:18 +00002217 // C++ [expr.new]p8:
2218 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002219 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002220 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002221 // type, the allocation function's name is operator new[] and the
2222 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002223 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002224 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002225
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002226 QualType AllocElemType = Context.getBaseElementType(AllocType);
2227
Richard Smithb2f0f052016-10-10 18:54:32 +00002228 // Find the allocation function.
2229 {
2230 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2231
2232 // C++1z [expr.new]p9:
2233 // If the new-expression begins with a unary :: operator, the allocation
2234 // function's name is looked up in the global scope. Otherwise, if the
2235 // allocated type is a class type T or array thereof, the allocation
2236 // function's name is looked up in the scope of T.
2237 if (AllocElemType->isRecordType() && !UseGlobal)
2238 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2239
2240 // We can see ambiguity here if the allocation function is found in
2241 // multiple base classes.
2242 if (R.isAmbiguous())
2243 return true;
2244
2245 // If this lookup fails to find the name, or if the allocated type is not
2246 // a class type, the allocation function's name is looked up in the
2247 // global scope.
2248 if (R.empty())
2249 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2250
2251 assert(!R.empty() && "implicitly declared allocation functions not found");
2252 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2253
2254 // We do our own custom access checks below.
2255 R.suppressDiagnostics();
2256
2257 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2258 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002259 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002260 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002261
Richard Smithb2f0f052016-10-10 18:54:32 +00002262 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002263 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002264 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002265 return false;
2266 }
2267
Richard Smithb2f0f052016-10-10 18:54:32 +00002268 // Note, the name of OperatorNew might have been changed from array to
2269 // non-array by resolveAllocationOverload.
2270 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2271 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2272 ? OO_Array_Delete
2273 : OO_Delete);
2274
Douglas Gregor6642ca22010-02-26 05:06:18 +00002275 // C++ [expr.new]p19:
2276 //
2277 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002278 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002279 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002280 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002281 // the scope of T. If this lookup fails to find the name, or if
2282 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002283 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002284 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002285 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002286 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002287 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002288 LookupQualifiedName(FoundDelete, RD);
2289 }
John McCallfb6f5262010-03-18 08:19:33 +00002290 if (FoundDelete.isAmbiguous())
2291 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002292
Richard Smithb2f0f052016-10-10 18:54:32 +00002293 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002294 if (FoundDelete.empty()) {
2295 DeclareGlobalNewDelete();
2296 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2297 }
2298
2299 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002300
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002301 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002302
John McCalld3be2c82010-09-14 21:34:24 +00002303 // Whether we're looking for a placement operator delete is dictated
2304 // by whether we selected a placement operator new, not by whether
2305 // we had explicit placement arguments. This matters for things like
2306 // struct A { void *operator new(size_t, int = 0); ... };
2307 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002308 //
2309 // We don't have any definition for what a "placement allocation function"
2310 // is, but we assume it's any allocation function whose
2311 // parameter-declaration-clause is anything other than (size_t).
2312 //
2313 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2314 // This affects whether an exception from the constructor of an overaligned
2315 // type uses the sized or non-sized form of aligned operator delete.
2316 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2317 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002318
2319 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002320 // C++ [expr.new]p20:
2321 // A declaration of a placement deallocation function matches the
2322 // declaration of a placement allocation function if it has the
2323 // same number of parameters and, after parameter transformations
2324 // (8.3.5), all parameter types except the first are
2325 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002326 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002327 // To perform this comparison, we compute the function type that
2328 // the deallocation function should have, and use that type both
2329 // for template argument deduction and for comparison purposes.
2330 QualType ExpectedFunctionType;
2331 {
2332 const FunctionProtoType *Proto
2333 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002334
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002335 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002336 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002337 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2338 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002339
John McCalldb40c7f2010-12-14 08:05:40 +00002340 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002341 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002342 EPI.Variadic = Proto->isVariadic();
2343
Douglas Gregor6642ca22010-02-26 05:06:18 +00002344 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002345 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002346 }
2347
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002348 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002349 DEnd = FoundDelete.end();
2350 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002351 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002352 if (FunctionTemplateDecl *FnTmpl =
2353 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002354 // Perform template argument deduction to try to match the
2355 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002356 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002357 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2358 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002359 continue;
2360 } else
2361 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2362
Richard Smithbaa47832016-12-01 02:11:49 +00002363 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2364 ExpectedFunctionType,
2365 /*AdjustExcpetionSpec*/true),
2366 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002367 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002368 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002369
Richard Smithb2f0f052016-10-10 18:54:32 +00002370 if (getLangOpts().CUDA)
2371 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2372 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002373 // C++1y [expr.new]p22:
2374 // For a non-placement allocation function, the normal deallocation
2375 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002376 //
2377 // Per [expr.delete]p10, this lookup prefers a member operator delete
2378 // without a size_t argument, but prefers a non-member operator delete
2379 // with a size_t where possible (which it always is in this case).
2380 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2381 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2382 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2383 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2384 &BestDeallocFns);
2385 if (Selected)
2386 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2387 else {
2388 // If we failed to select an operator, all remaining functions are viable
2389 // but ambiguous.
2390 for (auto Fn : BestDeallocFns)
2391 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002392 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002393 }
2394
2395 // C++ [expr.new]p20:
2396 // [...] If the lookup finds a single matching deallocation
2397 // function, that function will be called; otherwise, no
2398 // deallocation function will be called.
2399 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002400 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002401
Richard Smithb2f0f052016-10-10 18:54:32 +00002402 // C++1z [expr.new]p23:
2403 // If the lookup finds a usual deallocation function (3.7.4.2)
2404 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002405 // as a placement deallocation function, would have been
2406 // selected as a match for the allocation function, the program
2407 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002408 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002409 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002410 UsualDeallocFnInfo Info(*this,
2411 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002412 // Core issue, per mail to core reflector, 2016-10-09:
2413 // If this is a member operator delete, and there is a corresponding
2414 // non-sized member operator delete, this isn't /really/ a sized
2415 // deallocation function, it just happens to have a size_t parameter.
2416 bool IsSizedDelete = Info.HasSizeT;
2417 if (IsSizedDelete && !FoundGlobalDelete) {
2418 auto NonSizedDelete =
2419 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2420 /*WantAlign*/Info.HasAlignValT);
2421 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2422 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2423 IsSizedDelete = false;
2424 }
2425
2426 if (IsSizedDelete) {
2427 SourceRange R = PlaceArgs.empty()
2428 ? SourceRange()
2429 : SourceRange(PlaceArgs.front()->getLocStart(),
2430 PlaceArgs.back()->getLocEnd());
2431 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2432 if (!OperatorDelete->isImplicit())
2433 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2434 << DeleteName;
2435 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002436 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002437
2438 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2439 Matches[0].first);
2440 } else if (!Matches.empty()) {
2441 // We found multiple suitable operators. Per [expr.new]p20, that means we
2442 // call no 'operator delete' function, but we should at least warn the user.
2443 // FIXME: Suppress this warning if the construction cannot throw.
2444 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2445 << DeleteName << AllocElemType;
2446
2447 for (auto &Match : Matches)
2448 Diag(Match.second->getLocation(),
2449 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002450 }
2451
Sebastian Redlfaf68082008-12-03 20:26:15 +00002452 return false;
2453}
2454
2455/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2456/// delete. These are:
2457/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002458/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002459/// void* operator new(std::size_t) throw(std::bad_alloc);
2460/// void* operator new[](std::size_t) throw(std::bad_alloc);
2461/// void operator delete(void *) throw();
2462/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002463/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002464/// void* operator new(std::size_t);
2465/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002466/// void operator delete(void *) noexcept;
2467/// void operator delete[](void *) noexcept;
2468/// // C++1y:
2469/// void* operator new(std::size_t);
2470/// void* operator new[](std::size_t);
2471/// void operator delete(void *) noexcept;
2472/// void operator delete[](void *) noexcept;
2473/// void operator delete(void *, std::size_t) noexcept;
2474/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002475/// @endcode
2476/// Note that the placement and nothrow forms of new are *not* implicitly
2477/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002478void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002479 if (GlobalNewDeleteDeclared)
2480 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002481
Douglas Gregor87f54062009-09-15 22:30:29 +00002482 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002483 // [...] The following allocation and deallocation functions (18.4) are
2484 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002485 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002486 //
Sebastian Redl37588092011-03-14 18:08:30 +00002487 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002488 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002489 // void* operator new[](std::size_t) throw(std::bad_alloc);
2490 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002491 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002492 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002493 // void* operator new(std::size_t);
2494 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002495 // void operator delete(void*) noexcept;
2496 // void operator delete[](void*) noexcept;
2497 // C++1y:
2498 // void* operator new(std::size_t);
2499 // void* operator new[](std::size_t);
2500 // void operator delete(void*) noexcept;
2501 // void operator delete[](void*) noexcept;
2502 // void operator delete(void*, std::size_t) noexcept;
2503 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002504 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002505 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002506 // new, operator new[], operator delete, operator delete[].
2507 //
2508 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2509 // "std" or "bad_alloc" as necessary to form the exception specification.
2510 // However, we do not make these implicit declarations visible to name
2511 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002512 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002513 // The "std::bad_alloc" class has not yet been declared, so build it
2514 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002515 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2516 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002517 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002518 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002519 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002520 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002521 }
Richard Smith59139022016-09-30 22:41:36 +00002522 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002523 // The "std::align_val_t" enum class has not yet been declared, so build it
2524 // implicitly.
2525 auto *AlignValT = EnumDecl::Create(
2526 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2527 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2528 AlignValT->setIntegerType(Context.getSizeType());
2529 AlignValT->setPromotionType(Context.getSizeType());
2530 AlignValT->setImplicit(true);
2531 StdAlignValT = AlignValT;
2532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002533
Sebastian Redlfaf68082008-12-03 20:26:15 +00002534 GlobalNewDeleteDeclared = true;
2535
2536 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2537 QualType SizeT = Context.getSizeType();
2538
Richard Smith96269c52016-09-29 22:49:46 +00002539 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2540 QualType Return, QualType Param) {
2541 llvm::SmallVector<QualType, 3> Params;
2542 Params.push_back(Param);
2543
2544 // Create up to four variants of the function (sized/aligned).
2545 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2546 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002547 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002548
2549 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2550 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2551 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002552 if (Sized)
2553 Params.push_back(SizeT);
2554
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002555 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002556 if (Aligned)
2557 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2558
2559 DeclareGlobalAllocationFunction(
2560 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2561
2562 if (Aligned)
2563 Params.pop_back();
2564 }
2565 }
2566 };
2567
2568 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2569 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2570 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2571 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002572}
2573
2574/// DeclareGlobalAllocationFunction - Declares a single implicit global
2575/// allocation function if it doesn't already exist.
2576void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002577 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002578 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002579 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2580
2581 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002582 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2583 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2584 Alloc != AllocEnd; ++Alloc) {
2585 // Only look at non-template functions, as it is the predefined,
2586 // non-templated allocation function we are trying to declare here.
2587 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002588 if (Func->getNumParams() == Params.size()) {
2589 llvm::SmallVector<QualType, 3> FuncParams;
2590 for (auto *P : Func->parameters())
2591 FuncParams.push_back(
2592 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2593 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002594 // Make the function visible to name lookup, even if we found it in
2595 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002596 // allocation function, or is suppressing that function.
2597 Func->setHidden(false);
Chandler Carruth93538422010-02-03 11:02:14 +00002598 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002599 }
Chandler Carruth93538422010-02-03 11:02:14 +00002600 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002601 }
2602 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002603
Richard Smithc015bc22014-02-07 22:39:53 +00002604 FunctionProtoType::ExtProtoInfo EPI;
2605
Richard Smithf8b417c2014-02-08 00:42:45 +00002606 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002607 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002608 = (Name.getCXXOverloadedOperator() == OO_New ||
2609 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002610 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002611 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002612 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002613 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002614 EPI.ExceptionSpec.Type = EST_Dynamic;
2615 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002616 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002617 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002618 EPI.ExceptionSpec =
2619 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002620 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002621
Artem Belevich07db5cf2016-10-21 20:34:05 +00002622 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2623 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2624 FunctionDecl *Alloc = FunctionDecl::Create(
2625 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2626 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2627 Alloc->setImplicit();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002628
Artem Belevich07db5cf2016-10-21 20:34:05 +00002629 // Implicit sized deallocation functions always have default visibility.
2630 Alloc->addAttr(
2631 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002632
Artem Belevich07db5cf2016-10-21 20:34:05 +00002633 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2634 for (QualType T : Params) {
2635 ParamDecls.push_back(ParmVarDecl::Create(
2636 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2637 /*TInfo=*/nullptr, SC_None, nullptr));
2638 ParamDecls.back()->setImplicit();
2639 }
2640 Alloc->setParams(ParamDecls);
2641 if (ExtraAttr)
2642 Alloc->addAttr(ExtraAttr);
2643 Context.getTranslationUnitDecl()->addDecl(Alloc);
2644 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2645 };
2646
2647 if (!LangOpts.CUDA)
2648 CreateAllocationFunctionDecl(nullptr);
2649 else {
2650 // Host and device get their own declaration so each can be
2651 // defined or re-declared independently.
2652 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2653 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002654 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002655}
2656
Richard Smith1cdec012013-09-29 04:40:38 +00002657FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2658 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002659 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002660 DeclarationName Name) {
2661 DeclareGlobalNewDelete();
2662
2663 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2664 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2665
Richard Smithb2f0f052016-10-10 18:54:32 +00002666 // FIXME: It's possible for this to result in ambiguity, through a
2667 // user-declared variadic operator delete or the enable_if attribute. We
2668 // should probably not consider those cases to be usual deallocation
2669 // functions. But for now we just make an arbitrary choice in that case.
2670 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2671 Overaligned);
2672 assert(Result.FD && "operator delete missing from global scope?");
2673 return Result.FD;
2674}
Richard Smith1cdec012013-09-29 04:40:38 +00002675
Richard Smithb2f0f052016-10-10 18:54:32 +00002676FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2677 CXXRecordDecl *RD) {
2678 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002679
Richard Smithb2f0f052016-10-10 18:54:32 +00002680 FunctionDecl *OperatorDelete = nullptr;
2681 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2682 return nullptr;
2683 if (OperatorDelete)
2684 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002685
Richard Smithb2f0f052016-10-10 18:54:32 +00002686 // If there's no class-specific operator delete, look up the global
2687 // non-array delete.
2688 return FindUsualDeallocationFunction(
2689 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2690 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002691}
2692
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002693bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2694 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002695 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002696 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002697 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002698 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002699
John McCall27b18f82009-11-17 02:14:36 +00002700 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002701 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002702
Chandler Carruthb6f99172010-06-28 00:30:51 +00002703 Found.suppressDiagnostics();
2704
Richard Smithb2f0f052016-10-10 18:54:32 +00002705 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002706
Richard Smithb2f0f052016-10-10 18:54:32 +00002707 // C++17 [expr.delete]p10:
2708 // If the deallocation functions have class scope, the one without a
2709 // parameter of type std::size_t is selected.
2710 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2711 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2712 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002713
Richard Smithb2f0f052016-10-10 18:54:32 +00002714 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002715 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002716 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002717
Richard Smithb2f0f052016-10-10 18:54:32 +00002718 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002719 if (Operator->isDeleted()) {
2720 if (Diagnose) {
2721 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002722 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002723 }
2724 return true;
2725 }
2726
Richard Smith921bd202012-02-26 09:11:52 +00002727 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002728 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002729 return true;
2730
John McCall66a87592010-08-04 00:31:26 +00002731 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002732 }
John McCall66a87592010-08-04 00:31:26 +00002733
Richard Smithb2f0f052016-10-10 18:54:32 +00002734 // We found multiple suitable operators; complain about the ambiguity.
2735 // FIXME: The standard doesn't say to do this; it appears that the intent
2736 // is that this should never happen.
2737 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002738 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002739 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2740 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002741 for (auto &Match : Matches)
2742 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002743 }
John McCall66a87592010-08-04 00:31:26 +00002744 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002745 }
2746
2747 // We did find operator delete/operator delete[] declarations, but
2748 // none of them were suitable.
2749 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002750 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002751 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2752 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002753
Richard Smithb2f0f052016-10-10 18:54:32 +00002754 for (NamedDecl *D : Found)
2755 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002756 diag::note_member_declared_here) << Name;
2757 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002758 return true;
2759 }
2760
Craig Topperc3ec1492014-05-26 06:22:03 +00002761 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002762 return false;
2763}
2764
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002765namespace {
2766/// \brief Checks whether delete-expression, and new-expression used for
2767/// initializing deletee have the same array form.
2768class MismatchingNewDeleteDetector {
2769public:
2770 enum MismatchResult {
2771 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2772 NoMismatch,
2773 /// Indicates that variable is initialized with mismatching form of \a new.
2774 VarInitMismatches,
2775 /// Indicates that member is initialized with mismatching form of \a new.
2776 MemberInitMismatches,
2777 /// Indicates that 1 or more constructors' definitions could not been
2778 /// analyzed, and they will be checked again at the end of translation unit.
2779 AnalyzeLater
2780 };
2781
2782 /// \param EndOfTU True, if this is the final analysis at the end of
2783 /// translation unit. False, if this is the initial analysis at the point
2784 /// delete-expression was encountered.
2785 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002786 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002787 HasUndefinedConstructors(false) {}
2788
2789 /// \brief Checks whether pointee of a delete-expression is initialized with
2790 /// matching form of new-expression.
2791 ///
2792 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2793 /// point where delete-expression is encountered, then a warning will be
2794 /// issued immediately. If return value is \c AnalyzeLater at the point where
2795 /// delete-expression is seen, then member will be analyzed at the end of
2796 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2797 /// couldn't be analyzed. If at least one constructor initializes the member
2798 /// with matching type of new, the return value is \c NoMismatch.
2799 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2800 /// \brief Analyzes a class member.
2801 /// \param Field Class member to analyze.
2802 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2803 /// for deleting the \p Field.
2804 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002805 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002806 /// List of mismatching new-expressions used for initialization of the pointee
2807 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2808 /// Indicates whether delete-expression was in array form.
2809 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002810
2811private:
2812 const bool EndOfTU;
2813 /// \brief Indicates that there is at least one constructor without body.
2814 bool HasUndefinedConstructors;
2815 /// \brief Returns \c CXXNewExpr from given initialization expression.
2816 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002817 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002818 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2819 /// \brief Returns whether member is initialized with mismatching form of
2820 /// \c new either by the member initializer or in-class initialization.
2821 ///
2822 /// If bodies of all constructors are not visible at the end of translation
2823 /// unit or at least one constructor initializes member with the matching
2824 /// form of \c new, mismatch cannot be proven, and this function will return
2825 /// \c NoMismatch.
2826 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2827 /// \brief Returns whether variable is initialized with mismatching form of
2828 /// \c new.
2829 ///
2830 /// If variable is initialized with matching form of \c new or variable is not
2831 /// initialized with a \c new expression, this function will return true.
2832 /// If variable is initialized with mismatching form of \c new, returns false.
2833 /// \param D Variable to analyze.
2834 bool hasMatchingVarInit(const DeclRefExpr *D);
2835 /// \brief Checks whether the constructor initializes pointee with mismatching
2836 /// form of \c new.
2837 ///
2838 /// Returns true, if member is initialized with matching form of \c new in
2839 /// member initializer list. Returns false, if member is initialized with the
2840 /// matching form of \c new in this constructor's initializer or given
2841 /// constructor isn't defined at the point where delete-expression is seen, or
2842 /// member isn't initialized by the constructor.
2843 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2844 /// \brief Checks whether member is initialized with matching form of
2845 /// \c new in member initializer list.
2846 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2847 /// Checks whether member is initialized with mismatching form of \c new by
2848 /// in-class initializer.
2849 MismatchResult analyzeInClassInitializer();
2850};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002851}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002852
2853MismatchingNewDeleteDetector::MismatchResult
2854MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2855 NewExprs.clear();
2856 assert(DE && "Expected delete-expression");
2857 IsArrayForm = DE->isArrayForm();
2858 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2859 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2860 return analyzeMemberExpr(ME);
2861 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2862 if (!hasMatchingVarInit(D))
2863 return VarInitMismatches;
2864 }
2865 return NoMismatch;
2866}
2867
2868const CXXNewExpr *
2869MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2870 assert(E != nullptr && "Expected a valid initializer expression");
2871 E = E->IgnoreParenImpCasts();
2872 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2873 if (ILE->getNumInits() == 1)
2874 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2875 }
2876
2877 return dyn_cast_or_null<const CXXNewExpr>(E);
2878}
2879
2880bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2881 const CXXCtorInitializer *CI) {
2882 const CXXNewExpr *NE = nullptr;
2883 if (Field == CI->getMember() &&
2884 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2885 if (NE->isArray() == IsArrayForm)
2886 return true;
2887 else
2888 NewExprs.push_back(NE);
2889 }
2890 return false;
2891}
2892
2893bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2894 const CXXConstructorDecl *CD) {
2895 if (CD->isImplicit())
2896 return false;
2897 const FunctionDecl *Definition = CD;
2898 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2899 HasUndefinedConstructors = true;
2900 return EndOfTU;
2901 }
2902 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2903 if (hasMatchingNewInCtorInit(CI))
2904 return true;
2905 }
2906 return false;
2907}
2908
2909MismatchingNewDeleteDetector::MismatchResult
2910MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2911 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00002912 const Expr *InitExpr = Field->getInClassInitializer();
2913 if (!InitExpr)
2914 return EndOfTU ? NoMismatch : AnalyzeLater;
2915 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002916 if (NE->isArray() != IsArrayForm) {
2917 NewExprs.push_back(NE);
2918 return MemberInitMismatches;
2919 }
2920 }
2921 return NoMismatch;
2922}
2923
2924MismatchingNewDeleteDetector::MismatchResult
2925MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2926 bool DeleteWasArrayForm) {
2927 assert(Field != nullptr && "Analysis requires a valid class member.");
2928 this->Field = Field;
2929 IsArrayForm = DeleteWasArrayForm;
2930 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2931 for (const auto *CD : RD->ctors()) {
2932 if (hasMatchingNewInCtor(CD))
2933 return NoMismatch;
2934 }
2935 if (HasUndefinedConstructors)
2936 return EndOfTU ? NoMismatch : AnalyzeLater;
2937 if (!NewExprs.empty())
2938 return MemberInitMismatches;
2939 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
2940 : NoMismatch;
2941}
2942
2943MismatchingNewDeleteDetector::MismatchResult
2944MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
2945 assert(ME != nullptr && "Expected a member expression");
2946 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2947 return analyzeField(F, IsArrayForm);
2948 return NoMismatch;
2949}
2950
2951bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
2952 const CXXNewExpr *NE = nullptr;
2953 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
2954 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
2955 NE->isArray() != IsArrayForm) {
2956 NewExprs.push_back(NE);
2957 }
2958 }
2959 return NewExprs.empty();
2960}
2961
2962static void
2963DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
2964 const MismatchingNewDeleteDetector &Detector) {
2965 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
2966 FixItHint H;
2967 if (!Detector.IsArrayForm)
2968 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
2969 else {
2970 SourceLocation RSquare = Lexer::findLocationAfterToken(
2971 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
2972 SemaRef.getLangOpts(), true);
2973 if (RSquare.isValid())
2974 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
2975 }
2976 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
2977 << Detector.IsArrayForm << H;
2978
2979 for (const auto *NE : Detector.NewExprs)
2980 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
2981 << Detector.IsArrayForm;
2982}
2983
2984void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
2985 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
2986 return;
2987 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
2988 switch (Detector.analyzeDeleteExpr(DE)) {
2989 case MismatchingNewDeleteDetector::VarInitMismatches:
2990 case MismatchingNewDeleteDetector::MemberInitMismatches: {
2991 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
2992 break;
2993 }
2994 case MismatchingNewDeleteDetector::AnalyzeLater: {
2995 DeleteExprs[Detector.Field].push_back(
2996 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
2997 break;
2998 }
2999 case MismatchingNewDeleteDetector::NoMismatch:
3000 break;
3001 }
3002}
3003
3004void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3005 bool DeleteWasArrayForm) {
3006 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3007 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3008 case MismatchingNewDeleteDetector::VarInitMismatches:
3009 llvm_unreachable("This analysis should have been done for class members.");
3010 case MismatchingNewDeleteDetector::AnalyzeLater:
3011 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3012 "translation unit.");
3013 case MismatchingNewDeleteDetector::MemberInitMismatches:
3014 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3015 break;
3016 case MismatchingNewDeleteDetector::NoMismatch:
3017 break;
3018 }
3019}
3020
Sebastian Redlbd150f42008-11-21 19:14:01 +00003021/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3022/// @code ::delete ptr; @endcode
3023/// or
3024/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003025ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003026Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003027 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003028 // C++ [expr.delete]p1:
3029 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003030 // non-explicit conversion function to a pointer type. The result has type
3031 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003032 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003033 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3034
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003035 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003036 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003037 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003038 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003039
John Wiegley01296292011-04-08 18:41:53 +00003040 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003041 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003042 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003043 if (Ex.isInvalid())
3044 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003045
John Wiegley01296292011-04-08 18:41:53 +00003046 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003047
Richard Smithccc11812013-05-21 19:05:48 +00003048 class DeleteConverter : public ContextualImplicitConverter {
3049 public:
3050 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003051
Craig Toppere14c0f82014-03-12 04:55:44 +00003052 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003053 // FIXME: If we have an operator T* and an operator void*, we must pick
3054 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003055 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003056 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003057 return true;
3058 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003059 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003060
Richard Smithccc11812013-05-21 19:05:48 +00003061 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003062 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003063 return S.Diag(Loc, diag::err_delete_operand) << T;
3064 }
3065
3066 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003067 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003068 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3069 }
3070
3071 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003072 QualType T,
3073 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003074 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3075 }
3076
3077 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003078 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003079 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3080 << ConvTy;
3081 }
3082
3083 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003084 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003085 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3086 }
3087
3088 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003089 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003090 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3091 << ConvTy;
3092 }
3093
3094 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003095 QualType T,
3096 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003097 llvm_unreachable("conversion functions are permitted");
3098 }
3099 } Converter;
3100
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003101 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003102 if (Ex.isInvalid())
3103 return ExprError();
3104 Type = Ex.get()->getType();
3105 if (!Converter.match(Type))
3106 // FIXME: PerformContextualImplicitConversion should return ExprError
3107 // itself in this case.
3108 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003109
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003110 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003111 QualType PointeeElem = Context.getBaseElementType(Pointee);
3112
3113 if (unsigned AddressSpace = Pointee.getAddressSpace())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003114 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003115 diag::err_address_space_qualified_delete)
3116 << Pointee.getUnqualifiedType() << AddressSpace;
3117
Craig Topperc3ec1492014-05-26 06:22:03 +00003118 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003119 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003120 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003121 // effectively bans deletion of "void*". However, most compilers support
3122 // this, so we treat it as a warning unless we're in a SFINAE context.
3123 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003124 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003125 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003126 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003127 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003128 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003129 // FIXME: This can result in errors if the definition was imported from a
3130 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003131 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003132 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003133 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3134 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3135 }
3136 }
3137
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003138 if (Pointee->isArrayType() && !ArrayForm) {
3139 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003140 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003141 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003142 ArrayForm = true;
3143 }
3144
Anders Carlssona471db02009-08-16 20:29:29 +00003145 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3146 ArrayForm ? OO_Array_Delete : OO_Delete);
3147
Eli Friedmanae4280f2011-07-26 22:25:31 +00003148 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003149 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003150 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3151 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003152 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003153
John McCall284c48f2011-01-27 09:37:56 +00003154 // If we're allocating an array of records, check whether the
3155 // usual operator delete[] has a size_t parameter.
3156 if (ArrayForm) {
3157 // If the user specifically asked to use the global allocator,
3158 // we'll need to do the lookup into the class.
3159 if (UseGlobal)
3160 UsualArrayDeleteWantsSize =
3161 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3162
3163 // Otherwise, the usual operator delete[] should be the
3164 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003165 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003166 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003167 UsualDeallocFnInfo(*this,
3168 DeclAccessPair::make(OperatorDelete, AS_public))
3169 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003170 }
3171
Richard Smitheec915d62012-02-18 04:13:32 +00003172 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003173 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003174 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003175 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003176 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3177 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003178 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003179
Nico Weber5a9259c2016-01-15 21:45:31 +00003180 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3181 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3182 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3183 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003185
Richard Smithb2f0f052016-10-10 18:54:32 +00003186 if (!OperatorDelete) {
3187 bool IsComplete = isCompleteType(StartLoc, Pointee);
3188 bool CanProvideSize =
3189 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3190 Pointee.isDestructedType());
3191 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3192
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003193 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003194 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3195 Overaligned, DeleteName);
3196 }
Mike Stump11289f42009-09-09 15:08:12 +00003197
Eli Friedmanfa0df832012-02-02 03:46:19 +00003198 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003199
Douglas Gregorfa778132011-02-01 15:50:11 +00003200 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003201 if (PointeeRD) {
3202 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00003203 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00003204 PDiag(diag::err_access_dtor) << PointeeElem);
3205 }
3206 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003207 }
3208
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003209 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003210 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3211 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003212 AnalyzeDeleteExprMismatch(Result);
3213 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003214}
3215
Nico Weber5a9259c2016-01-15 21:45:31 +00003216void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3217 bool IsDelete, bool CallCanBeVirtual,
3218 bool WarnOnNonAbstractTypes,
3219 SourceLocation DtorLoc) {
3220 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
3221 return;
3222
3223 // C++ [expr.delete]p3:
3224 // In the first alternative (delete object), if the static type of the
3225 // object to be deleted is different from its dynamic type, the static
3226 // type shall be a base class of the dynamic type of the object to be
3227 // deleted and the static type shall have a virtual destructor or the
3228 // behavior is undefined.
3229 //
3230 const CXXRecordDecl *PointeeRD = dtor->getParent();
3231 // Note: a final class cannot be derived from, no issue there
3232 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3233 return;
3234
3235 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3236 if (PointeeRD->isAbstract()) {
3237 // If the class is abstract, we warn by default, because we're
3238 // sure the code has undefined behavior.
3239 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3240 << ClassType;
3241 } else if (WarnOnNonAbstractTypes) {
3242 // Otherwise, if this is not an array delete, it's a bit suspect,
3243 // but not necessarily wrong.
3244 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3245 << ClassType;
3246 }
3247 if (!IsDelete) {
3248 std::string TypeStr;
3249 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3250 Diag(DtorLoc, diag::note_delete_non_virtual)
3251 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3252 }
3253}
3254
Richard Smith03a4aa32016-06-23 19:02:52 +00003255Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3256 SourceLocation StmtLoc,
3257 ConditionKind CK) {
3258 ExprResult E =
3259 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3260 if (E.isInvalid())
3261 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003262 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3263 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003264}
3265
Douglas Gregor633caca2009-11-23 23:44:04 +00003266/// \brief Check the use of the given variable as a C++ condition in an if,
3267/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003268ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003269 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003270 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003271 if (ConditionVar->isInvalidDecl())
3272 return ExprError();
3273
Douglas Gregor633caca2009-11-23 23:44:04 +00003274 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003275
Douglas Gregor633caca2009-11-23 23:44:04 +00003276 // C++ [stmt.select]p2:
3277 // The declarator shall not specify a function or an array.
3278 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003279 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003280 diag::err_invalid_use_of_function_type)
3281 << ConditionVar->getSourceRange());
3282 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003283 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003284 diag::err_invalid_use_of_array_type)
3285 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003286
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003287 ExprResult Condition = DeclRefExpr::Create(
3288 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3289 /*enclosing*/ false, ConditionVar->getLocation(),
3290 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003291
Eli Friedmanfa0df832012-02-02 03:46:19 +00003292 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003293
Richard Smith03a4aa32016-06-23 19:02:52 +00003294 switch (CK) {
3295 case ConditionKind::Boolean:
3296 return CheckBooleanCondition(StmtLoc, Condition.get());
3297
Richard Smithb130fe72016-06-23 19:16:49 +00003298 case ConditionKind::ConstexprIf:
3299 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3300
Richard Smith03a4aa32016-06-23 19:02:52 +00003301 case ConditionKind::Switch:
3302 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003304
Richard Smith03a4aa32016-06-23 19:02:52 +00003305 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003306}
3307
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003308/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003309ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003310 // C++ 6.4p4:
3311 // The value of a condition that is an initialized declaration in a statement
3312 // other than a switch statement is the value of the declared variable
3313 // implicitly converted to type bool. If that conversion is ill-formed, the
3314 // program is ill-formed.
3315 // The value of a condition that is an expression is the value of the
3316 // expression, implicitly converted to bool.
3317 //
Richard Smithb130fe72016-06-23 19:16:49 +00003318 // FIXME: Return this value to the caller so they don't need to recompute it.
3319 llvm::APSInt Value(/*BitWidth*/1);
3320 return (IsConstexpr && !CondExpr->isValueDependent())
3321 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3322 CCEK_ConstexprIf)
3323 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003324}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003325
3326/// Helper function to determine whether this is the (deprecated) C++
3327/// conversion from a string literal to a pointer to non-const char or
3328/// non-const wchar_t (for narrow and wide string literals,
3329/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003330bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003331Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3332 // Look inside the implicit cast, if it exists.
3333 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3334 From = Cast->getSubExpr();
3335
3336 // A string literal (2.13.4) that is not a wide string literal can
3337 // be converted to an rvalue of type "pointer to char"; a wide
3338 // string literal can be converted to an rvalue of type "pointer
3339 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003340 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003341 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003342 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003343 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003344 // This conversion is considered only when there is an
3345 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003346 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3347 switch (StrLit->getKind()) {
3348 case StringLiteral::UTF8:
3349 case StringLiteral::UTF16:
3350 case StringLiteral::UTF32:
3351 // We don't allow UTF literals to be implicitly converted
3352 break;
3353 case StringLiteral::Ascii:
3354 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3355 ToPointeeType->getKind() == BuiltinType::Char_S);
3356 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003357 return Context.typesAreCompatible(Context.getWideCharType(),
3358 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003359 }
3360 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003361 }
3362
3363 return false;
3364}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003365
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003366static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003367 SourceLocation CastLoc,
3368 QualType Ty,
3369 CastKind Kind,
3370 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003371 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003372 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003373 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003374 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003375 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003376 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003377 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003378 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003379
Richard Smith72d74052013-07-20 19:41:36 +00003380 if (S.RequireNonAbstractType(CastLoc, Ty,
3381 diag::err_allocation_of_abstract_type))
3382 return ExprError();
3383
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003384 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003385 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003386
Richard Smith5179eb72016-06-28 19:03:57 +00003387 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3388 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003389 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003390 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003391
Richard Smithf8adcdc2014-07-17 05:12:35 +00003392 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003393 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003394 ConstructorArgs, HadMultipleCandidates,
3395 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3396 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003397 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003398 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003399
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003400 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003401 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402
John McCalle3027922010-08-25 11:45:40 +00003403 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003404 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003405
Richard Smithd3f2d322015-02-24 21:16:19 +00003406 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003407 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003408 return ExprError();
3409
Douglas Gregora4253922010-04-16 22:17:36 +00003410 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003411 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3412 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003413 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003414 if (Result.isInvalid())
3415 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003416 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003417 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3418 CK_UserDefinedConversion, Result.get(),
3419 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420
Douglas Gregor668443e2011-01-20 00:18:04 +00003421 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003422 }
3423 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003424}
Douglas Gregora4253922010-04-16 22:17:36 +00003425
Douglas Gregor5fb53972009-01-14 15:45:31 +00003426/// PerformImplicitConversion - Perform an implicit conversion of the
3427/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003428/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003429/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003430/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003431ExprResult
3432Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003433 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003434 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003435 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003436 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003437 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003438 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3439 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003440 if (Res.isInvalid())
3441 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003442 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003443 break;
John Wiegley01296292011-04-08 18:41:53 +00003444 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003445
Anders Carlsson110b07b2009-09-15 06:28:28 +00003446 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003447
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003448 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003449 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003450 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003451 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003452 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003453 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003454
Anders Carlsson110b07b2009-09-15 06:28:28 +00003455 // If the user-defined conversion is specified by a conversion function,
3456 // the initial standard conversion sequence converts the source type to
3457 // the implicit object parameter of the conversion function.
3458 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003459 } else {
3460 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003461 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003462 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003463 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003464 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003465 // initial standard conversion sequence converts the source type to
3466 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003467 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3468 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003469 }
Richard Smith72d74052013-07-20 19:41:36 +00003470 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003471 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003472 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003473 PerformImplicitConversion(From, BeforeToType,
3474 ICS.UserDefined.Before, AA_Converting,
3475 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003476 if (Res.isInvalid())
3477 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003478 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003480
3481 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003482 = BuildCXXCastArgument(*this,
3483 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003484 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003485 CastKind, cast<CXXMethodDecl>(FD),
3486 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003487 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003488 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003489
3490 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003491 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003492
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003493 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003494
Richard Smith507840d2011-11-29 22:48:16 +00003495 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3496 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003497 }
John McCall0d1da222010-01-12 00:44:57 +00003498
3499 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003500 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003501 PDiag(diag::err_typecheck_ambiguous_condition)
3502 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003503 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003504
Douglas Gregor39c16d42008-10-24 04:54:22 +00003505 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003506 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003507
3508 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003509 bool Diagnosed =
3510 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3511 From->getType(), From, Action);
3512 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003513 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003514 }
3515
3516 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003517 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003518}
3519
Richard Smith507840d2011-11-29 22:48:16 +00003520/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003521/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003522/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003523/// expression. Flavor is the context in which we're performing this
3524/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003525ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003526Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003527 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003528 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003529 CheckedConversionKind CCK) {
3530 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003531
Mike Stump87c57ac2009-05-16 07:39:55 +00003532 // Overall FIXME: we are recomputing too many types here and doing far too
3533 // much extra work. What this means is that we need to keep track of more
3534 // information that is computed when we try the implicit conversion initially,
3535 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003536 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003537
Douglas Gregor2fe98832008-11-03 19:09:14 +00003538 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003539 // FIXME: When can ToType be a reference type?
3540 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003541 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003542 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003543 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003544 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003545 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003546 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003547 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003548 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3549 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003550 ConstructorArgs, /*HadMultipleCandidates*/ false,
3551 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3552 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003553 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003554 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003555 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3556 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003557 From, /*HadMultipleCandidates*/ false,
3558 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3559 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003560 }
3561
Douglas Gregor980fb162010-04-29 18:24:40 +00003562 // Resolve overloaded function references.
3563 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3564 DeclAccessPair Found;
3565 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3566 true, Found);
3567 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003568 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003569
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003570 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003571 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003572
Douglas Gregor980fb162010-04-29 18:24:40 +00003573 From = FixOverloadedFunctionReference(From, Found, Fn);
3574 FromType = From->getType();
3575 }
3576
Richard Smitha23ab512013-05-23 00:30:41 +00003577 // If we're converting to an atomic type, first convert to the corresponding
3578 // non-atomic type.
3579 QualType ToAtomicType;
3580 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3581 ToAtomicType = ToType;
3582 ToType = ToAtomic->getValueType();
3583 }
3584
George Burgess IV8d141e02015-12-14 22:00:49 +00003585 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003586 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003587 switch (SCS.First) {
3588 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003589 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3590 FromType = FromAtomic->getValueType().getUnqualifiedType();
3591 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3592 From, /*BasePath=*/nullptr, VK_RValue);
3593 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003594 break;
3595
Eli Friedman946b7b52012-01-24 22:51:26 +00003596 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003597 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003598 ExprResult FromRes = DefaultLvalueConversion(From);
3599 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003600 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003601 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003602 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003603 }
John McCall34376a62010-12-04 03:47:34 +00003604
Douglas Gregor39c16d42008-10-24 04:54:22 +00003605 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003606 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003607 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003608 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003609 break;
3610
3611 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003612 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003613 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003614 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003615 break;
3616
3617 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003618 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003619 }
3620
Richard Smith507840d2011-11-29 22:48:16 +00003621 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003622 switch (SCS.Second) {
3623 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003624 // C++ [except.spec]p5:
3625 // [For] assignment to and initialization of pointers to functions,
3626 // pointers to member functions, and references to functions: the
3627 // target entity shall allow at least the exceptions allowed by the
3628 // source value in the assignment or initialization.
3629 switch (Action) {
3630 case AA_Assigning:
3631 case AA_Initializing:
3632 // Note, function argument passing and returning are initialization.
3633 case AA_Passing:
3634 case AA_Returning:
3635 case AA_Sending:
3636 case AA_Passing_CFAudited:
3637 if (CheckExceptionSpecCompatibility(From, ToType))
3638 return ExprError();
3639 break;
3640
3641 case AA_Casting:
3642 case AA_Converting:
3643 // Casts and implicit conversions are not initialization, so are not
3644 // checked for exception specification mismatches.
3645 break;
3646 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003647 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003648 break;
3649
3650 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003651 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003652 if (ToType->isBooleanType()) {
3653 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3654 SCS.Second == ICK_Integral_Promotion &&
3655 "only enums with fixed underlying type can promote to bool");
3656 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003657 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003658 } else {
3659 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003660 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003661 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003662 break;
3663
3664 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003665 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003666 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003667 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003668 break;
3669
3670 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003671 case ICK_Complex_Conversion: {
3672 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3673 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3674 CastKind CK;
3675 if (FromEl->isRealFloatingType()) {
3676 if (ToEl->isRealFloatingType())
3677 CK = CK_FloatingComplexCast;
3678 else
3679 CK = CK_FloatingComplexToIntegralComplex;
3680 } else if (ToEl->isRealFloatingType()) {
3681 CK = CK_IntegralComplexToFloatingComplex;
3682 } else {
3683 CK = CK_IntegralComplexCast;
3684 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003685 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003686 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003687 break;
John McCall8cb679e2010-11-15 09:13:47 +00003688 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003689
Douglas Gregor39c16d42008-10-24 04:54:22 +00003690 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003691 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003692 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003693 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003694 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00003695 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003696 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003697 break;
3698
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003699 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003700 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003701 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003702 break;
3703
John McCall31168b02011-06-15 23:02:42 +00003704 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003705 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003706 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003707 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00003708 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003709 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003710 diag::ext_typecheck_convert_incompatible_pointer)
3711 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003712 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003713 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003714 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003715 diag::ext_typecheck_convert_incompatible_pointer)
3716 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003717 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00003718
Douglas Gregor33823722011-06-11 01:09:30 +00003719 if (From->getType()->isObjCObjectPointerType() &&
3720 ToType->isObjCObjectPointerType())
3721 EmitRelatedResultTypeNote(From);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003722 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00003723 else if (getLangOpts().ObjCAutoRefCount &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00003724 !CheckObjCARCUnavailableWeakConversion(ToType,
Fariborz Jahanianf2913402011-07-08 17:41:42 +00003725 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00003726 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003727 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003728 diag::err_arc_weak_unavailable_assign);
3729 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003730 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00003731 diag::err_arc_convesion_of_weak_unavailable)
3732 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00003733 << From->getSourceRange();
3734 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003735
John McCall8cb679e2010-11-15 09:13:47 +00003736 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003737 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003738 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003739 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00003740
3741 // Make sure we extend blocks if necessary.
3742 // FIXME: doing this here is really ugly.
3743 if (Kind == CK_BlockPointerToObjCPointerCast) {
3744 ExprResult E = From;
3745 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003746 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00003747 }
Fariborz Jahanian374089e2013-07-31 17:12:26 +00003748 if (getLangOpts().ObjCAutoRefCount)
3749 CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00003750 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003751 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003752 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003753 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003754
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003755 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00003756 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003757 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003758 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003759 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00003760 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003761 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00003762
3763 // We may not have been able to figure out what this member pointer resolved
3764 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00003765 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003766 (void)isCompleteType(From->getExprLoc(), From->getType());
3767 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00003768 }
David Majnemerd96b9972014-08-08 00:10:39 +00003769
Richard Smith507840d2011-11-29 22:48:16 +00003770 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003771 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003772 break;
3773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003774
Abramo Bagnara7ccce982011-04-07 09:26:19 +00003775 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003776 // Perform half-to-boolean conversion via float.
3777 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003778 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003779 FromType = Context.FloatTy;
3780 }
3781
Richard Smith507840d2011-11-29 22:48:16 +00003782 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003783 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003784 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003785 break;
3786
Douglas Gregor88d292c2010-05-13 16:44:06 +00003787 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00003788 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003789 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003790 ToType.getNonReferenceType(),
3791 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003792 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003793 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00003794 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003795 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00003796
Richard Smith507840d2011-11-29 22:48:16 +00003797 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3798 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003799 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003800 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00003801 }
3802
Douglas Gregor46188682010-05-18 22:42:18 +00003803 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003804 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003805 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003806 break;
3807
George Burgess IVdf1ed002016-01-13 01:52:39 +00003808 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00003809 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00003810 Expr *Elem = prepareVectorSplat(ToType, From).get();
3811 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3812 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003813 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00003814 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003815
Douglas Gregor46188682010-05-18 22:42:18 +00003816 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00003817 // Case 1. x -> _Complex y
3818 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3819 QualType ElType = ToComplex->getElementType();
3820 bool isFloatingComplex = ElType->isRealFloatingType();
3821
3822 // x -> y
3823 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3824 // do nothing
3825 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003826 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003827 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00003828 } else {
3829 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003830 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003831 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00003832 }
3833 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00003834 From = ImpCastExprToType(From, ToType,
3835 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003836 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00003837
3838 // Case 2. _Complex x -> y
3839 } else {
3840 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3841 assert(FromComplex);
3842
3843 QualType ElType = FromComplex->getElementType();
3844 bool isFloatingComplex = ElType->isRealFloatingType();
3845
3846 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00003847 From = ImpCastExprToType(From, ElType,
3848 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00003849 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003850 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003851
3852 // x -> y
3853 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3854 // do nothing
3855 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003856 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003857 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003858 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003859 } else {
3860 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003861 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003862 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003863 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003864 }
3865 }
Douglas Gregor46188682010-05-18 22:42:18 +00003866 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00003867
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00003868 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003869 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003870 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00003871 break;
3872 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003873
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003874 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003875 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003876 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00003877 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3878 if (FromRes.isInvalid())
3879 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003880 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003881 assert ((ConvTy == Sema::Compatible) &&
3882 "Improper transparent union conversion");
3883 (void)ConvTy;
3884 break;
3885 }
3886
Guy Benyei259f9f42013-02-07 16:05:33 +00003887 case ICK_Zero_Event_Conversion:
3888 From = ImpCastExprToType(From, ToType,
3889 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003890 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00003891 break;
3892
Egor Churaev89831422016-12-23 14:55:49 +00003893 case ICK_Zero_Queue_Conversion:
3894 From = ImpCastExprToType(From, ToType,
3895 CK_ZeroToOCLQueue,
3896 From->getValueKind()).get();
3897 break;
3898
Douglas Gregor46188682010-05-18 22:42:18 +00003899 case ICK_Lvalue_To_Rvalue:
3900 case ICK_Array_To_Pointer:
3901 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003902 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00003903 case ICK_Qualification:
3904 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00003905 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00003906 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003907 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003908 }
3909
3910 switch (SCS.Third) {
3911 case ICK_Identity:
3912 // Nothing to do.
3913 break;
3914
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003915 case ICK_Function_Conversion:
3916 // If both sides are functions (or pointers/references to them), there could
3917 // be incompatible exception declarations.
3918 if (CheckExceptionSpecCompatibility(From, ToType))
3919 return ExprError();
3920
3921 From = ImpCastExprToType(From, ToType, CK_NoOp,
3922 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3923 break;
3924
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003925 case ICK_Qualification: {
3926 // The qualification keeps the category of the inner expression, unless the
3927 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00003928 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003929 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00003930 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003931 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00003932
Douglas Gregore981bb02011-03-14 16:13:32 +00003933 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003934 !getLangOpts().WritableStrings) {
3935 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3936 ? diag::ext_deprecated_string_literal_conversion
3937 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00003938 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003939 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00003940
Douglas Gregor39c16d42008-10-24 04:54:22 +00003941 break;
Richard Smitha23ab512013-05-23 00:30:41 +00003942 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003943
Douglas Gregor39c16d42008-10-24 04:54:22 +00003944 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003945 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003946 }
3947
Douglas Gregor298f43d2012-04-12 20:42:30 +00003948 // If this conversion sequence involved a scalar -> atomic conversion, perform
3949 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00003950 if (!ToAtomicType.isNull()) {
3951 assert(Context.hasSameType(
3952 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3953 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003954 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00003955 }
3956
George Burgess IV8d141e02015-12-14 22:00:49 +00003957 // If this conversion sequence succeeded and involved implicitly converting a
3958 // _Nullable type to a _Nonnull one, complain.
3959 if (CCK == CCK_ImplicitConversion)
3960 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
3961 From->getLocStart());
3962
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003963 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003964}
3965
Chandler Carruth8e172c62011-05-01 06:51:22 +00003966/// \brief Check the completeness of a type in a unary type trait.
3967///
3968/// If the particular type trait requires a complete type, tries to complete
3969/// it. If completing the type fails, a diagnostic is emitted and false
3970/// returned. If completing the type succeeds or no completion was required,
3971/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00003972static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00003973 SourceLocation Loc,
3974 QualType ArgTy) {
3975 // C++0x [meta.unary.prop]p3:
3976 // For all of the class templates X declared in this Clause, instantiating
3977 // that template with a template argument that is a class template
3978 // specialization may result in the implicit instantiation of the template
3979 // argument if and only if the semantics of X require that the argument
3980 // must be a complete type.
3981 // We apply this rule to all the type trait expressions used to implement
3982 // these class templates. We also try to follow any GCC documented behavior
3983 // in these expressions to ensure portability of standard libraries.
3984 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00003985 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00003986 // is_complete_type somewhat obviously cannot require a complete type.
3987 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003988 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003989
3990 // These traits are modeled on the type predicates in C++0x
3991 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3992 // requiring a complete type, as whether or not they return true cannot be
3993 // impacted by the completeness of the type.
3994 case UTT_IsVoid:
3995 case UTT_IsIntegral:
3996 case UTT_IsFloatingPoint:
3997 case UTT_IsArray:
3998 case UTT_IsPointer:
3999 case UTT_IsLvalueReference:
4000 case UTT_IsRvalueReference:
4001 case UTT_IsMemberFunctionPointer:
4002 case UTT_IsMemberObjectPointer:
4003 case UTT_IsEnum:
4004 case UTT_IsUnion:
4005 case UTT_IsClass:
4006 case UTT_IsFunction:
4007 case UTT_IsReference:
4008 case UTT_IsArithmetic:
4009 case UTT_IsFundamental:
4010 case UTT_IsObject:
4011 case UTT_IsScalar:
4012 case UTT_IsCompound:
4013 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004014 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004015
4016 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4017 // which requires some of its traits to have the complete type. However,
4018 // the completeness of the type cannot impact these traits' semantics, and
4019 // so they don't require it. This matches the comments on these traits in
4020 // Table 49.
4021 case UTT_IsConst:
4022 case UTT_IsVolatile:
4023 case UTT_IsSigned:
4024 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004025
4026 // This type trait always returns false, checking the type is moot.
4027 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004028 return true;
4029
David Majnemer213bea32015-11-16 06:58:51 +00004030 // C++14 [meta.unary.prop]:
4031 // If T is a non-union class type, T shall be a complete type.
4032 case UTT_IsEmpty:
4033 case UTT_IsPolymorphic:
4034 case UTT_IsAbstract:
4035 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4036 if (!RD->isUnion())
4037 return !S.RequireCompleteType(
4038 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4039 return true;
4040
4041 // C++14 [meta.unary.prop]:
4042 // If T is a class type, T shall be a complete type.
4043 case UTT_IsFinal:
4044 case UTT_IsSealed:
4045 if (ArgTy->getAsCXXRecordDecl())
4046 return !S.RequireCompleteType(
4047 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4048 return true;
4049
4050 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
4051 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004052 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004053 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004054 case UTT_IsStandardLayout:
4055 case UTT_IsPOD:
4056 case UTT_IsLiteral:
David Majnemer213bea32015-11-16 06:58:51 +00004057
Alp Toker73287bf2014-01-20 00:24:09 +00004058 case UTT_IsDestructible:
4059 case UTT_IsNothrowDestructible:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004060 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004061
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004062 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00004063 // [meta.unary.prop] despite not being named the same. They are specified
4064 // by both GCC and the Embarcadero C++ compiler, and require the complete
4065 // type due to the overarching C++0x type predicates being implemented
4066 // requiring the complete type.
4067 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004068 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004069 case UTT_HasNothrowConstructor:
4070 case UTT_HasNothrowCopy:
4071 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004072 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004073 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004074 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004075 case UTT_HasTrivialCopy:
4076 case UTT_HasTrivialDestructor:
4077 case UTT_HasVirtualDestructor:
4078 // Arrays of unknown bound are expressly allowed.
4079 QualType ElTy = ArgTy;
4080 if (ArgTy->isIncompleteArrayType())
4081 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
4082
4083 // The void type is expressly allowed.
4084 if (ElTy->isVoidType())
4085 return true;
4086
4087 return !S.RequireCompleteType(
4088 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004089 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004090}
4091
Joao Matosc9523d42013-03-27 01:34:16 +00004092static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4093 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004094 bool (CXXRecordDecl::*HasTrivial)() const,
4095 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004096 bool (CXXMethodDecl::*IsDesiredOp)() const)
4097{
4098 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4099 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4100 return true;
4101
4102 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4103 DeclarationNameInfo NameInfo(Name, KeyLoc);
4104 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4105 if (Self.LookupQualifiedName(Res, RD)) {
4106 bool FoundOperator = false;
4107 Res.suppressDiagnostics();
4108 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4109 Op != OpEnd; ++Op) {
4110 if (isa<FunctionTemplateDecl>(*Op))
4111 continue;
4112
4113 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4114 if((Operator->*IsDesiredOp)()) {
4115 FoundOperator = true;
4116 const FunctionProtoType *CPT =
4117 Operator->getType()->getAs<FunctionProtoType>();
4118 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Alp Toker73287bf2014-01-20 00:24:09 +00004119 if (!CPT || !CPT->isNothrow(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004120 return false;
4121 }
4122 }
4123 return FoundOperator;
4124 }
4125 return false;
4126}
4127
Alp Toker95e7ff22014-01-01 05:57:51 +00004128static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004129 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004130 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004131
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004132 ASTContext &C = Self.Context;
4133 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004134 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004135 // Type trait expressions corresponding to the primary type category
4136 // predicates in C++0x [meta.unary.cat].
4137 case UTT_IsVoid:
4138 return T->isVoidType();
4139 case UTT_IsIntegral:
4140 return T->isIntegralType(C);
4141 case UTT_IsFloatingPoint:
4142 return T->isFloatingType();
4143 case UTT_IsArray:
4144 return T->isArrayType();
4145 case UTT_IsPointer:
4146 return T->isPointerType();
4147 case UTT_IsLvalueReference:
4148 return T->isLValueReferenceType();
4149 case UTT_IsRvalueReference:
4150 return T->isRValueReferenceType();
4151 case UTT_IsMemberFunctionPointer:
4152 return T->isMemberFunctionPointerType();
4153 case UTT_IsMemberObjectPointer:
4154 return T->isMemberDataPointerType();
4155 case UTT_IsEnum:
4156 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004157 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004158 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004159 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004160 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004161 case UTT_IsFunction:
4162 return T->isFunctionType();
4163
4164 // Type trait expressions which correspond to the convenient composition
4165 // predicates in C++0x [meta.unary.comp].
4166 case UTT_IsReference:
4167 return T->isReferenceType();
4168 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004169 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004170 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004171 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004172 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004173 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004174 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004175 // Note: semantic analysis depends on Objective-C lifetime types to be
4176 // considered scalar types. However, such types do not actually behave
4177 // like scalar types at run time (since they may require retain/release
4178 // operations), so we report them as non-scalar.
4179 if (T->isObjCLifetimeType()) {
4180 switch (T.getObjCLifetime()) {
4181 case Qualifiers::OCL_None:
4182 case Qualifiers::OCL_ExplicitNone:
4183 return true;
4184
4185 case Qualifiers::OCL_Strong:
4186 case Qualifiers::OCL_Weak:
4187 case Qualifiers::OCL_Autoreleasing:
4188 return false;
4189 }
4190 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004191
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004192 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004193 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004194 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004195 case UTT_IsMemberPointer:
4196 return T->isMemberPointerType();
4197
4198 // Type trait expressions which correspond to the type property predicates
4199 // in C++0x [meta.unary.prop].
4200 case UTT_IsConst:
4201 return T.isConstQualified();
4202 case UTT_IsVolatile:
4203 return T.isVolatileQualified();
4204 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004205 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004206 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004207 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004208 case UTT_IsStandardLayout:
4209 return T->isStandardLayoutType();
4210 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004211 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004212 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004213 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004214 case UTT_IsEmpty:
4215 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4216 return !RD->isUnion() && RD->isEmpty();
4217 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004218 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004219 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004220 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004221 return false;
4222 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004223 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004224 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004225 return false;
David Majnemer213bea32015-11-16 06:58:51 +00004226 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4227 // even then only when it is used with the 'interface struct ...' syntax
4228 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004229 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004230 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004231 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004232 case UTT_IsSealed:
4233 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004234 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004235 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004236 case UTT_IsSigned:
4237 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004238 case UTT_IsUnsigned:
4239 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004240
4241 // Type trait expressions which query classes regarding their construction,
4242 // destruction, and copying. Rather than being based directly on the
4243 // related type predicates in the standard, they are specified by both
4244 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4245 // specifications.
4246 //
4247 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4248 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004249 //
4250 // Note that these builtins do not behave as documented in g++: if a class
4251 // has both a trivial and a non-trivial special member of a particular kind,
4252 // they return false! For now, we emulate this behavior.
4253 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4254 // does not correctly compute triviality in the presence of multiple special
4255 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004256 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004257 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4258 // If __is_pod (type) is true then the trait is true, else if type is
4259 // a cv class or union type (or array thereof) with a trivial default
4260 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004261 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004262 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004263 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4264 return RD->hasTrivialDefaultConstructor() &&
4265 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004266 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004267 case UTT_HasTrivialMoveConstructor:
4268 // This trait is implemented by MSVC 2012 and needed to parse the
4269 // standard library headers. Specifically this is used as the logic
4270 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004271 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004272 return true;
4273 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4274 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4275 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004276 case UTT_HasTrivialCopy:
4277 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4278 // If __is_pod (type) is true or type is a reference type then
4279 // the trait is true, else if type is a cv class or union type
4280 // with a trivial copy constructor ([class.copy]) then the trait
4281 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004282 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004283 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004284 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4285 return RD->hasTrivialCopyConstructor() &&
4286 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004287 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004288 case UTT_HasTrivialMoveAssign:
4289 // This trait is implemented by MSVC 2012 and needed to parse the
4290 // standard library headers. Specifically it is used as the logic
4291 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004292 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004293 return true;
4294 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4295 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4296 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004297 case UTT_HasTrivialAssign:
4298 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4299 // If type is const qualified or is a reference type then the
4300 // trait is false. Otherwise if __is_pod (type) is true then the
4301 // trait is true, else if type is a cv class or union type with
4302 // a trivial copy assignment ([class.copy]) then the trait is
4303 // true, else it is false.
4304 // Note: the const and reference restrictions are interesting,
4305 // given that const and reference members don't prevent a class
4306 // from having a trivial copy assignment operator (but do cause
4307 // errors if the copy assignment operator is actually used, q.v.
4308 // [class.copy]p12).
4309
Richard Smith92f241f2012-12-08 02:53:02 +00004310 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004311 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004312 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004313 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004314 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4315 return RD->hasTrivialCopyAssignment() &&
4316 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004317 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004318 case UTT_IsDestructible:
4319 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004320 // C++14 [meta.unary.prop]:
4321 // For reference types, is_destructible<T>::value is true.
4322 if (T->isReferenceType())
4323 return true;
4324
4325 // Objective-C++ ARC: autorelease types don't require destruction.
4326 if (T->isObjCLifetimeType() &&
4327 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4328 return true;
4329
4330 // C++14 [meta.unary.prop]:
4331 // For incomplete types and function types, is_destructible<T>::value is
4332 // false.
4333 if (T->isIncompleteType() || T->isFunctionType())
4334 return false;
4335
4336 // C++14 [meta.unary.prop]:
4337 // For object types and given U equal to remove_all_extents_t<T>, if the
4338 // expression std::declval<U&>().~U() is well-formed when treated as an
4339 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4340 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4341 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4342 if (!Destructor)
4343 return false;
4344 // C++14 [dcl.fct.def.delete]p2:
4345 // A program that refers to a deleted function implicitly or
4346 // explicitly, other than to declare it, is ill-formed.
4347 if (Destructor->isDeleted())
4348 return false;
4349 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4350 return false;
4351 if (UTT == UTT_IsNothrowDestructible) {
4352 const FunctionProtoType *CPT =
4353 Destructor->getType()->getAs<FunctionProtoType>();
4354 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4355 if (!CPT || !CPT->isNothrow(C))
4356 return false;
4357 }
4358 }
4359 return true;
4360
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004361 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004362 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004363 // If __is_pod (type) is true or type is a reference type
4364 // then the trait is true, else if type is a cv class or union
4365 // type (or array thereof) with a trivial destructor
4366 // ([class.dtor]) then the trait is true, else it is
4367 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004368 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004369 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004370
John McCall31168b02011-06-15 23:02:42 +00004371 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004372 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004373 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4374 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004375
Richard Smith92f241f2012-12-08 02:53:02 +00004376 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4377 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004378 return false;
4379 // TODO: Propagate nothrowness for implicitly declared special members.
4380 case UTT_HasNothrowAssign:
4381 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4382 // If type is const qualified or is a reference type then the
4383 // trait is false. Otherwise if __has_trivial_assign (type)
4384 // is true then the trait is true, else if type is a cv class
4385 // or union type with copy assignment operators that are known
4386 // not to throw an exception then the trait is true, else it is
4387 // false.
4388 if (C.getBaseElementType(T).isConstQualified())
4389 return false;
4390 if (T->isReferenceType())
4391 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004392 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004393 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004394
Joao Matosc9523d42013-03-27 01:34:16 +00004395 if (const RecordType *RT = T->getAs<RecordType>())
4396 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4397 &CXXRecordDecl::hasTrivialCopyAssignment,
4398 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4399 &CXXMethodDecl::isCopyAssignmentOperator);
4400 return false;
4401 case UTT_HasNothrowMoveAssign:
4402 // This trait is implemented by MSVC 2012 and needed to parse the
4403 // standard library headers. Specifically this is used as the logic
4404 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004405 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004406 return true;
4407
4408 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4409 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4410 &CXXRecordDecl::hasTrivialMoveAssignment,
4411 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4412 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004413 return false;
4414 case UTT_HasNothrowCopy:
4415 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4416 // If __has_trivial_copy (type) is true then the trait is true, else
4417 // if type is a cv class or union type with copy constructors that are
4418 // known not to throw an exception then the trait is true, else it is
4419 // false.
John McCall31168b02011-06-15 23:02:42 +00004420 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004421 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004422 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4423 if (RD->hasTrivialCopyConstructor() &&
4424 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004425 return true;
4426
4427 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004428 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004429 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004430 // A template constructor is never a copy constructor.
4431 // FIXME: However, it may actually be selected at the actual overload
4432 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004433 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004434 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004435 // UsingDecl itself is not a constructor
4436 if (isa<UsingDecl>(ND))
4437 continue;
4438 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004439 if (Constructor->isCopyConstructor(FoundTQs)) {
4440 FoundConstructor = true;
4441 const FunctionProtoType *CPT
4442 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004443 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4444 if (!CPT)
4445 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004446 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004447 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004448 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004449 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004450 }
4451 }
4452
Richard Smith938f40b2011-06-11 17:19:42 +00004453 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004454 }
4455 return false;
4456 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004457 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004458 // If __has_trivial_constructor (type) is true then the trait is
4459 // true, else if type is a cv class or union type (or array
4460 // thereof) with a default constructor that is known not to
4461 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004462 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004463 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004464 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4465 if (RD->hasTrivialDefaultConstructor() &&
4466 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004467 return true;
4468
Alp Tokerb4bca412014-01-20 00:23:47 +00004469 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004470 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004471 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004472 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004473 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004474 // UsingDecl itself is not a constructor
4475 if (isa<UsingDecl>(ND))
4476 continue;
4477 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004478 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004479 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004480 const FunctionProtoType *CPT
4481 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004482 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4483 if (!CPT)
4484 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004485 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004486 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004487 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004488 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004489 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004490 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004491 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004492 }
4493 return false;
4494 case UTT_HasVirtualDestructor:
4495 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4496 // If type is a class type with a virtual destructor ([class.dtor])
4497 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004498 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004499 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004500 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004501 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004502
4503 // These type trait expressions are modeled on the specifications for the
4504 // Embarcadero C++0x type trait functions:
4505 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4506 case UTT_IsCompleteType:
4507 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4508 // Returns True if and only if T is a complete type at the point of the
4509 // function call.
4510 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004511 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004512}
Sebastian Redl5822f082009-02-07 20:10:22 +00004513
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004514/// \brief Determine whether T has a non-trivial Objective-C lifetime in
4515/// ARC mode.
4516static bool hasNontrivialObjCLifetime(QualType T) {
4517 switch (T.getObjCLifetime()) {
4518 case Qualifiers::OCL_ExplicitNone:
4519 return false;
4520
4521 case Qualifiers::OCL_Strong:
4522 case Qualifiers::OCL_Weak:
4523 case Qualifiers::OCL_Autoreleasing:
4524 return true;
4525
4526 case Qualifiers::OCL_None:
4527 return T->isObjCLifetimeType();
4528 }
4529
4530 llvm_unreachable("Unknown ObjC lifetime qualifier");
4531}
4532
Alp Tokercbb90342013-12-13 20:49:58 +00004533static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4534 QualType RhsT, SourceLocation KeyLoc);
4535
Douglas Gregor29c42f22012-02-24 07:38:34 +00004536static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4537 ArrayRef<TypeSourceInfo *> Args,
4538 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004539 if (Kind <= UTT_Last)
4540 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4541
Alp Tokercbb90342013-12-13 20:49:58 +00004542 if (Kind <= BTT_Last)
4543 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4544 Args[1]->getType(), RParenLoc);
4545
Douglas Gregor29c42f22012-02-24 07:38:34 +00004546 switch (Kind) {
Alp Toker73287bf2014-01-20 00:24:09 +00004547 case clang::TT_IsConstructible:
4548 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004549 case clang::TT_IsTriviallyConstructible: {
4550 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004551 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004552 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004553 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004554 // definition for is_constructible, as defined below, is known to call
4555 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004556 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004557 // The predicate condition for a template specialization
4558 // is_constructible<T, Args...> shall be satisfied if and only if the
4559 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004560 // variable t:
4561 //
4562 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004563 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004564
4565 // Precondition: T and all types in the parameter pack Args shall be
4566 // complete types, (possibly cv-qualified) void, or arrays of
4567 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004568 for (const auto *TSI : Args) {
4569 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004570 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004571 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004572
Simon Pilgrim75c26882016-09-30 14:25:09 +00004573 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004574 diag::err_incomplete_type_used_in_type_trait_expr))
4575 return false;
4576 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004577
David Majnemer9658ecc2015-11-13 05:32:43 +00004578 // Make sure the first argument is not incomplete nor a function type.
4579 QualType T = Args[0]->getType();
4580 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004581 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004582
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004583 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004584 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004585 if (RD && RD->isAbstract())
4586 return false;
4587
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004588 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4589 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004590 ArgExprs.reserve(Args.size() - 1);
4591 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004592 QualType ArgTy = Args[I]->getType();
4593 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4594 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004595 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004596 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4597 ArgTy.getNonLValueExprType(S.Context),
4598 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004599 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004600 for (Expr &E : OpaqueArgExprs)
4601 ArgExprs.push_back(&E);
4602
Simon Pilgrim75c26882016-09-30 14:25:09 +00004603 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004604 // trap at translation unit scope.
4605 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
4606 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4607 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4608 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4609 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4610 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004611 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004612 if (Init.Failed())
4613 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004614
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004615 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004616 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4617 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004618
Alp Toker73287bf2014-01-20 00:24:09 +00004619 if (Kind == clang::TT_IsConstructible)
4620 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004621
Alp Toker73287bf2014-01-20 00:24:09 +00004622 if (Kind == clang::TT_IsNothrowConstructible)
4623 return S.canThrow(Result.get()) == CT_Cannot;
4624
4625 if (Kind == clang::TT_IsTriviallyConstructible) {
4626 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4627 // lifetime, this is a non-trivial construction.
4628 if (S.getLangOpts().ObjCAutoRefCount &&
David Majnemer9658ecc2015-11-13 05:32:43 +00004629 hasNontrivialObjCLifetime(T.getNonReferenceType()))
Alp Toker73287bf2014-01-20 00:24:09 +00004630 return false;
4631
4632 // The initialization succeeded; now make sure there are no non-trivial
4633 // calls.
4634 return !Result.get()->hasNonTrivialCall(S.Context);
4635 }
4636
4637 llvm_unreachable("unhandled type trait");
4638 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004639 }
Alp Tokercbb90342013-12-13 20:49:58 +00004640 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004641 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004642
Douglas Gregor29c42f22012-02-24 07:38:34 +00004643 return false;
4644}
4645
Simon Pilgrim75c26882016-09-30 14:25:09 +00004646ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4647 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004648 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004649 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004650
Alp Toker95e7ff22014-01-01 05:57:51 +00004651 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4652 *this, Kind, KWLoc, Args[0]->getType()))
4653 return ExprError();
4654
Douglas Gregor29c42f22012-02-24 07:38:34 +00004655 bool Dependent = false;
4656 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4657 if (Args[I]->getType()->isDependentType()) {
4658 Dependent = true;
4659 break;
4660 }
4661 }
Alp Tokercbb90342013-12-13 20:49:58 +00004662
4663 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004664 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004665 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4666
4667 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4668 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004669}
4670
Alp Toker88f64e62013-12-13 21:19:30 +00004671ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4672 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004673 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004674 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004675 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00004676
Douglas Gregor29c42f22012-02-24 07:38:34 +00004677 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4678 TypeSourceInfo *TInfo;
4679 QualType T = GetTypeFromParser(Args[I], &TInfo);
4680 if (!TInfo)
4681 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004682
4683 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004684 }
Alp Tokercbb90342013-12-13 20:49:58 +00004685
Douglas Gregor29c42f22012-02-24 07:38:34 +00004686 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4687}
4688
Alp Tokercbb90342013-12-13 20:49:58 +00004689static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4690 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004691 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4692 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004693
4694 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004695 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004696 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004697 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004698 // Base and Derived are not unions and name the same class type without
4699 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004700
John McCall388ef532011-01-28 22:02:36 +00004701 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4702 if (!lhsRecord) return false;
4703
4704 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4705 if (!rhsRecord) return false;
4706
4707 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4708 == (lhsRecord == rhsRecord));
4709
4710 if (lhsRecord == rhsRecord)
4711 return !lhsRecord->getDecl()->isUnion();
4712
4713 // C++0x [meta.rel]p2:
4714 // If Base and Derived are class types and are different types
4715 // (ignoring possible cv-qualifiers) then Derived shall be a
4716 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004717 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00004718 diag::err_incomplete_type_used_in_type_trait_expr))
4719 return false;
4720
4721 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4722 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4723 }
John Wiegley65497cc2011-04-27 23:09:49 +00004724 case BTT_IsSame:
4725 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00004726 case BTT_TypeCompatible:
4727 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4728 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00004729 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00004730 case BTT_IsConvertibleTo: {
4731 // C++0x [meta.rel]p4:
4732 // Given the following function prototype:
4733 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004734 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00004735 // typename add_rvalue_reference<T>::type create();
4736 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004737 // the predicate condition for a template specialization
4738 // is_convertible<From, To> shall be satisfied if and only if
4739 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00004740 // well-formed, including any implicit conversions to the return
4741 // type of the function:
4742 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004743 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00004744 // return create<From>();
4745 // }
4746 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004747 // Access checking is performed as if in a context unrelated to To and
4748 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00004749 // of the return-statement (including conversions to the return type)
4750 // is considered.
4751 //
4752 // We model the initialization as a copy-initialization of a temporary
4753 // of the appropriate type, which for this expression is identical to the
4754 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004755
4756 // Functions aren't allowed to return function or array types.
4757 if (RhsT->isFunctionType() || RhsT->isArrayType())
4758 return false;
4759
4760 // A return statement in a void function must have void type.
4761 if (RhsT->isVoidType())
4762 return LhsT->isVoidType();
4763
4764 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00004765 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004766 return false;
4767
4768 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00004769 if (LhsT->isObjectType() || LhsT->isFunctionType())
4770 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004771
4772 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00004773 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00004774 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00004775 Expr::getValueKindForType(LhsT));
4776 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004777 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00004778 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004779
4780 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00004781 // trap at translation unit scope.
4782 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00004783 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4784 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004785 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004786 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00004787 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00004788
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004789 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00004790 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4791 }
Alp Toker73287bf2014-01-20 00:24:09 +00004792
David Majnemerb3d96882016-05-23 17:21:55 +00004793 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00004794 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00004795 case BTT_IsTriviallyAssignable: {
4796 // C++11 [meta.unary.prop]p3:
4797 // is_trivially_assignable is defined as:
4798 // is_assignable<T, U>::value is true and the assignment, as defined by
4799 // is_assignable, is known to call no operation that is not trivial
4800 //
4801 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004802 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00004803 // treated as an unevaluated operand (Clause 5).
4804 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004805 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00004806 // void, or arrays of unknown bound.
4807 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004808 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004809 diag::err_incomplete_type_used_in_type_trait_expr))
4810 return false;
4811 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004812 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004813 diag::err_incomplete_type_used_in_type_trait_expr))
4814 return false;
4815
4816 // cv void is never assignable.
4817 if (LhsT->isVoidType() || RhsT->isVoidType())
4818 return false;
4819
Simon Pilgrim75c26882016-09-30 14:25:09 +00004820 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00004821 // declval<U>().
4822 if (LhsT->isObjectType() || LhsT->isFunctionType())
4823 LhsT = Self.Context.getRValueReferenceType(LhsT);
4824 if (RhsT->isObjectType() || RhsT->isFunctionType())
4825 RhsT = Self.Context.getRValueReferenceType(RhsT);
4826 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4827 Expr::getValueKindForType(LhsT));
4828 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4829 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004830
4831 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00004832 // trap at translation unit scope.
4833 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
4834 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4835 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004836 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4837 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004838 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4839 return false;
4840
David Majnemerb3d96882016-05-23 17:21:55 +00004841 if (BTT == BTT_IsAssignable)
4842 return true;
4843
Alp Toker73287bf2014-01-20 00:24:09 +00004844 if (BTT == BTT_IsNothrowAssignable)
4845 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004846
Alp Toker73287bf2014-01-20 00:24:09 +00004847 if (BTT == BTT_IsTriviallyAssignable) {
4848 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4849 // lifetime, this is a non-trivial assignment.
4850 if (Self.getLangOpts().ObjCAutoRefCount &&
4851 hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
4852 return false;
4853
4854 return !Result.get()->hasNonTrivialCall(Self.Context);
4855 }
4856
4857 llvm_unreachable("unhandled type trait");
4858 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00004859 }
Alp Tokercbb90342013-12-13 20:49:58 +00004860 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004861 }
4862 llvm_unreachable("Unknown type trait or not implemented");
4863}
4864
John Wiegley6242b6a2011-04-28 00:16:57 +00004865ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4866 SourceLocation KWLoc,
4867 ParsedType Ty,
4868 Expr* DimExpr,
4869 SourceLocation RParen) {
4870 TypeSourceInfo *TSInfo;
4871 QualType T = GetTypeFromParser(Ty, &TSInfo);
4872 if (!TSInfo)
4873 TSInfo = Context.getTrivialTypeSourceInfo(T);
4874
4875 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4876}
4877
4878static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4879 QualType T, Expr *DimExpr,
4880 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004881 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00004882
4883 switch(ATT) {
4884 case ATT_ArrayRank:
4885 if (T->isArrayType()) {
4886 unsigned Dim = 0;
4887 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4888 ++Dim;
4889 T = AT->getElementType();
4890 }
4891 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00004892 }
John Wiegleyd3522222011-04-28 02:06:46 +00004893 return 0;
4894
John Wiegley6242b6a2011-04-28 00:16:57 +00004895 case ATT_ArrayExtent: {
4896 llvm::APSInt Value;
4897 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00004898 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00004899 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00004900 false).isInvalid())
4901 return 0;
4902 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00004903 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4904 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00004905 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00004906 }
Richard Smithf4c51d92012-02-04 09:53:13 +00004907 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00004908
4909 if (T->isArrayType()) {
4910 unsigned D = 0;
4911 bool Matched = false;
4912 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4913 if (Dim == D) {
4914 Matched = true;
4915 break;
4916 }
4917 ++D;
4918 T = AT->getElementType();
4919 }
4920
John Wiegleyd3522222011-04-28 02:06:46 +00004921 if (Matched && T->isArrayType()) {
4922 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4923 return CAT->getSize().getLimitedValue();
4924 }
John Wiegley6242b6a2011-04-28 00:16:57 +00004925 }
John Wiegleyd3522222011-04-28 02:06:46 +00004926 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00004927 }
4928 }
4929 llvm_unreachable("Unknown type trait or not implemented");
4930}
4931
4932ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4933 SourceLocation KWLoc,
4934 TypeSourceInfo *TSInfo,
4935 Expr* DimExpr,
4936 SourceLocation RParen) {
4937 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00004938
Chandler Carruthc5276e52011-05-01 08:48:21 +00004939 // FIXME: This should likely be tracked as an APInt to remove any host
4940 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004941 uint64_t Value = 0;
4942 if (!T->isDependentType())
4943 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4944
Chandler Carruthc5276e52011-05-01 08:48:21 +00004945 // While the specification for these traits from the Embarcadero C++
4946 // compiler's documentation says the return type is 'unsigned int', Clang
4947 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4948 // compiler, there is no difference. On several other platforms this is an
4949 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004950 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4951 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00004952}
4953
John Wiegleyf9f65842011-04-25 06:54:41 +00004954ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004955 SourceLocation KWLoc,
4956 Expr *Queried,
4957 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004958 // If error parsing the expression, ignore.
4959 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004960 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00004961
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004962 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004963
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004964 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00004965}
4966
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004967static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4968 switch (ET) {
4969 case ET_IsLValueExpr: return E->isLValue();
4970 case ET_IsRValueExpr: return E->isRValue();
4971 }
4972 llvm_unreachable("Expression trait not covered by switch");
4973}
4974
John Wiegleyf9f65842011-04-25 06:54:41 +00004975ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004976 SourceLocation KWLoc,
4977 Expr *Queried,
4978 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004979 if (Queried->isTypeDependent()) {
4980 // Delay type-checking for type-dependent expressions.
4981 } else if (Queried->getType()->isPlaceholderType()) {
4982 ExprResult PE = CheckPlaceholderExpr(Queried);
4983 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004984 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004985 }
4986
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004987 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00004988
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004989 return new (Context)
4990 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00004991}
4992
Richard Trieu82402a02011-09-15 21:56:47 +00004993QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004994 ExprValueKind &VK,
4995 SourceLocation Loc,
4996 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004997 assert(!LHS.get()->getType()->isPlaceholderType() &&
4998 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00004999 "placeholders should have been weeded out by now");
5000
Richard Smith4baaa5a2016-12-03 01:14:32 +00005001 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5002 // temporary materialization conversion otherwise.
5003 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005004 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005005 else if (LHS.get()->isRValue())
5006 LHS = TemporaryMaterializationConversion(LHS.get());
5007 if (LHS.isInvalid())
5008 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005009
5010 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005011 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005012 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005013
Sebastian Redl5822f082009-02-07 20:10:22 +00005014 const char *OpSpelling = isIndirect ? "->*" : ".*";
5015 // C++ 5.5p2
5016 // The binary operator .* [p3: ->*] binds its second operand, which shall
5017 // be of type "pointer to member of T" (where T is a completely-defined
5018 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005019 QualType RHSType = RHS.get()->getType();
5020 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005021 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005022 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005023 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005024 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005025 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005026
Sebastian Redl5822f082009-02-07 20:10:22 +00005027 QualType Class(MemPtr->getClass(), 0);
5028
Douglas Gregord07ba342010-10-13 20:41:14 +00005029 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5030 // member pointer points must be completely-defined. However, there is no
5031 // reason for this semantic distinction, and the rule is not enforced by
5032 // other compilers. Therefore, we do not check this property, as it is
5033 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005034
Sebastian Redl5822f082009-02-07 20:10:22 +00005035 // C++ 5.5p2
5036 // [...] to its first operand, which shall be of class T or of a class of
5037 // which T is an unambiguous and accessible base class. [p3: a pointer to
5038 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005039 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005040 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005041 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5042 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005043 else {
5044 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005045 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005046 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005047 return QualType();
5048 }
5049 }
5050
Richard Trieu82402a02011-09-15 21:56:47 +00005051 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005052 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005053 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5054 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005055 return QualType();
5056 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005057
Richard Smith0f59cb32015-12-18 21:45:41 +00005058 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005059 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005060 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005061 return QualType();
5062 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005063
5064 CXXCastPath BasePath;
5065 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5066 SourceRange(LHS.get()->getLocStart(),
5067 RHS.get()->getLocEnd()),
5068 &BasePath))
5069 return QualType();
5070
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005071 // Cast LHS to type of use.
5072 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005073 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005074 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005075 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005076 }
5077
Richard Trieu82402a02011-09-15 21:56:47 +00005078 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005079 // Diagnose use of pointer-to-member type which when used as
5080 // the functional cast in a pointer-to-member expression.
5081 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5082 return QualType();
5083 }
John McCall7decc9e2010-11-18 06:31:45 +00005084
Sebastian Redl5822f082009-02-07 20:10:22 +00005085 // C++ 5.5p2
5086 // The result is an object or a function of the type specified by the
5087 // second operand.
5088 // The cv qualifiers are the union of those in the pointer and the left side,
5089 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005090 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005091 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005092
Douglas Gregor1d042092011-01-26 16:40:18 +00005093 // C++0x [expr.mptr.oper]p6:
5094 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005095 // ill-formed if the second operand is a pointer to member function with
5096 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5097 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005098 // is a pointer to member function with ref-qualifier &&.
5099 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5100 switch (Proto->getRefQualifier()) {
5101 case RQ_None:
5102 // Do nothing
5103 break;
5104
5105 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005106 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005107 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005108 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005109 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005110
Douglas Gregor1d042092011-01-26 16:40:18 +00005111 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005112 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005113 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005114 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005115 break;
5116 }
5117 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005118
John McCall7decc9e2010-11-18 06:31:45 +00005119 // C++ [expr.mptr.oper]p6:
5120 // The result of a .* expression whose second operand is a pointer
5121 // to a data member is of the same value category as its
5122 // first operand. The result of a .* expression whose second
5123 // operand is a pointer to a member function is a prvalue. The
5124 // result of an ->* expression is an lvalue if its second operand
5125 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005126 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005127 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005128 return Context.BoundMemberTy;
5129 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005130 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005131 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005132 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005133 }
John McCall7decc9e2010-11-18 06:31:45 +00005134
Sebastian Redl5822f082009-02-07 20:10:22 +00005135 return Result;
5136}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005137
Richard Smith2414bca2016-04-25 19:30:37 +00005138/// \brief Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005139///
5140/// This is part of the parameter validation for the ? operator. If either
5141/// value operand is a class type, the two operands are attempted to be
5142/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005143/// It returns true if the program is ill-formed and has already been diagnosed
5144/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005145static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5146 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005147 bool &HaveConversion,
5148 QualType &ToType) {
5149 HaveConversion = false;
5150 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005151
5152 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005153 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005154 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005155 // The process for determining whether an operand expression E1 of type T1
5156 // can be converted to match an operand expression E2 of type T2 is defined
5157 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005158 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5159 // implicitly converted to type "lvalue reference to T2", subject to the
5160 // constraint that in the conversion the reference must bind directly to
5161 // an lvalue.
5162 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5163 // implicitly conveted to the type "rvalue reference to R2", subject to
5164 // the constraint that the reference must bind directly.
5165 if (To->isLValue() || To->isXValue()) {
5166 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5167 : Self.Context.getRValueReferenceType(ToType);
5168
Douglas Gregor838fcc32010-03-26 20:14:36 +00005169 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005170
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005171 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005172 if (InitSeq.isDirectReferenceBinding()) {
5173 ToType = T;
5174 HaveConversion = true;
5175 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005176 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005177
Douglas Gregor838fcc32010-03-26 20:14:36 +00005178 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005179 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005180 }
John McCall65eb8792010-02-25 01:37:24 +00005181
Sebastian Redl1a99f442009-04-16 17:51:27 +00005182 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5183 // -- if E1 and E2 have class type, and the underlying class types are
5184 // the same or one is a base class of the other:
5185 QualType FTy = From->getType();
5186 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005187 const RecordType *FRec = FTy->getAs<RecordType>();
5188 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005189 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005190 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5191 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5192 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005193 // E1 can be converted to match E2 if the class of T2 is the
5194 // same type as, or a base class of, the class of T1, and
5195 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005196 if (FRec == TRec || FDerivedFromT) {
5197 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005198 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005199 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005200 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005201 HaveConversion = true;
5202 return false;
5203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005204
Douglas Gregor838fcc32010-03-26 20:14:36 +00005205 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005206 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005207 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005208 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005209
Douglas Gregor838fcc32010-03-26 20:14:36 +00005210 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005211 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005212
Douglas Gregor838fcc32010-03-26 20:14:36 +00005213 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5214 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005215 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005216 // an rvalue).
5217 //
5218 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5219 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005220 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005221
Douglas Gregor838fcc32010-03-26 20:14:36 +00005222 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005223 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005224 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005225 ToType = TTy;
5226 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005227 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005228
Sebastian Redl1a99f442009-04-16 17:51:27 +00005229 return false;
5230}
5231
5232/// \brief Try to find a common type for two according to C++0x 5.16p5.
5233///
5234/// This is part of the parameter validation for the ? operator. If either
5235/// value operand is a class type, overload resolution is used to find a
5236/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005237static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005238 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005239 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005240 OverloadCandidateSet CandidateSet(QuestionLoc,
5241 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005242 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005243 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005244
5245 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005246 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005247 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005248 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00005249 ExprResult LHSRes =
5250 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
5251 Best->Conversions[0], Sema::AA_Converting);
5252 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005253 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005254 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005255
5256 ExprResult RHSRes =
5257 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
5258 Best->Conversions[1], Sema::AA_Converting);
5259 if (RHSRes.isInvalid())
5260 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005261 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005262 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005263 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005264 return false;
John Wiegley01296292011-04-08 18:41:53 +00005265 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005266
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005267 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005268
5269 // Emit a better diagnostic if one of the expressions is a null pointer
5270 // constant and the other is a pointer type. In this case, the user most
5271 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005272 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005273 return true;
5274
5275 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005276 << LHS.get()->getType() << RHS.get()->getType()
5277 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005278 return true;
5279
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005280 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005281 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005282 << LHS.get()->getType() << RHS.get()->getType()
5283 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005284 // FIXME: Print the possible common types by printing the return types of
5285 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005286 break;
5287
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005288 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005289 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005290 }
5291 return true;
5292}
5293
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005294/// \brief Perform an "extended" implicit conversion as returned by
5295/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005296static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005297 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005298 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005299 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005300 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005301 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005302 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005303 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005304 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005305
John Wiegley01296292011-04-08 18:41:53 +00005306 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005307 return false;
5308}
5309
Sebastian Redl1a99f442009-04-16 17:51:27 +00005310/// \brief Check the operands of ?: under C++ semantics.
5311///
5312/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5313/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005314QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5315 ExprResult &RHS, ExprValueKind &VK,
5316 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005317 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005318 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5319 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005320
Richard Smith45edb702012-08-07 22:06:48 +00005321 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005322 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00005323 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005324 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005325 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005326 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005327 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005328 }
5329
John McCall7decc9e2010-11-18 06:31:45 +00005330 // Assume r-value.
5331 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005332 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005333
Sebastian Redl1a99f442009-04-16 17:51:27 +00005334 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005335 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005336 return Context.DependentTy;
5337
Richard Smith45edb702012-08-07 22:06:48 +00005338 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005339 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005340 QualType LTy = LHS.get()->getType();
5341 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005342 bool LVoid = LTy->isVoidType();
5343 bool RVoid = RTy->isVoidType();
5344 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005345 // ... one of the following shall hold:
5346 // -- The second or the third operand (but not both) is a (possibly
5347 // parenthesized) throw-expression; the result is of the type
5348 // and value category of the other.
5349 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5350 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5351 if (LThrow != RThrow) {
5352 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5353 VK = NonThrow->getValueKind();
5354 // DR (no number yet): the result is a bit-field if the
5355 // non-throw-expression operand is a bit-field.
5356 OK = NonThrow->getObjectKind();
5357 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005358 }
5359
Sebastian Redl1a99f442009-04-16 17:51:27 +00005360 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005361 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005362 if (LVoid && RVoid)
5363 return Context.VoidTy;
5364
5365 // Neither holds, error.
5366 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5367 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005368 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005369 return QualType();
5370 }
5371
5372 // Neither is void.
5373
Richard Smithf2b084f2012-08-08 06:13:49 +00005374 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005375 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005376 // either has (cv) class type [...] an attempt is made to convert each of
5377 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005378 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005379 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005380 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005381 QualType L2RType, R2LType;
5382 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005383 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005384 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005385 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005386 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005387
Sebastian Redl1a99f442009-04-16 17:51:27 +00005388 // If both can be converted, [...] the program is ill-formed.
5389 if (HaveL2R && HaveR2L) {
5390 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005391 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005392 return QualType();
5393 }
5394
5395 // If exactly one conversion is possible, that conversion is applied to
5396 // the chosen operand and the converted operands are used in place of the
5397 // original operands for the remainder of this section.
5398 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005399 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005400 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005401 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005402 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005403 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005404 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005405 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005406 }
5407 }
5408
Richard Smithf2b084f2012-08-08 06:13:49 +00005409 // C++11 [expr.cond]p3
5410 // if both are glvalues of the same value category and the same type except
5411 // for cv-qualification, an attempt is made to convert each of those
5412 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005413 // FIXME:
5414 // Resolving a defect in P0012R1: we extend this to cover all cases where
5415 // one of the operands is reference-compatible with the other, in order
5416 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005417 ExprValueKind LVK = LHS.get()->getValueKind();
5418 ExprValueKind RVK = RHS.get()->getValueKind();
5419 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005420 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005421 // DerivedToBase was already handled by the class-specific case above.
5422 // FIXME: Should we allow ObjC conversions here?
5423 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5424 if (CompareReferenceRelationship(
5425 QuestionLoc, LTy, RTy, DerivedToBase,
5426 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005427 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5428 // [...] subject to the constraint that the reference must bind
5429 // directly [...]
5430 !RHS.get()->refersToBitField() &&
5431 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005432 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005433 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005434 } else if (CompareReferenceRelationship(
5435 QuestionLoc, RTy, LTy, DerivedToBase,
5436 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005437 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5438 !LHS.get()->refersToBitField() &&
5439 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005440 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5441 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005442 }
5443 }
5444
5445 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005446 // If the second and third operands are glvalues of the same value
5447 // category and have the same type, the result is of that type and
5448 // value category and it is a bit-field if the second or the third
5449 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005450 // We only extend this to bitfields, not to the crazy other kinds of
5451 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005452 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005453 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005454 LHS.get()->isOrdinaryOrBitFieldObject() &&
5455 RHS.get()->isOrdinaryOrBitFieldObject()) {
5456 VK = LHS.get()->getValueKind();
5457 if (LHS.get()->getObjectKind() == OK_BitField ||
5458 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005459 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005460
5461 // If we have function pointer types, unify them anyway to unify their
5462 // exception specifications, if any.
5463 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5464 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005465 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005466 /*ConvertArgs*/false);
5467 LTy = Context.getQualifiedType(LTy, Qs);
5468
5469 assert(!LTy.isNull() && "failed to find composite pointer type for "
5470 "canonically equivalent function ptr types");
5471 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5472 }
5473
John McCall7decc9e2010-11-18 06:31:45 +00005474 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005475 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005476
Richard Smithf2b084f2012-08-08 06:13:49 +00005477 // C++11 [expr.cond]p5
5478 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005479 // do not have the same type, and either has (cv) class type, ...
5480 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5481 // ... overload resolution is used to determine the conversions (if any)
5482 // to be applied to the operands. If the overload resolution fails, the
5483 // program is ill-formed.
5484 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5485 return QualType();
5486 }
5487
Richard Smithf2b084f2012-08-08 06:13:49 +00005488 // C++11 [expr.cond]p6
5489 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005490 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005491 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5492 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005493 if (LHS.isInvalid() || RHS.isInvalid())
5494 return QualType();
5495 LTy = LHS.get()->getType();
5496 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005497
5498 // After those conversions, one of the following shall hold:
5499 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005500 // is of that type. If the operands have class type, the result
5501 // is a prvalue temporary of the result type, which is
5502 // copy-initialized from either the second operand or the third
5503 // operand depending on the value of the first operand.
5504 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5505 if (LTy->isRecordType()) {
5506 // The operands have class type. Make a temporary copy.
5507 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005508
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005509 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5510 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005511 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005512 if (LHSCopy.isInvalid())
5513 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005514
5515 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5516 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005517 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005518 if (RHSCopy.isInvalid())
5519 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005520
John Wiegley01296292011-04-08 18:41:53 +00005521 LHS = LHSCopy;
5522 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005523 }
5524
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005525 // If we have function pointer types, unify them anyway to unify their
5526 // exception specifications, if any.
5527 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5528 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5529 assert(!LTy.isNull() && "failed to find composite pointer type for "
5530 "canonically equivalent function ptr types");
5531 }
5532
Sebastian Redl1a99f442009-04-16 17:51:27 +00005533 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005534 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005535
Douglas Gregor46188682010-05-18 22:42:18 +00005536 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005537 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005538 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5539 /*AllowBothBool*/true,
5540 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005541
Sebastian Redl1a99f442009-04-16 17:51:27 +00005542 // -- The second and third operands have arithmetic or enumeration type;
5543 // the usual arithmetic conversions are performed to bring them to a
5544 // common type, and the result is of that type.
5545 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005546 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005547 if (LHS.isInvalid() || RHS.isInvalid())
5548 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005549 if (ResTy.isNull()) {
5550 Diag(QuestionLoc,
5551 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5552 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5553 return QualType();
5554 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005555
5556 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5557 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5558
5559 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005560 }
5561
5562 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005563 // type and the other is a null pointer constant, or both are null
5564 // pointer constants, at least one of which is non-integral; pointer
5565 // conversions and qualification conversions are performed to bring them
5566 // to their composite pointer type. The result is of the composite
5567 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005568 // -- The second and third operands have pointer to member type, or one has
5569 // pointer to member type and the other is a null pointer constant;
5570 // pointer to member conversions and qualification conversions are
5571 // performed to bring them to a common type, whose cv-qualification
5572 // shall match the cv-qualification of either the second or the third
5573 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005574 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5575 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005576 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005577
Douglas Gregor697a3912010-04-01 22:47:07 +00005578 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005579 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5580 if (!Composite.isNull())
5581 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005582
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005583 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005584 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005585 return QualType();
5586
Sebastian Redl1a99f442009-04-16 17:51:27 +00005587 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005588 << LHS.get()->getType() << RHS.get()->getType()
5589 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005590 return QualType();
5591}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005592
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005593static FunctionProtoType::ExceptionSpecInfo
5594mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5595 FunctionProtoType::ExceptionSpecInfo ESI2,
5596 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5597 ExceptionSpecificationType EST1 = ESI1.Type;
5598 ExceptionSpecificationType EST2 = ESI2.Type;
5599
5600 // If either of them can throw anything, that is the result.
5601 if (EST1 == EST_None) return ESI1;
5602 if (EST2 == EST_None) return ESI2;
5603 if (EST1 == EST_MSAny) return ESI1;
5604 if (EST2 == EST_MSAny) return ESI2;
5605
5606 // If either of them is non-throwing, the result is the other.
5607 if (EST1 == EST_DynamicNone) return ESI2;
5608 if (EST2 == EST_DynamicNone) return ESI1;
5609 if (EST1 == EST_BasicNoexcept) return ESI2;
5610 if (EST2 == EST_BasicNoexcept) return ESI1;
5611
5612 // If either of them is a non-value-dependent computed noexcept, that
5613 // determines the result.
5614 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5615 !ESI2.NoexceptExpr->isValueDependent())
5616 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5617 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5618 !ESI1.NoexceptExpr->isValueDependent())
5619 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5620 // If we're left with value-dependent computed noexcept expressions, we're
5621 // stuck. Before C++17, we can just drop the exception specification entirely,
5622 // since it's not actually part of the canonical type. And this should never
5623 // happen in C++17, because it would mean we were computing the composite
5624 // pointer type of dependent types, which should never happen.
5625 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
5626 assert(!S.getLangOpts().CPlusPlus1z &&
5627 "computing composite pointer type of dependent types");
5628 return FunctionProtoType::ExceptionSpecInfo();
5629 }
5630
5631 // Switch over the possibilities so that people adding new values know to
5632 // update this function.
5633 switch (EST1) {
5634 case EST_None:
5635 case EST_DynamicNone:
5636 case EST_MSAny:
5637 case EST_BasicNoexcept:
5638 case EST_ComputedNoexcept:
5639 llvm_unreachable("handled above");
5640
5641 case EST_Dynamic: {
5642 // This is the fun case: both exception specifications are dynamic. Form
5643 // the union of the two lists.
5644 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5645 llvm::SmallPtrSet<QualType, 8> Found;
5646 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5647 for (QualType E : Exceptions)
5648 if (Found.insert(S.Context.getCanonicalType(E)).second)
5649 ExceptionTypeStorage.push_back(E);
5650
5651 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5652 Result.Exceptions = ExceptionTypeStorage;
5653 return Result;
5654 }
5655
5656 case EST_Unevaluated:
5657 case EST_Uninstantiated:
5658 case EST_Unparsed:
5659 llvm_unreachable("shouldn't see unresolved exception specifications here");
5660 }
5661
5662 llvm_unreachable("invalid ExceptionSpecificationType");
5663}
5664
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005665/// \brief Find a merged pointer type and convert the two expressions to it.
5666///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005667/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005668/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005669/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005670/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005671///
Douglas Gregor19175ff2010-04-16 23:20:25 +00005672/// \param Loc The location of the operator requiring these two expressions to
5673/// be converted to the composite pointer type.
5674///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005675/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005676QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00005677 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005678 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005679 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005680
5681 // C++1z [expr]p14:
5682 // The composite pointer type of two operands p1 and p2 having types T1
5683 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005684 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005685
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005686 // where at least one is a pointer or pointer to member type or
5687 // std::nullptr_t is:
5688 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5689 T1->isNullPtrType();
5690 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5691 T2->isNullPtrType();
5692 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00005693 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005694
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005695 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5696 // This can't actually happen, following the standard, but we also use this
5697 // to implement the end of [expr.conv], which hits this case.
5698 //
5699 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5700 if (T1IsPointerLike &&
5701 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005702 if (ConvertArgs)
5703 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5704 ? CK_NullToMemberPointer
5705 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005706 return T1;
5707 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005708 if (T2IsPointerLike &&
5709 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005710 if (ConvertArgs)
5711 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5712 ? CK_NullToMemberPointer
5713 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005714 return T2;
5715 }
Mike Stump11289f42009-09-09 15:08:12 +00005716
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005717 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005718 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005719 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005720 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
5721 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005722
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005723 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5724 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5725 // the union of cv1 and cv2;
5726 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5727 // "pointer to function", where the function types are otherwise the same,
5728 // "pointer to function";
5729 // FIXME: This rule is defective: it should also permit removing noexcept
5730 // from a pointer to member function. As a Clang extension, we also
5731 // permit removing 'noreturn', so we generalize this rule to;
5732 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5733 // "pointer to member function" and the pointee types can be unified
5734 // by a function pointer conversion, that conversion is applied
5735 // before checking the following rules.
5736 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5737 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5738 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5739 // respectively;
5740 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5741 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5742 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5743 // T1 or the cv-combined type of T1 and T2, respectively;
5744 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5745 // T2;
5746 //
5747 // If looked at in the right way, these bullets all do the same thing.
5748 // What we do here is, we build the two possible cv-combined types, and try
5749 // the conversions in both directions. If only one works, or if the two
5750 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00005751 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005752 //
5753 // Note that this will fail to find a composite pointer type for "pointer
5754 // to void" and "pointer to function". We can't actually perform the final
5755 // conversion in this case, even though a composite pointer type formally
5756 // exists.
5757 SmallVector<unsigned, 4> QualifierUnion;
5758 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005759 QualType Composite1 = T1;
5760 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005761 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005762 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005763 const PointerType *Ptr1, *Ptr2;
5764 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5765 (Ptr2 = Composite2->getAs<PointerType>())) {
5766 Composite1 = Ptr1->getPointeeType();
5767 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005768
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005769 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005770 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005771 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005772 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005773
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005774 QualifierUnion.push_back(
5775 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00005776 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005777 continue;
5778 }
Mike Stump11289f42009-09-09 15:08:12 +00005779
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005780 const MemberPointerType *MemPtr1, *MemPtr2;
5781 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5782 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5783 Composite1 = MemPtr1->getPointeeType();
5784 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005785
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005786 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005787 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005788 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005789 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005790
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005791 QualifierUnion.push_back(
5792 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5793 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5794 MemPtr2->getClass()));
5795 continue;
5796 }
Mike Stump11289f42009-09-09 15:08:12 +00005797
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005798 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00005799
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005800 // Cannot unwrap any more types.
5801 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005802 }
Mike Stump11289f42009-09-09 15:08:12 +00005803
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005804 // Apply the function pointer conversion to unify the types. We've already
5805 // unwrapped down to the function types, and we want to merge rather than
5806 // just convert, so do this ourselves rather than calling
5807 // IsFunctionConversion.
5808 //
5809 // FIXME: In order to match the standard wording as closely as possible, we
5810 // currently only do this under a single level of pointers. Ideally, we would
5811 // allow this in general, and set NeedConstBefore to the relevant depth on
5812 // the side(s) where we changed anything.
5813 if (QualifierUnion.size() == 1) {
5814 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5815 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5816 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5817 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5818
5819 // The result is noreturn if both operands are.
5820 bool Noreturn =
5821 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5822 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5823 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5824
5825 // The result is nothrow if both operands are.
5826 SmallVector<QualType, 8> ExceptionTypeStorage;
5827 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
5828 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
5829 ExceptionTypeStorage);
5830
5831 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
5832 FPT1->getParamTypes(), EPI1);
5833 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
5834 FPT2->getParamTypes(), EPI2);
5835 }
5836 }
5837 }
5838
Richard Smith5e9746f2016-10-21 22:00:42 +00005839 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005840 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005841 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005842 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00005843 for (unsigned I = 0; I != NeedConstBefore; ++I)
5844 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005845 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005846 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005847
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005848 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005849 auto MOC = MemberOfClass.rbegin();
5850 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
5851 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
5852 auto Classes = *MOC++;
5853 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005854 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005855 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005856 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00005857 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005858 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005859 } else {
5860 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005861 Composite1 =
5862 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5863 Composite2 =
5864 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005865 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005866 }
5867
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005868 struct Conversion {
5869 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005870 Expr *&E1, *&E2;
5871 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00005872 InitializedEntity Entity;
5873 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005874 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00005875 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00005876
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005877 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
5878 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00005879 : S(S), E1(E1), E2(E2), Composite(Composite),
5880 Entity(InitializedEntity::InitializeTemporary(Composite)),
5881 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
5882 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
5883 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005884
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005885 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005886 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
5887 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005888 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005889 E1 = E1Result.getAs<Expr>();
5890
5891 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
5892 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005893 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005894 E2 = E2Result.getAs<Expr>();
5895
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005896 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005897 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005898 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00005899
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005900 // Try to convert to each composite pointer type.
5901 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005902 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
5903 if (ConvertArgs && C1.perform())
5904 return QualType();
5905 return C1.Composite;
5906 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005907 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005908
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005909 if (C1.Viable == C2.Viable) {
5910 // Either Composite1 and Composite2 are viable and are different, or
5911 // neither is viable.
5912 // FIXME: How both be viable and different?
5913 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005914 }
5915
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005916 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005917 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
5918 return QualType();
5919
5920 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005921}
Anders Carlsson85a307d2009-05-17 18:41:29 +00005922
John McCalldadc5752010-08-24 06:29:42 +00005923ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00005924 if (!E)
5925 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005926
John McCall31168b02011-06-15 23:02:42 +00005927 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
5928
5929 // If the result is a glvalue, we shouldn't bind it.
5930 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005931 return E;
Mike Stump11289f42009-09-09 15:08:12 +00005932
John McCall31168b02011-06-15 23:02:42 +00005933 // In ARC, calls that return a retainable type can return retained,
5934 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005935 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00005936 E->getType()->isObjCRetainableType()) {
5937
5938 bool ReturnsRetained;
5939
5940 // For actual calls, we compute this by examining the type of the
5941 // called value.
5942 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5943 Expr *Callee = Call->getCallee()->IgnoreParens();
5944 QualType T = Callee->getType();
5945
5946 if (T == Context.BoundMemberTy) {
5947 // Handle pointer-to-members.
5948 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5949 T = BinOp->getRHS()->getType();
5950 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5951 T = Mem->getMemberDecl()->getType();
5952 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005953
John McCall31168b02011-06-15 23:02:42 +00005954 if (const PointerType *Ptr = T->getAs<PointerType>())
5955 T = Ptr->getPointeeType();
5956 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
5957 T = Ptr->getPointeeType();
5958 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
5959 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00005960
John McCall31168b02011-06-15 23:02:42 +00005961 const FunctionType *FTy = T->getAs<FunctionType>();
5962 assert(FTy && "call to value not of function type?");
5963 ReturnsRetained = FTy->getExtInfo().getProducesResult();
5964
5965 // ActOnStmtExpr arranges things so that StmtExprs of retainable
5966 // type always produce a +1 object.
5967 } else if (isa<StmtExpr>(E)) {
5968 ReturnsRetained = true;
5969
Ted Kremeneke65b0862012-03-06 20:05:56 +00005970 // We hit this case with the lambda conversion-to-block optimization;
5971 // we don't want any extra casts here.
5972 } else if (isa<CastExpr>(E) &&
5973 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005974 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005975
John McCall31168b02011-06-15 23:02:42 +00005976 // For message sends and property references, we try to find an
5977 // actual method. FIXME: we should infer retention by selector in
5978 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00005979 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00005980 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005981 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
5982 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00005983 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
5984 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00005985 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
5986 D = ArrayLit->getArrayWithObjectsMethod();
5987 } else if (ObjCDictionaryLiteral *DictLit
5988 = dyn_cast<ObjCDictionaryLiteral>(E)) {
5989 D = DictLit->getDictWithObjectsMethod();
5990 }
John McCall31168b02011-06-15 23:02:42 +00005991
5992 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00005993
5994 // Don't do reclaims on performSelector calls; despite their
5995 // return type, the invoked method doesn't necessarily actually
5996 // return an object.
5997 if (!ReturnsRetained &&
5998 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005999 return E;
John McCall31168b02011-06-15 23:02:42 +00006000 }
6001
John McCall16de4d22011-11-14 19:53:16 +00006002 // Don't reclaim an object of Class type.
6003 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006004 return E;
John McCall16de4d22011-11-14 19:53:16 +00006005
Tim Shen4a05bb82016-06-21 20:29:17 +00006006 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006007
John McCall2d637d22011-09-10 06:18:15 +00006008 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6009 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006010 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6011 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006012 }
6013
David Blaikiebbafb8a2012-03-11 07:00:24 +00006014 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006015 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006016
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006017 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6018 // a fast path for the common case that the type is directly a RecordType.
6019 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006020 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006021 while (!RT) {
6022 switch (T->getTypeClass()) {
6023 case Type::Record:
6024 RT = cast<RecordType>(T);
6025 break;
6026 case Type::ConstantArray:
6027 case Type::IncompleteArray:
6028 case Type::VariableArray:
6029 case Type::DependentSizedArray:
6030 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6031 break;
6032 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006033 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006034 }
6035 }
Mike Stump11289f42009-09-09 15:08:12 +00006036
Richard Smithfd555f62012-02-22 02:04:18 +00006037 // That should be enough to guarantee that this type is complete, if we're
6038 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006039 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006040 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006041 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006042
6043 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006044 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006045
John McCall31168b02011-06-15 23:02:42 +00006046 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006047 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006048 CheckDestructorAccess(E->getExprLoc(), Destructor,
6049 PDiag(diag::err_access_dtor_temp)
6050 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006051 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6052 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006053
Richard Smithfd555f62012-02-22 02:04:18 +00006054 // If destructor is trivial, we can avoid the extra copy.
6055 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006056 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006057
John McCall28fc7092011-11-10 05:35:25 +00006058 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006059 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006060 }
Richard Smitheec915d62012-02-18 04:13:32 +00006061
6062 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006063 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6064
6065 if (IsDecltype)
6066 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6067
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006068 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006069}
6070
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006071ExprResult
John McCall5d413782010-12-06 08:20:24 +00006072Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006073 if (SubExpr.isInvalid())
6074 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006075
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006076 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006077}
6078
John McCall28fc7092011-11-10 05:35:25 +00006079Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006080 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006081
Eli Friedman3bda6b12012-02-02 23:15:15 +00006082 CleanupVarDeclMarking();
6083
John McCall28fc7092011-11-10 05:35:25 +00006084 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6085 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006086 assert(Cleanup.exprNeedsCleanups() ||
6087 ExprCleanupObjects.size() == FirstCleanup);
6088 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006089 return SubExpr;
6090
Craig Topper5fc8fc22014-08-27 06:28:36 +00006091 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6092 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006093
Tim Shen4a05bb82016-06-21 20:29:17 +00006094 auto *E = ExprWithCleanups::Create(
6095 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006096 DiscardCleanupsInEvaluationContext();
6097
6098 return E;
6099}
6100
John McCall5d413782010-12-06 08:20:24 +00006101Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006102 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006103
Eli Friedman3bda6b12012-02-02 23:15:15 +00006104 CleanupVarDeclMarking();
6105
Tim Shen4a05bb82016-06-21 20:29:17 +00006106 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006107 return SubStmt;
6108
6109 // FIXME: In order to attach the temporaries, wrap the statement into
6110 // a StmtExpr; currently this is only used for asm statements.
6111 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6112 // a new AsmStmtWithTemporaries.
Nico Webera2a0eb92012-12-29 20:03:39 +00006113 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006114 SourceLocation(),
6115 SourceLocation());
6116 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6117 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006118 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006119}
6120
Richard Smithfd555f62012-02-22 02:04:18 +00006121/// Process the expression contained within a decltype. For such expressions,
6122/// certain semantic checks on temporaries are delayed until this point, and
6123/// are omitted for the 'topmost' call in the decltype expression. If the
6124/// topmost call bound a temporary, strip that temporary off the expression.
6125ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006126 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006127
6128 // C++11 [expr.call]p11:
6129 // If a function call is a prvalue of object type,
6130 // -- if the function call is either
6131 // -- the operand of a decltype-specifier, or
6132 // -- the right operand of a comma operator that is the operand of a
6133 // decltype-specifier,
6134 // a temporary object is not introduced for the prvalue.
6135
6136 // Recursively rebuild ParenExprs and comma expressions to strip out the
6137 // outermost CXXBindTemporaryExpr, if any.
6138 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6139 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6140 if (SubExpr.isInvalid())
6141 return ExprError();
6142 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006143 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006144 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006145 }
6146 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6147 if (BO->getOpcode() == BO_Comma) {
6148 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6149 if (RHS.isInvalid())
6150 return ExprError();
6151 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006152 return E;
6153 return new (Context) BinaryOperator(
6154 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6155 BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
Richard Smithfd555f62012-02-22 02:04:18 +00006156 }
6157 }
6158
6159 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006160 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6161 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006162 if (TopCall)
6163 E = TopCall;
6164 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006165 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006166
6167 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006168 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00006169
Richard Smithf86b0ae2012-07-28 19:54:11 +00006170 // In MS mode, don't perform any extra checking of call return types within a
6171 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006172 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006173 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006174
Richard Smithfd555f62012-02-22 02:04:18 +00006175 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006176 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6177 I != N; ++I) {
6178 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006179 if (Call == TopCall)
6180 continue;
6181
David Majnemerced8bdf2015-02-25 17:36:15 +00006182 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006183 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006184 Call, Call->getDirectCallee()))
6185 return ExprError();
6186 }
6187
6188 // Now all relevant types are complete, check the destructors are accessible
6189 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006190 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6191 I != N; ++I) {
6192 CXXBindTemporaryExpr *Bind =
6193 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006194 if (Bind == TopBind)
6195 continue;
6196
6197 CXXTemporary *Temp = Bind->getTemporary();
6198
6199 CXXRecordDecl *RD =
6200 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6201 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6202 Temp->setDestructor(Destructor);
6203
Richard Smith7d847b12012-05-11 22:20:10 +00006204 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6205 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006206 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006207 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006208 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6209 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006210
6211 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006212 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006213 }
6214
6215 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006216 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006217}
6218
Richard Smith79c927b2013-11-06 19:31:51 +00006219/// Note a set of 'operator->' functions that were used for a member access.
6220static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006221 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006222 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6223 // FIXME: Make this configurable?
6224 unsigned Limit = 9;
6225 if (OperatorArrows.size() > Limit) {
6226 // Produce Limit-1 normal notes and one 'skipping' note.
6227 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6228 SkipCount = OperatorArrows.size() - (Limit - 1);
6229 }
6230
6231 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6232 if (I == SkipStart) {
6233 S.Diag(OperatorArrows[I]->getLocation(),
6234 diag::note_operator_arrows_suppressed)
6235 << SkipCount;
6236 I += SkipCount;
6237 } else {
6238 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6239 << OperatorArrows[I]->getCallResultType();
6240 ++I;
6241 }
6242 }
6243}
6244
Nico Weber964d3322015-02-16 22:35:45 +00006245ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6246 SourceLocation OpLoc,
6247 tok::TokenKind OpKind,
6248 ParsedType &ObjectType,
6249 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006250 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006251 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006252 if (Result.isInvalid()) return ExprError();
6253 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006254
John McCall526ab472011-10-25 17:37:35 +00006255 Result = CheckPlaceholderExpr(Base);
6256 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006257 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006258
John McCallb268a282010-08-23 23:25:46 +00006259 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006260 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006261 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006262 // If we have a pointer to a dependent type and are using the -> operator,
6263 // the object type is the type that the pointer points to. We might still
6264 // have enough information about that type to do something useful.
6265 if (OpKind == tok::arrow)
6266 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6267 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006268
John McCallba7bf592010-08-24 05:47:05 +00006269 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006270 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006271 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006272 }
Mike Stump11289f42009-09-09 15:08:12 +00006273
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006274 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006275 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006276 // returned, with the original second operand.
6277 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006278 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006279 bool NoArrowOperatorFound = false;
6280 bool FirstIteration = true;
6281 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006282 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006283 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006284 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006285 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006286
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006287 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006288 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6289 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006290 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006291 noteOperatorArrows(*this, OperatorArrows);
6292 Diag(OpLoc, diag::note_operator_arrow_depth)
6293 << getLangOpts().ArrowDepth;
6294 return ExprError();
6295 }
6296
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006297 Result = BuildOverloadedArrowExpr(
6298 S, Base, OpLoc,
6299 // When in a template specialization and on the first loop iteration,
6300 // potentially give the default diagnostic (with the fixit in a
6301 // separate note) instead of having the error reported back to here
6302 // and giving a diagnostic with a fixit attached to the error itself.
6303 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006304 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006305 : &NoArrowOperatorFound);
6306 if (Result.isInvalid()) {
6307 if (NoArrowOperatorFound) {
6308 if (FirstIteration) {
6309 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006310 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006311 << FixItHint::CreateReplacement(OpLoc, ".");
6312 OpKind = tok::period;
6313 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006314 }
6315 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6316 << BaseType << Base->getSourceRange();
6317 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006318 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006319 Diag(CD->getLocStart(),
6320 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006321 }
6322 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006323 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006324 }
John McCallb268a282010-08-23 23:25:46 +00006325 Base = Result.get();
6326 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006327 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006328 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006329 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006330 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006331 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6332 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006333 return ExprError();
6334 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006335 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006336 }
Mike Stump11289f42009-09-09 15:08:12 +00006337
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006338 if (OpKind == tok::arrow &&
6339 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006340 BaseType = BaseType->getPointeeType();
6341 }
Mike Stump11289f42009-09-09 15:08:12 +00006342
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006343 // Objective-C properties allow "." access on Objective-C pointer types,
6344 // so adjust the base type to the object type itself.
6345 if (BaseType->isObjCObjectPointerType())
6346 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006347
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006348 // C++ [basic.lookup.classref]p2:
6349 // [...] If the type of the object expression is of pointer to scalar
6350 // type, the unqualified-id is looked up in the context of the complete
6351 // postfix-expression.
6352 //
6353 // This also indicates that we could be parsing a pseudo-destructor-name.
6354 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006355 // expressions or normal member (ivar or property) access expressions, and
6356 // it's legal for the type to be incomplete if this is a pseudo-destructor
6357 // call. We'll do more incomplete-type checks later in the lookup process,
6358 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006359 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006360 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006361 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006362 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006363 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006364 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006365 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006366 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006367 }
Mike Stump11289f42009-09-09 15:08:12 +00006368
Douglas Gregor3024f072012-04-16 07:05:22 +00006369 // The object type must be complete (or dependent), or
6370 // C++11 [expr.prim.general]p3:
6371 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006372 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006373 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006374 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006375 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006376 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006377 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006378
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006379 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006380 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006381 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006382 // type C (or of pointer to a class type C), the unqualified-id is looked
6383 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006384 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006385 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006386}
6387
Simon Pilgrim75c26882016-09-30 14:25:09 +00006388static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006389 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006390 if (Base->hasPlaceholderType()) {
6391 ExprResult result = S.CheckPlaceholderExpr(Base);
6392 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006393 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006394 }
6395 ObjectType = Base->getType();
6396
David Blaikie1d578782011-12-16 16:03:09 +00006397 // C++ [expr.pseudo]p2:
6398 // The left-hand side of the dot operator shall be of scalar type. The
6399 // left-hand side of the arrow operator shall be of pointer to scalar type.
6400 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006401 // Note that this is rather different from the normal handling for the
6402 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006403 if (OpKind == tok::arrow) {
6404 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6405 ObjectType = Ptr->getPointeeType();
6406 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006407 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006408 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6409 << ObjectType << true
6410 << FixItHint::CreateReplacement(OpLoc, ".");
6411 if (S.isSFINAEContext())
6412 return true;
6413
6414 OpKind = tok::period;
6415 }
6416 }
6417
6418 return false;
6419}
6420
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006421/// \brief Check if it's ok to try and recover dot pseudo destructor calls on
6422/// pointer objects.
6423static bool
6424canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6425 QualType DestructedType) {
6426 // If this is a record type, check if its destructor is callable.
6427 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6428 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6429 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6430 return false;
6431 }
6432
6433 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6434 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6435 DestructedType->isVectorType();
6436}
6437
John McCalldadc5752010-08-24 06:29:42 +00006438ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006439 SourceLocation OpLoc,
6440 tok::TokenKind OpKind,
6441 const CXXScopeSpec &SS,
6442 TypeSourceInfo *ScopeTypeInfo,
6443 SourceLocation CCLoc,
6444 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006445 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006446 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006447
Eli Friedman0ce4de42012-01-25 04:35:06 +00006448 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006449 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6450 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006451
Douglas Gregorc5c57342012-09-10 14:57:06 +00006452 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6453 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006454 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006455 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006456 else {
Nico Weber58829272012-01-23 05:50:57 +00006457 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6458 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006459 return ExprError();
6460 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006461 }
6462
6463 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006464 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006465 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006466 if (DestructedTypeInfo) {
6467 QualType DestructedType = DestructedTypeInfo->getType();
6468 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006469 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006470 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6471 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006472 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6473 // Foo *foo;
6474 // foo.~Foo();
6475 if (OpKind == tok::period && ObjectType->isPointerType() &&
6476 Context.hasSameUnqualifiedType(DestructedType,
6477 ObjectType->getPointeeType())) {
6478 auto Diagnostic =
6479 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6480 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006481
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006482 // Issue a fixit only when the destructor is valid.
6483 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6484 *this, DestructedType))
6485 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6486
6487 // Recover by setting the object type to the destructed type and the
6488 // operator to '->'.
6489 ObjectType = DestructedType;
6490 OpKind = tok::arrow;
6491 } else {
6492 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6493 << ObjectType << DestructedType << Base->getSourceRange()
6494 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6495
6496 // Recover by setting the destructed type to the object type.
6497 DestructedType = ObjectType;
6498 DestructedTypeInfo =
6499 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6500 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6501 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006502 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006503 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006504
John McCall31168b02011-06-15 23:02:42 +00006505 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6506 // Okay: just pretend that the user provided the correctly-qualified
6507 // type.
6508 } else {
6509 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6510 << ObjectType << DestructedType << Base->getSourceRange()
6511 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6512 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006513
John McCall31168b02011-06-15 23:02:42 +00006514 // Recover by setting the destructed type to the object type.
6515 DestructedType = ObjectType;
6516 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6517 DestructedTypeStart);
6518 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6519 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006520 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006521 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006522
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006523 // C++ [expr.pseudo]p2:
6524 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6525 // form
6526 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006527 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006528 //
6529 // shall designate the same scalar type.
6530 if (ScopeTypeInfo) {
6531 QualType ScopeType = ScopeTypeInfo->getType();
6532 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006533 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006534
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006535 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006536 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006537 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006538 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006539
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006540 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006541 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006542 }
6543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006544
John McCallb268a282010-08-23 23:25:46 +00006545 Expr *Result
6546 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6547 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006548 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006549 ScopeTypeInfo,
6550 CCLoc,
6551 TildeLoc,
6552 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006553
David Majnemerced8bdf2015-02-25 17:36:15 +00006554 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006555}
6556
John McCalldadc5752010-08-24 06:29:42 +00006557ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006558 SourceLocation OpLoc,
6559 tok::TokenKind OpKind,
6560 CXXScopeSpec &SS,
6561 UnqualifiedId &FirstTypeName,
6562 SourceLocation CCLoc,
6563 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006564 UnqualifiedId &SecondTypeName) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006565 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6566 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6567 "Invalid first type name in pseudo-destructor");
6568 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6569 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6570 "Invalid second type name in pseudo-destructor");
6571
Eli Friedman0ce4de42012-01-25 04:35:06 +00006572 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006573 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6574 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006575
6576 // Compute the object type that we should use for name lookup purposes. Only
6577 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006578 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006579 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006580 if (ObjectType->isRecordType())
6581 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006582 else if (ObjectType->isDependentType())
6583 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006584 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006585
6586 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006587 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006588 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006589 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006590 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006591 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006592 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006593 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006594 S, &SS, true, false, ObjectTypePtrForLookup,
6595 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006596 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006597 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6598 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006599 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006600 // couldn't find anything useful in scope. Just store the identifier and
6601 // it's location, and we'll perform (qualified) name lookup again at
6602 // template instantiation time.
6603 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6604 SecondTypeName.StartLocation);
6605 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006606 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006607 diag::err_pseudo_dtor_destructor_non_type)
6608 << SecondTypeName.Identifier << ObjectType;
6609 if (isSFINAEContext())
6610 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006611
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006612 // Recover by assuming we had the right type all along.
6613 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006614 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006615 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006616 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006617 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006618 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006619 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006620 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006621 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006622 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006623 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006624 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006625 TemplateId->TemplateNameLoc,
6626 TemplateId->LAngleLoc,
6627 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006628 TemplateId->RAngleLoc,
6629 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006630 if (T.isInvalid() || !T.get()) {
6631 // Recover by assuming we had the right type all along.
6632 DestructedType = ObjectType;
6633 } else
6634 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006636
6637 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006638 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006639 if (!DestructedType.isNull()) {
6640 if (!DestructedTypeInfo)
6641 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006642 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006643 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6644 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006645
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006646 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006647 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006648 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006649 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006650 FirstTypeName.Identifier) {
6651 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006652 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006653 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006654 S, &SS, true, false, ObjectTypePtrForLookup,
6655 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006656 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006657 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006658 diag::err_pseudo_dtor_destructor_non_type)
6659 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006660
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006661 if (isSFINAEContext())
6662 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006663
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006664 // Just drop this type. It's unnecessary anyway.
6665 ScopeType = QualType();
6666 } else
6667 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006668 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006669 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006670 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006671 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006672 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006673 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006674 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006675 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00006676 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006677 TemplateId->TemplateNameLoc,
6678 TemplateId->LAngleLoc,
6679 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00006680 TemplateId->RAngleLoc,
6681 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006682 if (T.isInvalid() || !T.get()) {
6683 // Recover by dropping this type.
6684 ScopeType = QualType();
6685 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006686 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006687 }
6688 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006689
Douglas Gregor90ad9222010-02-24 23:02:30 +00006690 if (!ScopeType.isNull() && !ScopeTypeInfo)
6691 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6692 FirstTypeName.StartLocation);
6693
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006694
John McCallb268a282010-08-23 23:25:46 +00006695 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00006696 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006697 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00006698}
6699
David Blaikie1d578782011-12-16 16:03:09 +00006700ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6701 SourceLocation OpLoc,
6702 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006703 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006704 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00006705 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006706 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6707 return ExprError();
6708
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006709 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6710 false);
David Blaikie1d578782011-12-16 16:03:09 +00006711
6712 TypeLocBuilder TLB;
6713 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6714 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6715 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6716 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6717
6718 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006719 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006720 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00006721}
6722
John Wiegley01296292011-04-08 18:41:53 +00006723ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00006724 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006725 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00006726 if (Method->getParent()->isLambda() &&
6727 Method->getConversionType()->isBlockPointerType()) {
6728 // This is a lambda coversion to block pointer; check if the argument
6729 // is a LambdaExpr.
6730 Expr *SubE = E;
6731 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6732 if (CE && CE->getCastKind() == CK_NoOp)
6733 SubE = CE->getSubExpr();
6734 SubE = SubE->IgnoreParens();
6735 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6736 SubE = BE->getSubExpr();
6737 if (isa<LambdaExpr>(SubE)) {
6738 // For the conversion to block pointer on a lambda expression, we
6739 // construct a special BlockLiteral instead; this doesn't really make
6740 // a difference in ARC, but outside of ARC the resulting block literal
6741 // follows the normal lifetime rules for block literals instead of being
6742 // autoreleased.
6743 DiagnosticErrorTrap Trap(Diags);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006744 PushExpressionEvaluationContext(PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00006745 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6746 E->getExprLoc(),
6747 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006748 PopExpressionEvaluationContext();
6749
Eli Friedman98b01ed2012-03-01 04:01:32 +00006750 if (Exp.isInvalid())
6751 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6752 return Exp;
6753 }
6754 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00006755
Craig Topperc3ec1492014-05-26 06:22:03 +00006756 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006757 FoundDecl, Method);
6758 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00006759 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00006760
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00006761 MemberExpr *ME = new (Context) MemberExpr(
6762 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6763 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006764 if (HadMultipleCandidates)
6765 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00006766 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006767
Alp Toker314cc812014-01-25 16:55:45 +00006768 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00006769 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6770 ResultType = ResultType.getNonLValueExprType(Context);
6771
Douglas Gregor27381f32009-11-23 12:27:39 +00006772 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006773 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00006774 Exp.get()->getLocEnd());
George Burgess IVce6284b2017-01-28 02:19:40 +00006775
6776 if (CheckFunctionCall(Method, CE,
6777 Method->getType()->castAs<FunctionProtoType>()))
6778 return ExprError();
6779
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006780 return CE;
6781}
6782
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006783ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6784 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00006785 // If the operand is an unresolved lookup expression, the expression is ill-
6786 // formed per [over.over]p1, because overloaded function names cannot be used
6787 // without arguments except in explicit contexts.
6788 ExprResult R = CheckPlaceholderExpr(Operand);
6789 if (R.isInvalid())
6790 return R;
6791
6792 // The operand may have been modified when checking the placeholder type.
6793 Operand = R.get();
6794
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006795 if (ActiveTemplateInstantiations.empty() &&
6796 Operand->HasSideEffects(Context, false)) {
6797 // The expression operand for noexcept is in an unevaluated expression
6798 // context, so side effects could result in unintended consequences.
6799 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6800 }
6801
Richard Smithf623c962012-04-17 00:58:00 +00006802 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006803 return new (Context)
6804 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006805}
6806
6807ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6808 Expr *Operand, SourceLocation RParen) {
6809 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00006810}
6811
Eli Friedmanf798f652012-05-24 22:04:19 +00006812static bool IsSpecialDiscardedValue(Expr *E) {
6813 // In C++11, discarded-value expressions of a certain form are special,
6814 // according to [expr]p10:
6815 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6816 // expression is an lvalue of volatile-qualified type and it has
6817 // one of the following forms:
6818 E = E->IgnoreParens();
6819
Eli Friedmanc49c2262012-05-24 22:36:31 +00006820 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006821 if (isa<DeclRefExpr>(E))
6822 return true;
6823
Eli Friedmanc49c2262012-05-24 22:36:31 +00006824 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006825 if (isa<ArraySubscriptExpr>(E))
6826 return true;
6827
Eli Friedmanc49c2262012-05-24 22:36:31 +00006828 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006829 if (isa<MemberExpr>(E))
6830 return true;
6831
Eli Friedmanc49c2262012-05-24 22:36:31 +00006832 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006833 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6834 if (UO->getOpcode() == UO_Deref)
6835 return true;
6836
6837 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00006838 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006839 if (BO->isPtrMemOp())
6840 return true;
6841
Eli Friedmanc49c2262012-05-24 22:36:31 +00006842 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00006843 if (BO->getOpcode() == BO_Comma)
6844 return IsSpecialDiscardedValue(BO->getRHS());
6845 }
6846
Eli Friedmanc49c2262012-05-24 22:36:31 +00006847 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00006848 // operands are one of the above, or
6849 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6850 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6851 IsSpecialDiscardedValue(CO->getFalseExpr());
6852 // The related edge case of "*x ?: *x".
6853 if (BinaryConditionalOperator *BCO =
6854 dyn_cast<BinaryConditionalOperator>(E)) {
6855 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6856 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6857 IsSpecialDiscardedValue(BCO->getFalseExpr());
6858 }
6859
6860 // Objective-C++ extensions to the rule.
6861 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6862 return true;
6863
6864 return false;
6865}
6866
John McCall34376a62010-12-04 03:47:34 +00006867/// Perform the conversions required for an expression used in a
6868/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00006869ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00006870 if (E->hasPlaceholderType()) {
6871 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006872 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006873 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00006874 }
6875
John McCallfee942d2010-12-02 02:07:15 +00006876 // C99 6.3.2.1:
6877 // [Except in specific positions,] an lvalue that does not have
6878 // array type is converted to the value stored in the
6879 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00006880 if (E->isRValue()) {
6881 // In C, function designators (i.e. expressions of function type)
6882 // are r-values, but we still want to do function-to-pointer decay
6883 // on them. This is both technically correct and convenient for
6884 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006885 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00006886 return DefaultFunctionArrayConversion(E);
6887
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006888 return E;
John McCalld68b2d02011-06-27 21:24:11 +00006889 }
John McCallfee942d2010-12-02 02:07:15 +00006890
Eli Friedmanf798f652012-05-24 22:04:19 +00006891 if (getLangOpts().CPlusPlus) {
6892 // The C++11 standard defines the notion of a discarded-value expression;
6893 // normally, we don't need to do anything to handle it, but if it is a
6894 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6895 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006896 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00006897 E->getType().isVolatileQualified() &&
6898 IsSpecialDiscardedValue(E)) {
6899 ExprResult Res = DefaultLvalueConversion(E);
6900 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006901 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006902 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006903 }
Richard Smith122f88d2016-12-06 23:52:28 +00006904
6905 // C++1z:
6906 // If the expression is a prvalue after this optional conversion, the
6907 // temporary materialization conversion is applied.
6908 //
6909 // We skip this step: IR generation is able to synthesize the storage for
6910 // itself in the aggregate case, and adding the extra node to the AST is
6911 // just clutter.
6912 // FIXME: We don't emit lifetime markers for the temporaries due to this.
6913 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006914 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00006915 }
John McCall34376a62010-12-04 03:47:34 +00006916
6917 // GCC seems to also exclude expressions of incomplete enum type.
6918 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6919 if (!T->getDecl()->isComplete()) {
6920 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006921 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006922 return E;
John McCall34376a62010-12-04 03:47:34 +00006923 }
6924 }
6925
John Wiegley01296292011-04-08 18:41:53 +00006926 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6927 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006928 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006929 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00006930
John McCallca61b652010-12-04 12:29:11 +00006931 if (!E->getType()->isVoidType())
6932 RequireCompleteType(E->getExprLoc(), E->getType(),
6933 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006934 return E;
John McCall34376a62010-12-04 03:47:34 +00006935}
6936
Faisal Valia17d19f2013-11-07 05:17:06 +00006937// If we can unambiguously determine whether Var can never be used
6938// in a constant expression, return true.
6939// - if the variable and its initializer are non-dependent, then
6940// we can unambiguously check if the variable is a constant expression.
6941// - if the initializer is not value dependent - we can determine whether
6942// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00006943// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00006944// never be a constant expression.
6945// - FXIME: if the initializer is dependent, we can still do some analysis and
6946// identify certain cases unambiguously as non-const by using a Visitor:
6947// - such as those that involve odr-use of a ParmVarDecl, involve a new
6948// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00006949static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00006950 ASTContext &Context) {
6951 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006952 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006953
6954 // If there is no initializer - this can not be a constant expression.
6955 if (!Var->getAnyInitializer(DefVD)) return true;
6956 assert(DefVD);
6957 if (DefVD->isWeak()) return false;
6958 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00006959
Faisal Valia17d19f2013-11-07 05:17:06 +00006960 Expr *Init = cast<Expr>(Eval->Value);
6961
6962 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00006963 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
6964 // of value-dependent expressions, and use it here to determine whether the
6965 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00006966 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00006967 }
6968
Simon Pilgrim75c26882016-09-30 14:25:09 +00006969 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00006970}
6971
Simon Pilgrim75c26882016-09-30 14:25:09 +00006972/// \brief Check if the current lambda has any potential captures
6973/// that must be captured by any of its enclosing lambdas that are ready to
6974/// capture. If there is a lambda that can capture a nested
6975/// potential-capture, go ahead and do so. Also, check to see if any
6976/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00006977/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00006978
Faisal Valiab3d6462013-12-07 20:22:44 +00006979static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
6980 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
6981
Simon Pilgrim75c26882016-09-30 14:25:09 +00006982 assert(!S.isUnevaluatedContext());
6983 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00006984#ifndef NDEBUG
6985 DeclContext *DC = S.CurContext;
6986 while (DC && isa<CapturedDecl>(DC))
6987 DC = DC->getParent();
6988 assert(
6989 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00006990 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00006991#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00006992
6993 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
6994
6995 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
6996 S.FunctionScopes.data(), S.FunctionScopes.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00006997
Faisal Valiab3d6462013-12-07 20:22:44 +00006998 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00006999 // lambda (within a generic outer lambda), must be captured by an
7000 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007001 const unsigned NumPotentialCaptures =
7002 CurrentLSI->getNumPotentialVariableCaptures();
7003 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007004 Expr *VarExpr = nullptr;
7005 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007006 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007007 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007008 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007009 // need to check enclosing lambda's for speculative captures.
7010 // For e.g.:
7011 // Even though 'x' is not odr-used, it should be captured.
7012 // int test() {
7013 // const int x = 10;
7014 // auto L = [=](auto a) {
7015 // (void) +x + a;
7016 // };
7017 // }
7018 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007019 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007020 continue;
7021
7022 // If we have a capture-capable lambda for the variable, go ahead and
7023 // capture the variable in that lambda (and all its enclosing lambdas).
7024 if (const Optional<unsigned> Index =
7025 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7026 FunctionScopesArrayRef, Var, S)) {
7027 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7028 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7029 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007030 }
7031 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007032 VariableCanNeverBeAConstantExpression(Var, S.Context);
7033 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7034 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007035 // can not be used in a constant expression - which means
7036 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007037 // capture violation early, if the variable is un-captureable.
7038 // This is purely for diagnosing errors early. Otherwise, this
7039 // error would get diagnosed when the lambda becomes capture ready.
7040 QualType CaptureType, DeclRefType;
7041 SourceLocation ExprLoc = VarExpr->getExprLoc();
7042 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007043 /*EllipsisLoc*/ SourceLocation(),
7044 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007045 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007046 // We will never be able to capture this variable, and we need
7047 // to be able to in any and all instantiations, so diagnose it.
7048 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007049 /*EllipsisLoc*/ SourceLocation(),
7050 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007051 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007052 }
7053 }
7054 }
7055
Faisal Valiab3d6462013-12-07 20:22:44 +00007056 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007057 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007058 // If we have a capture-capable lambda for 'this', go ahead and capture
7059 // 'this' in that lambda (and all its enclosing lambdas).
7060 if (const Optional<unsigned> Index =
7061 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Craig Topperc3ec1492014-05-26 06:22:03 +00007062 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007063 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7064 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7065 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7066 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007067 }
7068 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007069
7070 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007071 CurrentLSI->clearPotentialCaptures();
7072}
7073
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007074static ExprResult attemptRecovery(Sema &SemaRef,
7075 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007076 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007077 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7078 Consumer.getLookupResult().getLookupKind());
7079 const CXXScopeSpec *SS = Consumer.getSS();
7080 CXXScopeSpec NewSS;
7081
7082 // Use an approprate CXXScopeSpec for building the expr.
7083 if (auto *NNS = TC.getCorrectionSpecifier())
7084 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7085 else if (SS && !TC.WillReplaceSpecifier())
7086 NewSS = *SS;
7087
Richard Smithde6d6c42015-12-29 19:43:10 +00007088 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007089 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007090 R.addDecl(ND);
7091 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007092 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007093 CXXRecordDecl *Record = nullptr;
7094 if (auto *NNS = TC.getCorrectionSpecifier())
7095 Record = NNS->getAsType()->getAsCXXRecordDecl();
7096 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007097 Record =
7098 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7099 if (Record)
7100 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007101
7102 // Detect and handle the case where the decl might be an implicit
7103 // member.
7104 bool MightBeImplicitMember;
7105 if (!Consumer.isAddressOfOperand())
7106 MightBeImplicitMember = true;
7107 else if (!NewSS.isEmpty())
7108 MightBeImplicitMember = false;
7109 else if (R.isOverloadedResult())
7110 MightBeImplicitMember = false;
7111 else if (R.isUnresolvableResult())
7112 MightBeImplicitMember = true;
7113 else
7114 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7115 isa<IndirectFieldDecl>(ND) ||
7116 isa<MSPropertyDecl>(ND);
7117
7118 if (MightBeImplicitMember)
7119 return SemaRef.BuildPossibleImplicitMemberExpr(
7120 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007121 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007122 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7123 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7124 Ivar->getIdentifier());
7125 }
7126 }
7127
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007128 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7129 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007130}
7131
Kaelyn Takata6c759512014-10-27 18:07:37 +00007132namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007133class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7134 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7135
7136public:
7137 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7138 : TypoExprs(TypoExprs) {}
7139 bool VisitTypoExpr(TypoExpr *TE) {
7140 TypoExprs.insert(TE);
7141 return true;
7142 }
7143};
7144
Kaelyn Takata6c759512014-10-27 18:07:37 +00007145class TransformTypos : public TreeTransform<TransformTypos> {
7146 typedef TreeTransform<TransformTypos> BaseTransform;
7147
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007148 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7149 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007150 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007151 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007152 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007153 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007154
7155 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7156 /// If the TypoExprs were successfully corrected, then the diagnostics should
7157 /// suggest the corrections. Otherwise the diagnostics will not suggest
7158 /// anything (having been passed an empty TypoCorrection).
7159 void EmitAllDiagnostics() {
7160 for (auto E : TypoExprs) {
7161 TypoExpr *TE = cast<TypoExpr>(E);
7162 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007163 if (State.DiagHandler) {
7164 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7165 ExprResult Replacement = TransformCache[TE];
7166
7167 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7168 // TypoCorrection, replacing the existing decls. This ensures the right
7169 // NamedDecl is used in diagnostics e.g. in the case where overload
7170 // resolution was used to select one from several possible decls that
7171 // had been stored in the TypoCorrection.
7172 if (auto *ND = getDeclFromExpr(
7173 Replacement.isInvalid() ? nullptr : Replacement.get()))
7174 TC.setCorrectionDecl(ND);
7175
7176 State.DiagHandler(TC);
7177 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007178 SemaRef.clearDelayedTypo(TE);
7179 }
7180 }
7181
7182 /// \brief If corrections for the first TypoExpr have been exhausted for a
7183 /// given combination of the other TypoExprs, retry those corrections against
7184 /// the next combination of substitutions for the other TypoExprs by advancing
7185 /// to the next potential correction of the second TypoExpr. For the second
7186 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7187 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7188 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7189 /// TransformCache). Returns true if there is still any untried combinations
7190 /// of corrections.
7191 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7192 for (auto TE : TypoExprs) {
7193 auto &State = SemaRef.getTypoExprState(TE);
7194 TransformCache.erase(TE);
7195 if (!State.Consumer->finished())
7196 return true;
7197 State.Consumer->resetCorrectionStream();
7198 }
7199 return false;
7200 }
7201
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007202 NamedDecl *getDeclFromExpr(Expr *E) {
7203 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7204 E = OverloadResolution[OE];
7205
7206 if (!E)
7207 return nullptr;
7208 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007209 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007210 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007211 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007212 // FIXME: Add any other expr types that could be be seen by the delayed typo
7213 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007214 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007215 return nullptr;
7216 }
7217
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007218 ExprResult TryTransform(Expr *E) {
7219 Sema::SFINAETrap Trap(SemaRef);
7220 ExprResult Res = TransformExpr(E);
7221 if (Trap.hasErrorOccurred() || Res.isInvalid())
7222 return ExprError();
7223
7224 return ExprFilter(Res.get());
7225 }
7226
Kaelyn Takata6c759512014-10-27 18:07:37 +00007227public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007228 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7229 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007230
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007231 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7232 MultiExprArg Args,
7233 SourceLocation RParenLoc,
7234 Expr *ExecConfig = nullptr) {
7235 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7236 RParenLoc, ExecConfig);
7237 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007238 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007239 Expr *ResultCall = Result.get();
7240 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7241 ResultCall = BE->getSubExpr();
7242 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7243 OverloadResolution[OE] = CE->getCallee();
7244 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007245 }
7246 return Result;
7247 }
7248
Kaelyn Takata6c759512014-10-27 18:07:37 +00007249 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7250
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007251 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7252
Saleem Abdulrasool407f36b2016-02-07 02:30:55 +00007253 ExprResult TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
7254 return Owned(E);
7255 }
7256
Saleem Abdulrasool02e19a12016-02-07 02:30:59 +00007257 ExprResult TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
7258 return Owned(E);
7259 }
7260
Kaelyn Takata6c759512014-10-27 18:07:37 +00007261 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007262 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007263 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007264 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007265
Kaelyn Takata6c759512014-10-27 18:07:37 +00007266 // Exit if either the transform was valid or if there were no TypoExprs
7267 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007268 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007269 !CheckAndAdvanceTypoExprCorrectionStreams())
7270 break;
7271 }
7272
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007273 // Ensure none of the TypoExprs have multiple typo correction candidates
7274 // with the same edit length that pass all the checks and filters.
7275 // TODO: Properly handle various permutations of possible corrections when
7276 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007277 // Also, disable typo correction while attempting the transform when
7278 // handling potentially ambiguous typo corrections as any new TypoExprs will
7279 // have been introduced by the application of one of the correction
7280 // candidates and add little to no value if corrected.
7281 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007282 while (!AmbiguousTypoExprs.empty()) {
7283 auto TE = AmbiguousTypoExprs.back();
7284 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007285 auto &State = SemaRef.getTypoExprState(TE);
7286 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007287 TransformCache.erase(TE);
7288 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007289 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007290 TransformCache.erase(TE);
7291 Res = ExprError();
7292 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007293 }
7294 AmbiguousTypoExprs.remove(TE);
7295 State.Consumer->restoreSavedPosition();
7296 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007297 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007298 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007299
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007300 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007301 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007302 FindTypoExprs(TypoExprs).TraverseStmt(E);
7303
Kaelyn Takata6c759512014-10-27 18:07:37 +00007304 EmitAllDiagnostics();
7305
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007306 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007307 }
7308
7309 ExprResult TransformTypoExpr(TypoExpr *E) {
7310 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7311 // cached transformation result if there is one and the TypoExpr isn't the
7312 // first one that was encountered.
7313 auto &CacheEntry = TransformCache[E];
7314 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7315 return CacheEntry;
7316 }
7317
7318 auto &State = SemaRef.getTypoExprState(E);
7319 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7320
7321 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7322 // typo correction and return it.
7323 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007324 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007325 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007326 // FIXME: If we would typo-correct to an invalid declaration, it's
7327 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007328 ExprResult NE = State.RecoveryHandler ?
7329 State.RecoveryHandler(SemaRef, E, TC) :
7330 attemptRecovery(SemaRef, *State.Consumer, TC);
7331 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007332 // Check whether there may be a second viable correction with the same
7333 // edit distance; if so, remember this TypoExpr may have an ambiguous
7334 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007335 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007336 if ((Next = State.Consumer->peekNextCorrection()) &&
7337 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7338 AmbiguousTypoExprs.insert(E);
7339 } else {
7340 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007341 }
7342 assert(!NE.isUnset() &&
7343 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007344 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007345 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007346 }
7347 return CacheEntry = ExprError();
7348 }
7349};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007350}
Faisal Valia17d19f2013-11-07 05:17:06 +00007351
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007352ExprResult
7353Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7354 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007355 // If the current evaluation context indicates there are uncorrected typos
7356 // and the current expression isn't guaranteed to not have typos, try to
7357 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007358 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007359 (E->isTypeDependent() || E->isValueDependent() ||
7360 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007361 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7362 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7363 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007364 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007365 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007366 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007367 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007368 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007369 ExprEvalContexts.back().NumTypos -= TyposResolved;
7370 return Result;
7371 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007372 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007373 }
7374 return E;
7375}
7376
Richard Smith945f8d32013-01-14 22:39:08 +00007377ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007378 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007379 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007380 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007381 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007382
7383 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007384 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007385
7386 // If we are an init-expression in a lambdas init-capture, we should not
7387 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007388 // containing full-expression is done).
7389 // template<class ... Ts> void test(Ts ... t) {
7390 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7391 // return a;
7392 // }() ...);
7393 // }
7394 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7395 // when we parse the lambda introducer, and teach capturing (but not
7396 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7397 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7398 // lambda where we've entered the introducer but not the body, or represent a
7399 // lambda where we've entered the body, depending on where the
7400 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007401 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007402 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007403 return ExprError();
7404
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007405 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007406 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007407 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007408 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007409 if (FullExpr.isInvalid())
7410 return ExprError();
7411 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007412
Richard Smith945f8d32013-01-14 22:39:08 +00007413 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007414 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007415 if (FullExpr.isInvalid())
7416 return ExprError();
7417
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007418 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007419 if (FullExpr.isInvalid())
7420 return ExprError();
7421 }
John Wiegley01296292011-04-08 18:41:53 +00007422
Kaelyn Takata49d84322014-11-11 23:26:56 +00007423 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7424 if (FullExpr.isInvalid())
7425 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007426
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007427 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007428
Simon Pilgrim75c26882016-09-30 14:25:09 +00007429 // At the end of this full expression (which could be a deeply nested
7430 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007431 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007432 // Consider the following code:
7433 // void f(int, int);
7434 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007435 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007436 // const int x = 10, y = 20;
7437 // auto L = [=](auto a) {
7438 // auto M = [=](auto b) {
7439 // f(x, b); <-- requires x to be captured by L and M
7440 // f(y, a); <-- requires y to be captured by L, but not all Ms
7441 // };
7442 // };
7443 // }
7444
Simon Pilgrim75c26882016-09-30 14:25:09 +00007445 // FIXME: Also consider what happens for something like this that involves
7446 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007447 // void f() {
7448 // const int n = 0;
7449 // auto L = [&](auto a) {
7450 // +n + ({ 0; a; });
7451 // };
7452 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007453 //
7454 // Here, we see +n, and then the full-expression 0; ends, so we don't
7455 // capture n (and instead remove it from our list of potential captures),
7456 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007457 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007458
Alexey Bataev31939e32016-11-11 12:36:20 +00007459 LambdaScopeInfo *const CurrentLSI =
7460 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007461 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007462 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007463 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007464 // By ensuring we are in the context of a lambda's call operator
7465 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007466 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007467 // PR, a proper fix would entail :
7468 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007469 // - Add to Sema an integer holding the smallest (outermost) scope
7470 // index that we are *lexically* within, and save/restore/set to
7471 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007472 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007473 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007474 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007475 DeclContext *DC = CurContext;
7476 while (DC && isa<CapturedDecl>(DC))
7477 DC = DC->getParent();
7478 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007479 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007480 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007481 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7482 *this);
John McCall5d413782010-12-06 08:20:24 +00007483 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007484}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007485
7486StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7487 if (!FullStmt) return StmtError();
7488
John McCall5d413782010-12-06 08:20:24 +00007489 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007490}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007491
Simon Pilgrim75c26882016-09-30 14:25:09 +00007492Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007493Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7494 CXXScopeSpec &SS,
7495 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007496 DeclarationName TargetName = TargetNameInfo.getName();
7497 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007498 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007499
Douglas Gregor43edb322011-10-24 22:31:10 +00007500 // If the name itself is dependent, then the result is dependent.
7501 if (TargetName.isDependentName())
7502 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007503
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007504 // Do the redeclaration lookup in the current scope.
7505 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7506 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007507 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007508 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007509
Douglas Gregor43edb322011-10-24 22:31:10 +00007510 switch (R.getResultKind()) {
7511 case LookupResult::Found:
7512 case LookupResult::FoundOverloaded:
7513 case LookupResult::FoundUnresolvedValue:
7514 case LookupResult::Ambiguous:
7515 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007516
Douglas Gregor43edb322011-10-24 22:31:10 +00007517 case LookupResult::NotFound:
7518 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007519
Douglas Gregor43edb322011-10-24 22:31:10 +00007520 case LookupResult::NotFoundInCurrentInstantiation:
7521 return IER_Dependent;
7522 }
David Blaikie8a40f702012-01-17 06:56:22 +00007523
7524 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007525}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007526
Simon Pilgrim75c26882016-09-30 14:25:09 +00007527Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007528Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7529 bool IsIfExists, CXXScopeSpec &SS,
7530 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007531 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007532
Richard Smith151c4562016-12-20 21:35:28 +00007533 // Check for an unexpanded parameter pack.
7534 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7535 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7536 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007537 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007538
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007539 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7540}