blob: 83474cb7f83d1d3e1e019ad6969ca2dd67b85510 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
James Dennett84053fb2012-06-22 05:14:59 +00009///
10/// \file
11/// \brief Implements semantic analysis for C++ expressions.
12///
13//===----------------------------------------------------------------------===//
Chris Lattner29375652006-12-04 18:06:35 +000014
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Kaelyn Takata6c759512014-10-27 18:07:37 +000016#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "TypeLocBuilder.h"
Steve Naroffaac94152007-08-25 14:02:58 +000018#include "clang/AST/ASTContext.h"
Faisal Vali47d9ed42014-05-30 04:39:37 +000019#include "clang/AST/ASTLambda.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/CharUnits.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000036#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000038#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000040#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000041using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000042using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000043
Richard Smith7447af42013-03-26 01:15:19 +000044/// \brief Handle the result of the special case name lookup for inheriting
45/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46/// constructor names in member using declarations, even if 'X' is not the
47/// name of the corresponding type.
48ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49 SourceLocation NameLoc,
50 IdentifierInfo &Name) {
51 NestedNameSpecifier *NNS = SS.getScopeRep();
52
53 // Convert the nested-name-specifier into a type.
54 QualType Type;
55 switch (NNS->getKind()) {
56 case NestedNameSpecifier::TypeSpec:
57 case NestedNameSpecifier::TypeSpecWithTemplate:
58 Type = QualType(NNS->getAsType(), 0);
59 break;
60
61 case NestedNameSpecifier::Identifier:
62 // Strip off the last layer of the nested-name-specifier and build a
63 // typename type for it.
64 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66 NNS->getAsIdentifier());
67 break;
68
69 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000070 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000071 case NestedNameSpecifier::Namespace:
72 case NestedNameSpecifier::NamespaceAlias:
73 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
74 }
75
76 // This reference to the type is located entirely at the location of the
77 // final identifier in the qualified-id.
78 return CreateParsedType(Type,
79 Context.getTrivialTypeSourceInfo(Type, NameLoc));
80}
81
John McCallba7bf592010-08-24 05:47:05 +000082ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000083 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000084 SourceLocation NameLoc,
85 Scope *S, CXXScopeSpec &SS,
86 ParsedType ObjectTypePtr,
87 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000088 // Determine where to perform name lookup.
89
90 // FIXME: This area of the standard is very messy, and the current
91 // wording is rather unclear about which scopes we search for the
92 // destructor name; see core issues 399 and 555. Issue 399 in
93 // particular shows where the current description of destructor name
94 // lookup is completely out of line with existing practice, e.g.,
95 // this appears to be ill-formed:
96 //
97 // namespace N {
98 // template <typename T> struct S {
99 // ~S();
100 // };
101 // }
102 //
103 // void f(N::S<int>* s) {
104 // s->N::S<int>::~S();
105 // }
106 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000107 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000108 // For this reason, we're currently only doing the C++03 version of this
109 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000110 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000111 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000112 bool isDependent = false;
113 bool LookInScope = false;
114
Richard Smith64e033f2015-01-15 00:48:52 +0000115 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000116 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000117
Douglas Gregorfe17d252010-02-16 19:09:40 +0000118 // If we have an object type, it's because we are in a
119 // pseudo-destructor-expression or a member access expression, and
120 // we know what type we're looking for.
121 if (ObjectTypePtr)
122 SearchType = GetTypeFromParser(ObjectTypePtr);
123
124 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000125 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000126
Douglas Gregor46841e12010-02-23 00:15:22 +0000127 bool AlreadySearched = false;
128 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000129 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000130 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000131 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000132 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000133 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000134 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000135 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000136 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000137 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000138 // Here, we determine whether the code below is permitted to look at the
139 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000140 DeclContext *DC = computeDeclContext(SS, EnteringContext);
141 if (DC && DC->isFileContext()) {
142 AlreadySearched = true;
143 LookupCtx = DC;
144 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000145 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000146 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000147 LookInScope = true;
148 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000149
Sebastian Redla771d222010-07-07 23:17:38 +0000150 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000151 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000152 if (AlreadySearched) {
153 // Nothing left to do.
154 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
155 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000156 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000157 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
158 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000159 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000160 LookupCtx = computeDeclContext(SearchType);
161 isDependent = SearchType->isDependentType();
162 } else {
163 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000164 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000165 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000166 } else if (ObjectTypePtr) {
167 // C++ [basic.lookup.classref]p3:
168 // If the unqualified-id is ~type-name, the type-name is looked up
169 // in the context of the entire postfix-expression. If the type T
170 // of the object expression is of a class type C, the type-name is
171 // also looked up in the scope of class C. At least one of the
172 // lookups shall find a name that refers to (possibly
173 // cv-qualified) T.
174 LookupCtx = computeDeclContext(SearchType);
175 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000176 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000177 "Caller should have completed object type");
178
179 LookInScope = true;
180 } else {
181 // Perform lookup into the current scope (only).
182 LookInScope = true;
183 }
184
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000186 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
187 for (unsigned Step = 0; Step != 2; ++Step) {
188 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000189 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000190 // we're allowed to look there).
191 Found.clear();
192 if (Step == 0 && LookupCtx)
193 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000194 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000195 LookupName(Found, S);
196 else
197 continue;
198
199 // FIXME: Should we be suppressing ambiguities here?
200 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000201 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000202
203 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
204 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000205 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000206
207 if (SearchType.isNull() || SearchType->isDependentType() ||
208 Context.hasSameUnqualifiedType(T, SearchType)) {
209 // We found our type!
210
Richard Smithc278c002014-01-22 00:30:17 +0000211 return CreateParsedType(T,
212 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000213 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000214
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000215 if (!SearchType.isNull())
216 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000217 }
218
219 // If the name that we found is a class template name, and it is
220 // the same name as the template name in the last part of the
221 // nested-name-specifier (if present) or the object type, then
222 // this is the destructor for that class.
223 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000225 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
226 QualType MemberOfType;
227 if (SS.isSet()) {
228 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
229 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000230 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
231 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000232 }
233 }
234 if (MemberOfType.isNull())
235 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000236
Douglas Gregorfe17d252010-02-16 19:09:40 +0000237 if (MemberOfType.isNull())
238 continue;
239
240 // We're referring into a class template specialization. If the
241 // class template we found is the same as the template being
242 // specialized, we found what we are looking for.
243 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
244 if (ClassTemplateSpecializationDecl *Spec
245 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
246 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
247 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000248 return CreateParsedType(
249 MemberOfType,
250 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000251 }
252
253 continue;
254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000255
Douglas Gregorfe17d252010-02-16 19:09:40 +0000256 // We're referring to an unresolved class template
257 // specialization. Determine whether we class template we found
258 // is the same as the template being specialized or, if we don't
259 // know which template is being specialized, that it at least
260 // has the same name.
261 if (const TemplateSpecializationType *SpecType
262 = MemberOfType->getAs<TemplateSpecializationType>()) {
263 TemplateName SpecName = SpecType->getTemplateName();
264
265 // The class template we found is the same template being
266 // specialized.
267 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
268 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000269 return CreateParsedType(
270 MemberOfType,
271 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000272
273 continue;
274 }
275
276 // The class template we found has the same name as the
277 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000279 = SpecName.getAsDependentTemplateName()) {
280 if (DepTemplate->isIdentifier() &&
281 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000282 return CreateParsedType(
283 MemberOfType,
284 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000285
286 continue;
287 }
288 }
289 }
290 }
291
292 if (isDependent) {
293 // We didn't find our type, but that's okay: it's dependent
294 // anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000295
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000296 // FIXME: What if we have no nested-name-specifier?
297 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
298 SS.getWithLocInContext(Context),
299 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000300 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000301 }
302
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000303 if (NonMatchingTypeDecl) {
304 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
305 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
306 << T << SearchType;
307 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
308 << T;
309 } else if (ObjectTypePtr)
310 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000311 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000312 else {
313 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
314 diag::err_destructor_class_name);
315 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000316 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000317 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
318 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
319 Class->getNameAsString());
320 }
321 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000322
David Blaikieefdccaa2016-01-15 23:43:34 +0000323 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000324}
325
David Blaikieecd8a942011-12-08 16:13:53 +0000326ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie08608f62011-12-12 04:13:55 +0000327 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikieefdccaa2016-01-15 23:43:34 +0000328 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000329 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
David Blaikieecd8a942011-12-08 16:13:53 +0000330 && "only get destructor types from declspecs");
331 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
332 QualType SearchType = GetTypeFromParser(ObjectType);
333 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
334 return ParsedType::make(T);
335 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000336
David Blaikieecd8a942011-12-08 16:13:53 +0000337 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
338 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000339 return nullptr;
David Blaikieecd8a942011-12-08 16:13:53 +0000340}
341
Richard Smithd091dc12013-12-05 00:58:33 +0000342bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
343 const UnqualifiedId &Name) {
344 assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
345
346 if (!SS.isValid())
347 return false;
348
349 switch (SS.getScopeRep()->getKind()) {
350 case NestedNameSpecifier::Identifier:
351 case NestedNameSpecifier::TypeSpec:
352 case NestedNameSpecifier::TypeSpecWithTemplate:
353 // Per C++11 [over.literal]p2, literal operators can only be declared at
354 // namespace scope. Therefore, this unqualified-id cannot name anything.
355 // Reject it early, because we have no AST representation for this in the
356 // case where the scope is dependent.
357 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
358 << SS.getScopeRep();
359 return true;
360
361 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000362 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000363 case NestedNameSpecifier::Namespace:
364 case NestedNameSpecifier::NamespaceAlias:
365 return false;
366 }
367
368 llvm_unreachable("unknown nested name specifier kind");
369}
370
Douglas Gregor9da64192010-04-26 22:37:10 +0000371/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000372ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000373 SourceLocation TypeidLoc,
374 TypeSourceInfo *Operand,
375 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000376 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000377 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000378 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000379 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000380 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000381 Qualifiers Quals;
382 QualType T
383 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
384 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000385 if (T->getAs<RecordType>() &&
386 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
387 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388
David Majnemer6f3150a2014-11-21 21:09:12 +0000389 if (T->isVariablyModifiedType())
390 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
391
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000392 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
393 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000394}
395
396/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000397ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000398 SourceLocation TypeidLoc,
399 Expr *E,
400 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000401 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000402 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000403 if (E->getType()->isPlaceholderType()) {
404 ExprResult result = CheckPlaceholderExpr(E);
405 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000406 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000407 }
408
Douglas Gregor9da64192010-04-26 22:37:10 +0000409 QualType T = E->getType();
410 if (const RecordType *RecordT = T->getAs<RecordType>()) {
411 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
412 // C++ [expr.typeid]p3:
413 // [...] If the type of the expression is a class type, the class
414 // shall be completely-defined.
415 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
416 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417
Douglas Gregor9da64192010-04-26 22:37:10 +0000418 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000419 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000420 // polymorphic class type [...] [the] expression is an unevaluated
421 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000422 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000423 // The subexpression is potentially evaluated; switch the context
424 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000425 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000426 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000427 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000428
429 // We require a vtable to query the type at run time.
430 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000431 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000432 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000433 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000434
Douglas Gregor9da64192010-04-26 22:37:10 +0000435 // C++ [expr.typeid]p4:
436 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000437 // cv-qualified type, the result of the typeid expression refers to a
438 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000439 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000440 Qualifiers Quals;
441 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
442 if (!Context.hasSameType(T, UnqualT)) {
443 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000444 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000445 }
446 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000447
David Majnemer6f3150a2014-11-21 21:09:12 +0000448 if (E->getType()->isVariablyModifiedType())
449 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
450 << E->getType());
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000451 else if (ActiveTemplateInstantiations.empty() &&
452 E->HasSideEffects(Context, WasEvaluated)) {
453 // The expression operand for typeid is in an unevaluated expression
454 // context, so side effects could result in unintended consequences.
455 Diag(E->getExprLoc(), WasEvaluated
456 ? diag::warn_side_effects_typeid
457 : diag::warn_side_effects_unevaluated_context);
458 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000459
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000460 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
461 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000462}
463
464/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000465ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000466Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
467 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000468 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000469 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000470 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000471
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000472 if (!CXXTypeInfoDecl) {
473 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
474 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
475 LookupQualifiedName(R, getStdNamespace());
476 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000477 // Microsoft's typeinfo doesn't have type_info in std but in the global
478 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000479 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000480 LookupQualifiedName(R, Context.getTranslationUnitDecl());
481 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
482 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000483 if (!CXXTypeInfoDecl)
484 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000486
Nico Weber1b7f39d2012-05-20 01:27:21 +0000487 if (!getLangOpts().RTTI) {
488 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
489 }
490
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000491 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000492
Douglas Gregor9da64192010-04-26 22:37:10 +0000493 if (isType) {
494 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000495 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000496 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
497 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000498 if (T.isNull())
499 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
Douglas Gregor9da64192010-04-26 22:37:10 +0000501 if (!TInfo)
502 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000503
Douglas Gregor9da64192010-04-26 22:37:10 +0000504 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000505 }
Mike Stump11289f42009-09-09 15:08:12 +0000506
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000508 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000509}
510
David Majnemer1dbc7a72016-03-27 04:46:07 +0000511/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
512/// a single GUID.
513static void
514getUuidAttrOfType(Sema &SemaRef, QualType QT,
515 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
516 // Optionally remove one level of pointer, reference or array indirection.
517 const Type *Ty = QT.getTypePtr();
518 if (QT->isPointerType() || QT->isReferenceType())
519 Ty = QT->getPointeeType().getTypePtr();
520 else if (QT->isArrayType())
521 Ty = Ty->getBaseElementTypeUnsafe();
522
523 const auto *RD = Ty->getAsCXXRecordDecl();
524 if (!RD)
525 return;
526
527 if (const auto *Uuid = RD->getMostRecentDecl()->getAttr<UuidAttr>()) {
528 UuidAttrs.insert(Uuid);
529 return;
530 }
531
532 // __uuidof can grab UUIDs from template arguments.
533 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
534 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
535 for (const TemplateArgument &TA : TAL.asArray()) {
536 const UuidAttr *UuidForTA = nullptr;
537 if (TA.getKind() == TemplateArgument::Type)
538 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
539 else if (TA.getKind() == TemplateArgument::Declaration)
540 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
541
542 if (UuidForTA)
543 UuidAttrs.insert(UuidForTA);
544 }
545 }
546}
547
Francois Pichet9f4f2072010-09-08 12:20:18 +0000548/// \brief Build a Microsoft __uuidof expression with a type operand.
549ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
550 SourceLocation TypeidLoc,
551 TypeSourceInfo *Operand,
552 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000553 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000554 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000555 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
556 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
557 if (UuidAttrs.empty())
558 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
559 if (UuidAttrs.size() > 1)
560 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000561 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000562 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
David Majnemer2041b462016-03-28 03:19:50 +0000564 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000565 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000566}
567
568/// \brief Build a Microsoft __uuidof expression with an expression operand.
569ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
570 SourceLocation TypeidLoc,
571 Expr *E,
572 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000573 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000574 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000575 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
576 UuidStr = "00000000-0000-0000-0000-000000000000";
577 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000578 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
579 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
580 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000581 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000582 if (UuidAttrs.size() > 1)
583 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000584 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000585 }
Francois Pichetb7577652010-12-27 01:32:00 +0000586 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000587
David Majnemer2041b462016-03-28 03:19:50 +0000588 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000589 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000590}
591
592/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
593ExprResult
594Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
595 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000596 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000597 if (!MSVCGuidDecl) {
598 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
599 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
600 LookupQualifiedName(R, Context.getTranslationUnitDecl());
601 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
602 if (!MSVCGuidDecl)
603 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000604 }
605
Francois Pichet9f4f2072010-09-08 12:20:18 +0000606 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000607
Francois Pichet9f4f2072010-09-08 12:20:18 +0000608 if (isType) {
609 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000610 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000611 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
612 &TInfo);
613 if (T.isNull())
614 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000615
Francois Pichet9f4f2072010-09-08 12:20:18 +0000616 if (!TInfo)
617 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
618
619 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
620 }
621
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000622 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000623 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
624}
625
Steve Naroff66356bd2007-09-16 14:56:35 +0000626/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000627ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000628Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000629 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000630 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000631 return new (Context)
632 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000633}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000634
Sebastian Redl576fd422009-05-10 18:38:11 +0000635/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000636ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000637Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000638 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000639}
640
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000641/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000642ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000643Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
644 bool IsThrownVarInScope = false;
645 if (Ex) {
646 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000647 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000648 // copy/move construction of a class object [...]
649 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000650 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000651 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000652 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000653 // innermost enclosing try-block (if there is one), the copy/move
654 // operation from the operand to the exception object (15.1) can be
655 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000656 // exception object
657 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
658 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
659 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
660 for( ; S; S = S->getParent()) {
661 if (S->isDeclScope(Var)) {
662 IsThrownVarInScope = true;
663 break;
664 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000665
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000666 if (S->getFlags() &
667 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
668 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
669 Scope::TryScope))
670 break;
671 }
672 }
673 }
674 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000675
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000676 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
677}
678
Simon Pilgrim75c26882016-09-30 14:25:09 +0000679ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000680 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000681 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000682 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000683 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000684 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000685
Justin Lebar2a8db342016-09-28 22:45:54 +0000686 // Exceptions aren't allowed in CUDA device code.
687 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000688 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
689 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000690
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000691 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
692 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
693
John Wiegley01296292011-04-08 18:41:53 +0000694 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000695 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
696 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000697 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000698
699 // Initialize the exception result. This implicitly weeds out
700 // abstract types or types with inaccessible copy constructors.
701
702 // C++0x [class.copymove]p31:
703 // When certain criteria are met, an implementation is allowed to omit the
704 // copy/move construction of a class object [...]
705 //
706 // - in a throw-expression, when the operand is the name of a
707 // non-volatile automatic object (other than a function or
708 // catch-clause
709 // parameter) whose scope does not extend beyond the end of the
710 // innermost enclosing try-block (if there is one), the copy/move
711 // operation from the operand to the exception object (15.1) can be
712 // omitted by constructing the automatic object directly into the
713 // exception object
714 const VarDecl *NRVOVariable = nullptr;
715 if (IsThrownVarInScope)
716 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
717
718 InitializedEntity Entity = InitializedEntity::InitializeException(
719 OpLoc, ExceptionObjectTy,
720 /*NRVO=*/NRVOVariable != nullptr);
721 ExprResult Res = PerformMoveOrCopyInitialization(
722 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
723 if (Res.isInvalid())
724 return ExprError();
725 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000726 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000727
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000728 return new (Context)
729 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000730}
731
David Majnemere7a818f2015-03-06 18:53:55 +0000732static void
733collectPublicBases(CXXRecordDecl *RD,
734 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
735 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
736 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
737 bool ParentIsPublic) {
738 for (const CXXBaseSpecifier &BS : RD->bases()) {
739 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
740 bool NewSubobject;
741 // Virtual bases constitute the same subobject. Non-virtual bases are
742 // always distinct subobjects.
743 if (BS.isVirtual())
744 NewSubobject = VBases.insert(BaseDecl).second;
745 else
746 NewSubobject = true;
747
748 if (NewSubobject)
749 ++SubobjectsSeen[BaseDecl];
750
751 // Only add subobjects which have public access throughout the entire chain.
752 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
753 if (PublicPath)
754 PublicSubobjectsSeen.insert(BaseDecl);
755
756 // Recurse on to each base subobject.
757 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
758 PublicPath);
759 }
760}
761
762static void getUnambiguousPublicSubobjects(
763 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
764 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
765 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
766 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
767 SubobjectsSeen[RD] = 1;
768 PublicSubobjectsSeen.insert(RD);
769 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
770 /*ParentIsPublic=*/true);
771
772 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
773 // Skip ambiguous objects.
774 if (SubobjectsSeen[PublicSubobject] > 1)
775 continue;
776
777 Objects.push_back(PublicSubobject);
778 }
779}
780
Sebastian Redl4de47b42009-04-27 20:27:31 +0000781/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000782bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
783 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000784 // If the type of the exception would be an incomplete type or a pointer
785 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000786 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000787 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000788 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000789 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000790 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000791 }
792 if (!isPointer || !Ty->isVoidType()) {
793 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000794 isPointer ? diag::err_throw_incomplete_ptr
795 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000796 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000797 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000798
David Majnemerd09a51c2015-03-03 01:50:05 +0000799 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000800 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000801 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000802 }
803
Eli Friedman91a3d272010-06-03 20:39:03 +0000804 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000805 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
806 if (!RD)
807 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000808
Douglas Gregor88d292c2010-05-13 16:44:06 +0000809 // If we are throwing a polymorphic class type or pointer thereof,
810 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000811 MarkVTableUsed(ThrowLoc, RD);
812
Eli Friedman36ebbec2010-10-12 20:32:36 +0000813 // If a pointer is thrown, the referenced object will not be destroyed.
814 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000815 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000816
Richard Smitheec915d62012-02-18 04:13:32 +0000817 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000818 if (!RD->hasIrrelevantDestructor()) {
819 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
820 MarkFunctionReferenced(E->getExprLoc(), Destructor);
821 CheckDestructorAccess(E->getExprLoc(), Destructor,
822 PDiag(diag::err_access_dtor_exception) << Ty);
823 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000824 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000825 }
826 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000827
David Majnemerdfa6d202015-03-11 18:36:39 +0000828 // The MSVC ABI creates a list of all types which can catch the exception
829 // object. This list also references the appropriate copy constructor to call
830 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000831 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000832 // We are only interested in the public, unambiguous bases contained within
833 // the exception object. Bases which are ambiguous or otherwise
834 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000835 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
836 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000837
David Majnemere7a818f2015-03-06 18:53:55 +0000838 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000839 // Attempt to lookup the copy constructor. Various pieces of machinery
840 // will spring into action, like template instantiation, which means this
841 // cannot be a simple walk of the class's decls. Instead, we must perform
842 // lookup and overload resolution.
843 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
844 if (!CD)
845 continue;
846
847 // Mark the constructor referenced as it is used by this throw expression.
848 MarkFunctionReferenced(E->getExprLoc(), CD);
849
850 // Skip this copy constructor if it is trivial, we don't need to record it
851 // in the catchable type data.
852 if (CD->isTrivial())
853 continue;
854
855 // The copy constructor is non-trivial, create a mapping from this class
856 // type to this constructor.
857 // N.B. The selection of copy constructor is not sensitive to this
858 // particular throw-site. Lookup will be performed at the catch-site to
859 // ensure that the copy constructor is, in fact, accessible (via
860 // friendship or any other means).
861 Context.addCopyConstructorForExceptionObject(Subobject, CD);
862
863 // We don't keep the instantiated default argument expressions around so
864 // we must rebuild them here.
865 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
866 // Skip any default arguments that we've already instantiated.
867 if (Context.getDefaultArgExprForConstructor(CD, I))
868 continue;
869
870 Expr *DefaultArg =
871 BuildCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)).get();
872 Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
David Majnemere7a818f2015-03-06 18:53:55 +0000873 }
874 }
875 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000876
David Majnemerba3e5ec2015-03-13 18:26:17 +0000877 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000878}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000879
Faisal Vali67b04462016-06-11 16:41:54 +0000880static QualType adjustCVQualifiersForCXXThisWithinLambda(
881 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
882 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
883
884 QualType ClassType = ThisTy->getPointeeType();
885 LambdaScopeInfo *CurLSI = nullptr;
886 DeclContext *CurDC = CurSemaContext;
887
888 // Iterate through the stack of lambdas starting from the innermost lambda to
889 // the outermost lambda, checking if '*this' is ever captured by copy - since
890 // that could change the cv-qualifiers of the '*this' object.
891 // The object referred to by '*this' starts out with the cv-qualifiers of its
892 // member function. We then start with the innermost lambda and iterate
893 // outward checking to see if any lambda performs a by-copy capture of '*this'
894 // - and if so, any nested lambda must respect the 'constness' of that
895 // capturing lamdbda's call operator.
896 //
897
898 // The issue is that we cannot rely entirely on the FunctionScopeInfo stack
899 // since ScopeInfos are pushed on during parsing and treetransforming. But
900 // since a generic lambda's call operator can be instantiated anywhere (even
901 // end of the TU) we need to be able to examine its enclosing lambdas and so
902 // we use the DeclContext to get a hold of the closure-class and query it for
903 // capture information. The reason we don't just resort to always using the
904 // DeclContext chain is that it is only mature for lambda expressions
905 // enclosing generic lambda's call operators that are being instantiated.
906
907 for (int I = FunctionScopes.size();
908 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]);
909 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
910 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000911
912 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +0000913 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000914
Faisal Vali67b04462016-06-11 16:41:54 +0000915 auto C = CurLSI->getCXXThisCapture();
916
917 if (C.isCopyCapture()) {
918 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
919 if (CurLSI->CallOperator->isConst())
920 ClassType.addConst();
921 return ASTCtx.getPointerType(ClassType);
922 }
923 }
924 // We've run out of ScopeInfos but check if CurDC is a lambda (which can
925 // happen during instantiation of generic lambdas)
926 if (isLambdaCallOperator(CurDC)) {
927 assert(CurLSI);
928 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator));
929 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +0000930
Faisal Vali67b04462016-06-11 16:41:54 +0000931 auto IsThisCaptured =
932 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
933 IsConst = false;
934 IsByCopy = false;
935 for (auto &&C : Closure->captures()) {
936 if (C.capturesThis()) {
937 if (C.getCaptureKind() == LCK_StarThis)
938 IsByCopy = true;
939 if (Closure->getLambdaCallOperator()->isConst())
940 IsConst = true;
941 return true;
942 }
943 }
944 return false;
945 };
946
947 bool IsByCopyCapture = false;
948 bool IsConstCapture = false;
949 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
950 while (Closure &&
951 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
952 if (IsByCopyCapture) {
953 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
954 if (IsConstCapture)
955 ClassType.addConst();
956 return ASTCtx.getPointerType(ClassType);
957 }
958 Closure = isLambdaCallOperator(Closure->getParent())
959 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
960 : nullptr;
961 }
962 }
963 return ASTCtx.getPointerType(ClassType);
964}
965
Eli Friedman73a04092012-01-07 04:59:52 +0000966QualType Sema::getCurrentThisType() {
967 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +0000968 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000969
Richard Smith938f40b2011-06-11 17:19:42 +0000970 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
971 if (method && method->isInstance())
972 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000973 }
Faisal Validc6b5962016-03-21 09:25:37 +0000974
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000975 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
976 !ActiveTemplateInstantiations.empty()) {
Faisal Validc6b5962016-03-21 09:25:37 +0000977
Erik Pilkington3cdc3172016-07-27 18:25:10 +0000978 assert(isa<CXXRecordDecl>(DC) &&
979 "Trying to get 'this' type from static method?");
980
981 // This is a lambda call operator that is being instantiated as a default
982 // initializer. DC must point to the enclosing class type, so we can recover
983 // the 'this' type from it.
984
985 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
986 // There are no cv-qualifiers for 'this' within default initializers,
987 // per [expr.prim.general]p4.
988 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +0000989 }
Faisal Vali67b04462016-06-11 16:41:54 +0000990
991 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
992 // might need to be adjusted if the lambda or any of its enclosing lambda's
993 // captures '*this' by copy.
994 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
995 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
996 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000997 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +0000998}
999
Simon Pilgrim75c26882016-09-30 14:25:09 +00001000Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001001 Decl *ContextDecl,
1002 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001003 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001004 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1005{
1006 if (!Enabled || !ContextDecl)
1007 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001008
1009 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001010 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1011 Record = Template->getTemplatedDecl();
1012 else
1013 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001014
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001015 // We care only for CVR qualifiers here, so cut everything else.
1016 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001017 S.CXXThisTypeOverride
1018 = S.Context.getPointerType(
1019 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001020
Douglas Gregor3024f072012-04-16 07:05:22 +00001021 this->Enabled = true;
1022}
1023
1024
1025Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1026 if (Enabled) {
1027 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1028 }
1029}
1030
Faisal Validc6b5962016-03-21 09:25:37 +00001031static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1032 QualType ThisTy, SourceLocation Loc,
1033 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001034
Faisal Vali67b04462016-06-11 16:41:54 +00001035 QualType AdjustedThisTy = ThisTy;
1036 // The type of the corresponding data member (not a 'this' pointer if 'by
1037 // copy').
1038 QualType CaptureThisFieldTy = ThisTy;
1039 if (ByCopy) {
1040 // If we are capturing the object referred to by '*this' by copy, ignore any
1041 // cv qualifiers inherited from the type of the member function for the type
1042 // of the closure-type's corresponding data member and any use of 'this'.
1043 CaptureThisFieldTy = ThisTy->getPointeeType();
1044 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1045 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1046 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001047
Faisal Vali67b04462016-06-11 16:41:54 +00001048 FieldDecl *Field = FieldDecl::Create(
1049 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1050 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1051 ICIS_NoInit);
1052
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001053 Field->setImplicit(true);
1054 Field->setAccess(AS_private);
1055 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001056 Expr *This =
1057 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001058 if (ByCopy) {
1059 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1060 UO_Deref,
1061 This).get();
1062 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001063 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001064 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1065 InitializationSequence Init(S, Entity, InitKind, StarThis);
1066 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1067 if (ER.isInvalid()) return nullptr;
1068 return ER.get();
1069 }
1070 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001071}
1072
Simon Pilgrim75c26882016-09-30 14:25:09 +00001073bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001074 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1075 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001076 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001077 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001078 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001079
Faisal Validc6b5962016-03-21 09:25:37 +00001080 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001081
Faisal Valia17d19f2013-11-07 05:17:06 +00001082 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
Faisal Validc6b5962016-03-21 09:25:37 +00001083 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001084
Simon Pilgrim75c26882016-09-30 14:25:09 +00001085 // Check that we can capture the *enclosing object* (referred to by '*this')
1086 // by the capturing-entity/closure (lambda/block/etc) at
1087 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1088
1089 // Note: The *enclosing object* can only be captured by-value by a
1090 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001091 // [*this] { ... }.
1092 // Every other capture of the *enclosing object* results in its by-reference
1093 // capture.
1094
1095 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1096 // stack), we can capture the *enclosing object* only if:
1097 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1098 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001099 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001100 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001101 // -- or, there is some enclosing closure 'E' that has already captured the
1102 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001103 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001104 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001105 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001106
1107
Faisal Validc6b5962016-03-21 09:25:37 +00001108 unsigned NumCapturingClosures = 0;
Faisal Valia17d19f2013-11-07 05:17:06 +00001109 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001110 if (CapturingScopeInfo *CSI =
1111 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1112 if (CSI->CXXThisCaptureIndex != 0) {
1113 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman73a04092012-01-07 04:59:52 +00001114 break;
1115 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001116 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1117 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1118 // This context can't implicitly capture 'this'; fail out.
1119 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001120 Diag(Loc, diag::err_this_capture)
1121 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001122 return true;
1123 }
Eli Friedman20139d32012-01-11 02:36:31 +00001124 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001125 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001126 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001127 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001128 (Explicit && idx == MaxFunctionScopesIndex)) {
1129 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1130 // iteration through can be an explicit capture, all enclosing closures,
1131 // if any, must perform implicit captures.
1132
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001133 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001134 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001135 continue;
1136 }
Eli Friedman20139d32012-01-11 02:36:31 +00001137 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001138 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001139 Diag(Loc, diag::err_this_capture)
1140 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001141 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001142 }
Eli Friedman73a04092012-01-07 04:59:52 +00001143 break;
1144 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001145 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001146
1147 // If we got here, then the closure at MaxFunctionScopesIndex on the
1148 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1149 // (including implicit by-reference captures in any enclosing closures).
1150
1151 // In the loop below, respect the ByCopy flag only for the closure requesting
1152 // the capture (i.e. first iteration through the loop below). Ignore it for
1153 // all enclosing closure's upto NumCapturingClosures (since they must be
1154 // implicitly capturing the *enclosing object* by reference (see loop
1155 // above)).
1156 assert((!ByCopy ||
1157 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1158 "Only a lambda can capture the enclosing object (referred to by "
1159 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001160 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1161 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001162 QualType ThisTy = getCurrentThisType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00001163 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
Faisal Validc6b5962016-03-21 09:25:37 +00001164 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001165 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001166 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001167
Faisal Validc6b5962016-03-21 09:25:37 +00001168 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1169 // For lambda expressions, build a field and an initializing expression,
1170 // and capture the *enclosing object* by copy only if this is the first
1171 // iteration.
1172 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1173 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001174
Faisal Validc6b5962016-03-21 09:25:37 +00001175 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001176 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001177 ThisExpr =
1178 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1179 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001180
Faisal Validc6b5962016-03-21 09:25:37 +00001181 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001182 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001183 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001184 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001185}
1186
Richard Smith938f40b2011-06-11 17:19:42 +00001187ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001188 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1189 /// is a non-lvalue expression whose value is the address of the object for
1190 /// which the function is called.
1191
Douglas Gregor09deffa2011-10-18 16:47:30 +00001192 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001193 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001194
Eli Friedman73a04092012-01-07 04:59:52 +00001195 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001196 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001197}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001198
Douglas Gregor3024f072012-04-16 07:05:22 +00001199bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1200 // If we're outside the body of a member function, then we'll have a specified
1201 // type for 'this'.
1202 if (CXXThisTypeOverride.isNull())
1203 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001204
Douglas Gregor3024f072012-04-16 07:05:22 +00001205 // Determine whether we're looking into a class that's currently being
1206 // defined.
1207 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1208 return Class && Class->isBeingDefined();
1209}
1210
John McCalldadc5752010-08-24 06:29:42 +00001211ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001212Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001213 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001214 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001215 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001216 if (!TypeRep)
1217 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001218
John McCall97513962010-01-15 18:39:57 +00001219 TypeSourceInfo *TInfo;
1220 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1221 if (!TInfo)
1222 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001223
Richard Smithb8c414c2016-06-30 20:24:30 +00001224 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1225 // Avoid creating a non-type-dependent expression that contains typos.
1226 // Non-type-dependent expressions are liable to be discarded without
1227 // checking for embedded typos.
1228 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1229 !Result.get()->isTypeDependent())
1230 Result = CorrectDelayedTyposInExpr(Result.get());
1231 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001232}
1233
1234/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1235/// Can be interpreted either as function-style casting ("int(x)")
1236/// or class type construction ("ClassType(x,y,z)")
1237/// or creation of a value-initialized type ("int()").
1238ExprResult
1239Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1240 SourceLocation LParenLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001241 MultiExprArg Exprs,
Douglas Gregor2b88c112010-09-08 00:15:04 +00001242 SourceLocation RParenLoc) {
1243 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001244 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001245
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001246 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001247 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1248 RParenLoc);
Douglas Gregor0950e412009-03-13 21:01:28 +00001249 }
1250
Sebastian Redld74dd492012-02-12 18:41:05 +00001251 bool ListInitialization = LParenLoc.isInvalid();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001252 assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
Sebastian Redld74dd492012-02-12 18:41:05 +00001253 && "List initialization must have initializer list as expression.");
1254 SourceRange FullRange = SourceRange(TyBeginLoc,
1255 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1256
Douglas Gregordd04d332009-01-16 18:33:17 +00001257 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001258 // If the expression list is a single expression, the type conversion
1259 // expression is equivalent (in definedness, and if defined in meaning) to the
1260 // corresponding cast expression.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001261 if (Exprs.size() == 1 && !ListInitialization) {
John McCallb50451a2011-10-05 07:41:44 +00001262 Expr *Arg = Exprs[0];
John McCallb50451a2011-10-05 07:41:44 +00001263 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001264 }
1265
David Majnemer7eddcff2015-09-14 07:05:00 +00001266 // C++14 [expr.type.conv]p2: The expression T(), where T is a
1267 // simple-type-specifier or typename-specifier for a non-array complete
1268 // object type or the (possibly cv-qualified) void type, creates a prvalue
1269 // of the specified type, whose value is that produced by value-initializing
1270 // an object of type T.
Eli Friedman576cbd02012-02-29 00:00:28 +00001271 QualType ElemTy = Ty;
1272 if (Ty->isArrayType()) {
1273 if (!ListInitialization)
1274 return ExprError(Diag(TyBeginLoc,
1275 diag::err_value_init_for_array_type) << FullRange);
1276 ElemTy = Context.getBaseElementType(Ty);
1277 }
1278
David Majnemer7eddcff2015-09-14 07:05:00 +00001279 if (!ListInitialization && Ty->isFunctionType())
1280 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_function_type)
1281 << FullRange);
1282
Eli Friedman576cbd02012-02-29 00:00:28 +00001283 if (!Ty->isVoidType() &&
1284 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001285 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001286 return ExprError();
1287
1288 if (RequireNonAbstractType(TyBeginLoc, Ty,
1289 diag::err_allocation_of_abstract_type))
1290 return ExprError();
1291
Douglas Gregor8ec51732010-09-08 21:40:08 +00001292 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001293 InitializationKind Kind =
1294 Exprs.size() ? ListInitialization
1295 ? InitializationKind::CreateDirectList(TyBeginLoc)
1296 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
1297 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1298 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1299 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001300
Richard Smith90061902013-09-23 02:20:00 +00001301 if (Result.isInvalid() || !ListInitialization)
1302 return Result;
1303
1304 Expr *Inner = Result.get();
1305 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1306 Inner = BTE->getSubExpr();
Richard Smith1ae689c2015-01-28 22:06:01 +00001307 if (!isa<CXXTemporaryObjectExpr>(Inner)) {
1308 // If we created a CXXTemporaryObjectExpr, that node also represents the
1309 // functional cast. Otherwise, create an explicit cast to represent
1310 // the syntactic form of a functional-style cast that was used here.
1311 //
1312 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1313 // would give a more consistent AST representation than using a
1314 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1315 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001316 QualType ResultType = Result.get()->getType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001317 Result = CXXFunctionalCastExpr::Create(
Richard Smith90061902013-09-23 02:20:00 +00001318 Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001319 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
Sebastian Redl2b80af42012-02-13 19:55:43 +00001320 }
1321
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001322 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001323}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001324
Richard Smithb2f0f052016-10-10 18:54:32 +00001325/// \brief Determine whether the given function is a non-placement
1326/// deallocation function.
1327static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1328 if (FD->isInvalidDecl())
1329 return false;
1330
1331 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1332 return Method->isUsualDeallocationFunction();
1333
1334 if (FD->getOverloadedOperator() != OO_Delete &&
1335 FD->getOverloadedOperator() != OO_Array_Delete)
1336 return false;
1337
1338 unsigned UsualParams = 1;
1339
1340 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1341 S.Context.hasSameUnqualifiedType(
1342 FD->getParamDecl(UsualParams)->getType(),
1343 S.Context.getSizeType()))
1344 ++UsualParams;
1345
1346 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1347 S.Context.hasSameUnqualifiedType(
1348 FD->getParamDecl(UsualParams)->getType(),
1349 S.Context.getTypeDeclType(S.getStdAlignValT())))
1350 ++UsualParams;
1351
1352 return UsualParams == FD->getNumParams();
1353}
1354
1355namespace {
1356 struct UsualDeallocFnInfo {
1357 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001358 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001359 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smithf75dcbe2016-10-11 00:21:10 +00001360 HasSizeT(false), HasAlignValT(false), CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001361 // A function template declaration is never a usual deallocation function.
1362 if (!FD)
1363 return;
1364 if (FD->getNumParams() == 3)
1365 HasAlignValT = HasSizeT = true;
1366 else if (FD->getNumParams() == 2) {
1367 HasSizeT = FD->getParamDecl(1)->getType()->isIntegerType();
1368 HasAlignValT = !HasSizeT;
1369 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001370
1371 // In CUDA, determine how much we'd like / dislike to call this.
1372 if (S.getLangOpts().CUDA)
1373 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1374 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001375 }
1376
1377 operator bool() const { return FD; }
1378
Richard Smithf75dcbe2016-10-11 00:21:10 +00001379 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1380 bool WantAlign) const {
1381 // C++17 [expr.delete]p10:
1382 // If the type has new-extended alignment, a function with a parameter
1383 // of type std::align_val_t is preferred; otherwise a function without
1384 // such a parameter is preferred
1385 if (HasAlignValT != Other.HasAlignValT)
1386 return HasAlignValT == WantAlign;
1387
1388 if (HasSizeT != Other.HasSizeT)
1389 return HasSizeT == WantSize;
1390
1391 // Use CUDA call preference as a tiebreaker.
1392 return CUDAPref > Other.CUDAPref;
1393 }
1394
Richard Smithb2f0f052016-10-10 18:54:32 +00001395 DeclAccessPair Found;
1396 FunctionDecl *FD;
1397 bool HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001398 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001399 };
1400}
1401
1402/// Determine whether a type has new-extended alignment. This may be called when
1403/// the type is incomplete (for a delete-expression with an incomplete pointee
1404/// type), in which case it will conservatively return false if the alignment is
1405/// not known.
1406static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1407 return S.getLangOpts().AlignedAllocation &&
1408 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1409 S.getASTContext().getTargetInfo().getNewAlign();
1410}
1411
1412/// Select the correct "usual" deallocation function to use from a selection of
1413/// deallocation functions (either global or class-scope).
1414static UsualDeallocFnInfo resolveDeallocationOverload(
1415 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1416 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1417 UsualDeallocFnInfo Best;
1418
Richard Smithb2f0f052016-10-10 18:54:32 +00001419 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001420 UsualDeallocFnInfo Info(S, I.getPair());
1421 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1422 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001423 continue;
1424
1425 if (!Best) {
1426 Best = Info;
1427 if (BestFns)
1428 BestFns->push_back(Info);
1429 continue;
1430 }
1431
Richard Smithf75dcbe2016-10-11 00:21:10 +00001432 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001433 continue;
1434
1435 // If more than one preferred function is found, all non-preferred
1436 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001437 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001438 BestFns->clear();
1439
1440 Best = Info;
1441 if (BestFns)
1442 BestFns->push_back(Info);
1443 }
1444
1445 return Best;
1446}
1447
1448/// Determine whether a given type is a class for which 'delete[]' would call
1449/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1450/// we need to store the array size (even if the type is
1451/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001452static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1453 QualType allocType) {
1454 const RecordType *record =
1455 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1456 if (!record) return false;
1457
1458 // Try to find an operator delete[] in class scope.
1459
1460 DeclarationName deleteName =
1461 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1462 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1463 S.LookupQualifiedName(ops, record->getDecl());
1464
1465 // We're just doing this for information.
1466 ops.suppressDiagnostics();
1467
1468 // Very likely: there's no operator delete[].
1469 if (ops.empty()) return false;
1470
1471 // If it's ambiguous, it should be illegal to call operator delete[]
1472 // on this thing, so it doesn't matter if we allocate extra space or not.
1473 if (ops.isAmbiguous()) return false;
1474
Richard Smithb2f0f052016-10-10 18:54:32 +00001475 // C++17 [expr.delete]p10:
1476 // If the deallocation functions have class scope, the one without a
1477 // parameter of type std::size_t is selected.
1478 auto Best = resolveDeallocationOverload(
1479 S, ops, /*WantSize*/false,
1480 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1481 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001482}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001483
Sebastian Redld74dd492012-02-12 18:41:05 +00001484/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001485///
Sebastian Redld74dd492012-02-12 18:41:05 +00001486/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001487/// @code new (memory) int[size][4] @endcode
1488/// or
1489/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001490///
1491/// \param StartLoc The first location of the expression.
1492/// \param UseGlobal True if 'new' was prefixed with '::'.
1493/// \param PlacementLParen Opening paren of the placement arguments.
1494/// \param PlacementArgs Placement new arguments.
1495/// \param PlacementRParen Closing paren of the placement arguments.
1496/// \param TypeIdParens If the type is in parens, the source range.
1497/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001498/// \param Initializer The initializing expression or initializer-list, or null
1499/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001500ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001501Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001502 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001503 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001504 Declarator &D, Expr *Initializer) {
Richard Smith74aeef52013-04-26 16:15:35 +00001505 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
Richard Smith30482bc2011-02-20 03:19:35 +00001506
Craig Topperc3ec1492014-05-26 06:22:03 +00001507 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001508 // If the specified type is an array, unwrap it and save the expression.
1509 if (D.getNumTypeObjects() > 0 &&
1510 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
James Dennettf14a6e52012-06-15 22:23:43 +00001511 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith30482bc2011-02-20 03:19:35 +00001512 if (TypeContainsAuto)
1513 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1514 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001515 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001516 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1517 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001518 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001519 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1520 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001521
Sebastian Redl351bb782008-12-02 14:43:59 +00001522 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001523 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001524 }
1525
Douglas Gregor73341c42009-09-11 00:18:58 +00001526 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001527 if (ArraySize) {
1528 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001529 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1530 break;
1531
1532 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1533 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001534 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001535 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001536 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1537 // shall be a converted constant expression (5.19) of type std::size_t
1538 // and shall evaluate to a strictly positive value.
1539 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1540 assert(IntWidth && "Builtin type of size 0?");
1541 llvm::APSInt Value(IntWidth);
1542 Array.NumElts
1543 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1544 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001545 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001546 } else {
1547 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001548 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001549 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001550 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001551 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001552 if (!Array.NumElts)
1553 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001554 }
1555 }
1556 }
1557 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001558
Craig Topperc3ec1492014-05-26 06:22:03 +00001559 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001560 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001561 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001562 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001563
Sebastian Redl6047f072012-02-16 12:22:20 +00001564 SourceRange DirectInitRange;
1565 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1566 DirectInitRange = List->getSourceRange();
1567
David Blaikie7b97aef2012-11-07 00:12:38 +00001568 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001569 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001570 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001571 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001572 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001573 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001574 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001575 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001576 DirectInitRange,
1577 Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001578 TypeContainsAuto);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001579}
1580
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001581static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1582 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001583 if (!Init)
1584 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001585 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1586 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001587 if (isa<ImplicitValueInitExpr>(Init))
1588 return true;
1589 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1590 return !CCE->isListInitialization() &&
1591 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001592 else if (Style == CXXNewExpr::ListInit) {
1593 assert(isa<InitListExpr>(Init) &&
1594 "Shouldn't create list CXXConstructExprs for arrays.");
1595 return true;
1596 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001597 return false;
1598}
1599
John McCalldadc5752010-08-24 06:29:42 +00001600ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001601Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001602 SourceLocation PlacementLParen,
1603 MultiExprArg PlacementArgs,
1604 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001605 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001606 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001607 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001608 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001609 SourceRange DirectInitRange,
1610 Expr *Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001611 bool TypeMayContainAuto) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001612 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001613 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001614
Sebastian Redl6047f072012-02-16 12:22:20 +00001615 CXXNewExpr::InitializationStyle initStyle;
1616 if (DirectInitRange.isValid()) {
1617 assert(Initializer && "Have parens but no initializer.");
1618 initStyle = CXXNewExpr::CallInit;
1619 } else if (Initializer && isa<InitListExpr>(Initializer))
1620 initStyle = CXXNewExpr::ListInit;
1621 else {
1622 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1623 isa<CXXConstructExpr>(Initializer)) &&
1624 "Initializer expression that cannot have been implicitly created.");
1625 initStyle = CXXNewExpr::NoInit;
1626 }
1627
1628 Expr **Inits = &Initializer;
1629 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001630 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1631 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1632 Inits = List->getExprs();
1633 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001634 }
1635
Richard Smith66204ec2014-03-12 17:42:45 +00001636 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00001637 if (TypeMayContainAuto && AllocType->isUndeducedType()) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001638 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001639 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1640 << AllocType << TypeRange);
Richard Smith66204ec2014-03-12 17:42:45 +00001641 if (initStyle == CXXNewExpr::ListInit ||
1642 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001643 return ExprError(Diag(Inits[0]->getLocStart(),
Richard Smith66204ec2014-03-12 17:42:45 +00001644 diag::err_auto_new_list_init)
Sebastian Redl6047f072012-02-16 12:22:20 +00001645 << AllocType << TypeRange);
1646 if (NumInits > 1) {
1647 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001648 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001649 diag::err_auto_new_ctor_multiple_expressions)
1650 << AllocType << TypeRange);
1651 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001652 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001653 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001654 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001655 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001656 << AllocType << Deduce->getType()
1657 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001658 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001659 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001660 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001661 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001662
Douglas Gregorcda95f42010-05-16 16:01:03 +00001663 // Per C++0x [expr.new]p5, the type being constructed may be a
1664 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001665 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001666 if (const ConstantArrayType *Array
1667 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001668 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1669 Context.getSizeType(),
1670 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001671 AllocType = Array->getElementType();
1672 }
1673 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001674
Douglas Gregor3999e152010-10-06 16:00:31 +00001675 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1676 return ExprError();
1677
Craig Topperc3ec1492014-05-26 06:22:03 +00001678 if (initStyle == CXXNewExpr::ListInit &&
1679 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001680 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1681 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001682 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001683 }
1684
Simon Pilgrim75c26882016-09-30 14:25:09 +00001685 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001686 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001687 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1688 AllocType->isObjCLifetimeType()) {
1689 AllocType = Context.getLifetimeQualifiedType(AllocType,
1690 AllocType->getObjCARCImplicitLifetime());
1691 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001692
John McCall31168b02011-06-15 23:02:42 +00001693 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001694
John McCall5e77d762013-04-16 07:28:30 +00001695 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1696 ExprResult result = CheckPlaceholderExpr(ArraySize);
1697 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001698 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001699 }
Richard Smith8dd34252012-02-04 07:07:42 +00001700 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1701 // integral or enumeration type with a non-negative value."
1702 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1703 // enumeration type, or a class type for which a single non-explicit
1704 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001705 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001706 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001707 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001708 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001709 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001710 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001711 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1712
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001713 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1714 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001715
Simon Pilgrim75c26882016-09-30 14:25:09 +00001716 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001717 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001718 // Diagnose the compatibility of this conversion.
1719 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1720 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001721 } else {
1722 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1723 protected:
1724 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001725
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001726 public:
1727 SizeConvertDiagnoser(Expr *ArraySize)
1728 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1729 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001730
1731 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1732 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001733 return S.Diag(Loc, diag::err_array_size_not_integral)
1734 << S.getLangOpts().CPlusPlus11 << T;
1735 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001736
1737 SemaDiagnosticBuilder diagnoseIncomplete(
1738 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001739 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1740 << T << ArraySize->getSourceRange();
1741 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001742
1743 SemaDiagnosticBuilder diagnoseExplicitConv(
1744 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001745 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1746 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001747
1748 SemaDiagnosticBuilder noteExplicitConv(
1749 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001750 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1751 << ConvTy->isEnumeralType() << ConvTy;
1752 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001753
1754 SemaDiagnosticBuilder diagnoseAmbiguous(
1755 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001756 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1757 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001758
1759 SemaDiagnosticBuilder noteAmbiguous(
1760 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001761 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1762 << ConvTy->isEnumeralType() << ConvTy;
1763 }
Richard Smithccc11812013-05-21 19:05:48 +00001764
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001765 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1766 QualType T,
1767 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001768 return S.Diag(Loc,
1769 S.getLangOpts().CPlusPlus11
1770 ? diag::warn_cxx98_compat_array_size_conversion
1771 : diag::ext_array_size_conversion)
1772 << T << ConvTy->isEnumeralType() << ConvTy;
1773 }
1774 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001775
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001776 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1777 SizeDiagnoser);
1778 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001779 if (ConvertedSize.isInvalid())
1780 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001781
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001782 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001783 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001784
Douglas Gregor0bf31402010-10-08 23:50:27 +00001785 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001786 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001787
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001788 // C++98 [expr.new]p7:
1789 // The expression in a direct-new-declarator shall have integral type
1790 // with a non-negative value.
1791 //
Richard Smith0511d232016-10-05 22:41:02 +00001792 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1793 // per CWG1464. Otherwise, if it's not a constant, we must have an
1794 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001795 if (!ArraySize->isValueDependent()) {
1796 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001797 // We've already performed any required implicit conversion to integer or
1798 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001799 // FIXME: Per CWG1464, we are required to check the value prior to
1800 // converting to size_t. This will never find a negative array size in
1801 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001802 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001803 if (Value.isSigned() && Value.isNegative()) {
1804 return ExprError(Diag(ArraySize->getLocStart(),
1805 diag::err_typecheck_negative_array_size)
1806 << ArraySize->getSourceRange());
1807 }
1808
1809 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001810 unsigned ActiveSizeBits =
1811 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00001812 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1813 return ExprError(Diag(ArraySize->getLocStart(),
1814 diag::err_array_too_large)
1815 << Value.toString(10)
1816 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001817 }
Richard Smith0511d232016-10-05 22:41:02 +00001818
1819 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00001820 } else if (TypeIdParens.isValid()) {
1821 // Can't have dynamic array size when the type-id is in parentheses.
1822 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1823 << ArraySize->getSourceRange()
1824 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1825 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001826
Douglas Gregorf2753b32010-07-13 15:54:32 +00001827 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001828 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001829 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001830
John McCall036f2f62011-05-15 07:14:44 +00001831 // Note that we do *not* convert the argument in any way. It can
1832 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001833 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001834
Craig Topperc3ec1492014-05-26 06:22:03 +00001835 FunctionDecl *OperatorNew = nullptr;
1836 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00001837 unsigned Alignment =
1838 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1839 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1840 bool PassAlignment = getLangOpts().AlignedAllocation &&
1841 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001842
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001843 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001844 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001845 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001846 SourceRange(PlacementLParen, PlacementRParen),
Richard Smithb2f0f052016-10-10 18:54:32 +00001847 UseGlobal, AllocType, ArraySize, PassAlignment,
1848 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001849 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001850
1851 // If this is an array allocation, compute whether the usual array
1852 // deallocation function for the type has a size_t parameter.
1853 bool UsualArrayDeleteWantsSize = false;
1854 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00001855 UsualArrayDeleteWantsSize =
1856 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00001857
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001858 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001859 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001860 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00001861 OperatorNew->getType()->getAs<FunctionProtoType>();
1862 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1863 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001864
Richard Smithd6f9e732014-05-13 19:56:21 +00001865 // We've already converted the placement args, just fill in any default
1866 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00001867 // argument. Skip the second parameter too if we're passing in the
1868 // alignment; we've already filled it in.
1869 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
1870 PassAlignment ? 2 : 1, PlacementArgs,
1871 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001872 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001873
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001874 if (!AllPlaceArgs.empty())
1875 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00001876
Richard Smithd6f9e732014-05-13 19:56:21 +00001877 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001878 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00001879
1880 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001881
Richard Smithb2f0f052016-10-10 18:54:32 +00001882 // Warn if the type is over-aligned and is being allocated by (unaligned)
1883 // global operator new.
1884 if (PlacementArgs.empty() && !PassAlignment &&
1885 (OperatorNew->isImplicit() ||
1886 (OperatorNew->getLocStart().isValid() &&
1887 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
1888 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00001889 Diag(StartLoc, diag::warn_overaligned_type)
1890 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00001891 << unsigned(Alignment / Context.getCharWidth())
1892 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00001893 }
1894 }
1895
Sebastian Redl6047f072012-02-16 12:22:20 +00001896 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001897 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1898 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00001899 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
1900 SourceRange InitRange(Inits[0]->getLocStart(),
1901 Inits[NumInits - 1]->getLocEnd());
1902 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1903 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001904 }
1905
Richard Smithdd2ca572012-11-26 08:32:48 +00001906 // If we can perform the initialization, and we've not already done so,
1907 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00001908 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001909 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00001910 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00001911 // The type we initialize is the complete type, including the array bound.
1912 QualType InitType;
1913 if (KnownArraySize)
1914 InitType = Context.getConstantArrayType(
1915 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
1916 *KnownArraySize),
1917 ArrayType::Normal, 0);
1918 else if (ArraySize)
1919 InitType =
1920 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
1921 else
1922 InitType = AllocType;
1923
Sebastian Redld74dd492012-02-12 18:41:05 +00001924 // C++11 [expr.new]p15:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001925 // A new-expression that creates an object of type T initializes that
1926 // object as follows:
1927 InitializationKind Kind
1928 // - If the new-initializer is omitted, the object is default-
1929 // initialized (8.5); if no initialization is performed,
1930 // the object has indeterminate value
Sebastian Redl6047f072012-02-16 12:22:20 +00001931 = initStyle == CXXNewExpr::NoInit
1932 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001933 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001934 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +00001935 : initStyle == CXXNewExpr::ListInit
1936 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1937 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1938 DirectInitRange.getBegin(),
1939 DirectInitRange.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001940
Douglas Gregor85dabae2009-12-16 01:38:02 +00001941 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001942 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00001943 InitializationSequence InitSeq(*this, Entity, Kind,
1944 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00001946 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00001947 if (FullInit.isInvalid())
1948 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001949
Sebastian Redl6047f072012-02-16 12:22:20 +00001950 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1951 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00001952 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00001953 if (CXXBindTemporaryExpr *Binder =
1954 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001955 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001956
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001957 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001958 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959
Douglas Gregor6642ca22010-02-26 05:06:18 +00001960 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00001961 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00001962 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1963 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001964 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00001965 }
1966 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00001967 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1968 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001969 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00001970 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00001971
John McCall928a2572011-07-13 20:12:57 +00001972 // C++0x [expr.new]p17:
1973 // If the new expression creates an array of objects of class type,
1974 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00001975 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1976 if (ArraySize && !BaseAllocType->isDependentType()) {
1977 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1978 if (CXXDestructorDecl *dtor = LookupDestructor(
1979 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1980 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001981 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00001982 PDiag(diag::err_access_dtor)
1983 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00001984 if (DiagnoseUseOfDecl(dtor, StartLoc))
1985 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00001986 }
John McCall928a2572011-07-13 20:12:57 +00001987 }
1988 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001989
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001990 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00001991 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001992 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
1993 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
1994 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00001995}
1996
Sebastian Redl6047f072012-02-16 12:22:20 +00001997/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00001998/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00001999bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002000 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002001 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2002 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002003 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002004 return Diag(Loc, diag::err_bad_new_type)
2005 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002006 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002007 return Diag(Loc, diag::err_bad_new_type)
2008 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002009 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002010 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002011 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002012 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002013 diag::err_allocation_of_abstract_type))
2014 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002015 else if (AllocType->isVariablyModifiedType())
2016 return Diag(Loc, diag::err_variably_modified_new_type)
2017 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00002018 else if (unsigned AddressSpace = AllocType.getAddressSpace())
2019 return Diag(Loc, diag::err_address_space_qualified_new)
2020 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002021 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002022 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2023 QualType BaseAllocType = Context.getBaseElementType(AT);
2024 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2025 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002026 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002027 << BaseAllocType;
2028 }
2029 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002030
Sebastian Redlbd150f42008-11-21 19:14:01 +00002031 return false;
2032}
2033
Richard Smithb2f0f052016-10-10 18:54:32 +00002034static bool
2035resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2036 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2037 FunctionDecl *&Operator,
2038 OverloadCandidateSet *AlignedCandidates = nullptr,
2039 Expr *AlignArg = nullptr) {
2040 OverloadCandidateSet Candidates(R.getNameLoc(),
2041 OverloadCandidateSet::CSK_Normal);
2042 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2043 Alloc != AllocEnd; ++Alloc) {
2044 // Even member operator new/delete are implicitly treated as
2045 // static, so don't use AddMemberCandidate.
2046 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2047
2048 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2049 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2050 /*ExplicitTemplateArgs=*/nullptr, Args,
2051 Candidates,
2052 /*SuppressUserConversions=*/false);
2053 continue;
2054 }
2055
2056 FunctionDecl *Fn = cast<FunctionDecl>(D);
2057 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2058 /*SuppressUserConversions=*/false);
2059 }
2060
2061 // Do the resolution.
2062 OverloadCandidateSet::iterator Best;
2063 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2064 case OR_Success: {
2065 // Got one!
2066 FunctionDecl *FnDecl = Best->Function;
2067 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2068 Best->FoundDecl) == Sema::AR_inaccessible)
2069 return true;
2070
2071 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002072 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002073 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002074
Richard Smithb2f0f052016-10-10 18:54:32 +00002075 case OR_No_Viable_Function:
2076 // C++17 [expr.new]p13:
2077 // If no matching function is found and the allocated object type has
2078 // new-extended alignment, the alignment argument is removed from the
2079 // argument list, and overload resolution is performed again.
2080 if (PassAlignment) {
2081 PassAlignment = false;
2082 AlignArg = Args[1];
2083 Args.erase(Args.begin() + 1);
2084 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2085 Operator, &Candidates, AlignArg);
2086 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002087
Richard Smithb2f0f052016-10-10 18:54:32 +00002088 // MSVC will fall back on trying to find a matching global operator new
2089 // if operator new[] cannot be found. Also, MSVC will leak by not
2090 // generating a call to operator delete or operator delete[], but we
2091 // will not replicate that bug.
2092 // FIXME: Find out how this interacts with the std::align_val_t fallback
2093 // once MSVC implements it.
2094 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2095 S.Context.getLangOpts().MSVCCompat) {
2096 R.clear();
2097 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2098 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2099 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2100 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2101 Operator, nullptr);
2102 }
Richard Smith1cdec012013-09-29 04:40:38 +00002103
Richard Smithb2f0f052016-10-10 18:54:32 +00002104 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2105 << R.getLookupName() << Range;
2106
2107 // If we have aligned candidates, only note the align_val_t candidates
2108 // from AlignedCandidates and the non-align_val_t candidates from
2109 // Candidates.
2110 if (AlignedCandidates) {
2111 auto IsAligned = [](OverloadCandidate &C) {
2112 return C.Function->getNumParams() > 1 &&
2113 C.Function->getParamDecl(1)->getType()->isAlignValT();
2114 };
2115 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2116
2117 // This was an overaligned allocation, so list the aligned candidates
2118 // first.
2119 Args.insert(Args.begin() + 1, AlignArg);
2120 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2121 R.getNameLoc(), IsAligned);
2122 Args.erase(Args.begin() + 1);
2123 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2124 IsUnaligned);
2125 } else {
2126 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2127 }
Richard Smith1cdec012013-09-29 04:40:38 +00002128 return true;
2129
Richard Smithb2f0f052016-10-10 18:54:32 +00002130 case OR_Ambiguous:
2131 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2132 << R.getLookupName() << Range;
2133 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2134 return true;
2135
2136 case OR_Deleted: {
2137 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2138 << Best->Function->isDeleted()
2139 << R.getLookupName()
2140 << S.getDeletedOrUnavailableSuffix(Best->Function)
2141 << Range;
2142 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2143 return true;
2144 }
2145 }
2146 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002147}
2148
Richard Smithb2f0f052016-10-10 18:54:32 +00002149
Sebastian Redlfaf68082008-12-03 20:26:15 +00002150/// FindAllocationFunctions - Finds the overloads of operator new and delete
2151/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002152bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2153 bool UseGlobal, QualType AllocType,
Richard Smithb2f0f052016-10-10 18:54:32 +00002154 bool IsArray, bool &PassAlignment,
2155 MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002156 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00002157 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002158 // --- Choosing an allocation function ---
2159 // C++ 5.3.4p8 - 14 & 18
2160 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2161 // in the scope of the allocated class.
2162 // 2) If an array size is given, look for operator new[], else look for
2163 // operator new.
2164 // 3) The first argument is always size_t. Append the arguments from the
2165 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002166
Richard Smithb2f0f052016-10-10 18:54:32 +00002167 SmallVector<Expr*, 8> AllocArgs;
2168 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2169
2170 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002171 // FIXME: Should the Sema create the expression and embed it in the syntax
2172 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002173 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002174 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002175 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002176 Context.getSizeType(),
2177 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002178 AllocArgs.push_back(&Size);
2179
2180 QualType AlignValT = Context.VoidTy;
2181 if (PassAlignment) {
2182 DeclareGlobalNewDelete();
2183 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2184 }
2185 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2186 if (PassAlignment)
2187 AllocArgs.push_back(&Align);
2188
2189 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002190
Douglas Gregor6642ca22010-02-26 05:06:18 +00002191 // C++ [expr.new]p8:
2192 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002193 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002194 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002195 // type, the allocation function's name is operator new[] and the
2196 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002197 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002198 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002199
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002200 QualType AllocElemType = Context.getBaseElementType(AllocType);
2201
Richard Smithb2f0f052016-10-10 18:54:32 +00002202 // Find the allocation function.
2203 {
2204 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2205
2206 // C++1z [expr.new]p9:
2207 // If the new-expression begins with a unary :: operator, the allocation
2208 // function's name is looked up in the global scope. Otherwise, if the
2209 // allocated type is a class type T or array thereof, the allocation
2210 // function's name is looked up in the scope of T.
2211 if (AllocElemType->isRecordType() && !UseGlobal)
2212 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2213
2214 // We can see ambiguity here if the allocation function is found in
2215 // multiple base classes.
2216 if (R.isAmbiguous())
2217 return true;
2218
2219 // If this lookup fails to find the name, or if the allocated type is not
2220 // a class type, the allocation function's name is looked up in the
2221 // global scope.
2222 if (R.empty())
2223 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2224
2225 assert(!R.empty() && "implicitly declared allocation functions not found");
2226 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2227
2228 // We do our own custom access checks below.
2229 R.suppressDiagnostics();
2230
2231 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2232 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002233 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002234 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002235
Richard Smithb2f0f052016-10-10 18:54:32 +00002236 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002237 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002238 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002239 return false;
2240 }
2241
Richard Smithb2f0f052016-10-10 18:54:32 +00002242 // Note, the name of OperatorNew might have been changed from array to
2243 // non-array by resolveAllocationOverload.
2244 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2245 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2246 ? OO_Array_Delete
2247 : OO_Delete);
2248
Douglas Gregor6642ca22010-02-26 05:06:18 +00002249 // C++ [expr.new]p19:
2250 //
2251 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002252 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002253 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002254 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002255 // the scope of T. If this lookup fails to find the name, or if
2256 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002257 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002258 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002259 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002260 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002261 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002262 LookupQualifiedName(FoundDelete, RD);
2263 }
John McCallfb6f5262010-03-18 08:19:33 +00002264 if (FoundDelete.isAmbiguous())
2265 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002266
Richard Smithb2f0f052016-10-10 18:54:32 +00002267 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002268 if (FoundDelete.empty()) {
2269 DeclareGlobalNewDelete();
2270 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2271 }
2272
2273 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002274
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002275 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002276
John McCalld3be2c82010-09-14 21:34:24 +00002277 // Whether we're looking for a placement operator delete is dictated
2278 // by whether we selected a placement operator new, not by whether
2279 // we had explicit placement arguments. This matters for things like
2280 // struct A { void *operator new(size_t, int = 0); ... };
2281 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002282 //
2283 // We don't have any definition for what a "placement allocation function"
2284 // is, but we assume it's any allocation function whose
2285 // parameter-declaration-clause is anything other than (size_t).
2286 //
2287 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2288 // This affects whether an exception from the constructor of an overaligned
2289 // type uses the sized or non-sized form of aligned operator delete.
2290 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2291 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002292
2293 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002294 // C++ [expr.new]p20:
2295 // A declaration of a placement deallocation function matches the
2296 // declaration of a placement allocation function if it has the
2297 // same number of parameters and, after parameter transformations
2298 // (8.3.5), all parameter types except the first are
2299 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002300 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002301 // To perform this comparison, we compute the function type that
2302 // the deallocation function should have, and use that type both
2303 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00002304 //
2305 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002306 QualType ExpectedFunctionType;
2307 {
2308 const FunctionProtoType *Proto
2309 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002310
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002311 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002312 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002313 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2314 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002315
John McCalldb40c7f2010-12-14 08:05:40 +00002316 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002317 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002318 EPI.Variadic = Proto->isVariadic();
Richard Smithb2f0f052016-10-10 18:54:32 +00002319 EPI.ExceptionSpec.Type = EST_BasicNoexcept;
John McCalldb40c7f2010-12-14 08:05:40 +00002320
Douglas Gregor6642ca22010-02-26 05:06:18 +00002321 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002322 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002323 }
2324
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002325 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002326 DEnd = FoundDelete.end();
2327 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002328 FunctionDecl *Fn = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002329 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6642ca22010-02-26 05:06:18 +00002330 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2331 // Perform template argument deduction to try to match the
2332 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002333 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002334 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2335 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002336 continue;
2337 } else
2338 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2339
2340 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002341 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002342 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002343
Richard Smithb2f0f052016-10-10 18:54:32 +00002344 if (getLangOpts().CUDA)
2345 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2346 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002347 // C++1y [expr.new]p22:
2348 // For a non-placement allocation function, the normal deallocation
2349 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002350 //
2351 // Per [expr.delete]p10, this lookup prefers a member operator delete
2352 // without a size_t argument, but prefers a non-member operator delete
2353 // with a size_t where possible (which it always is in this case).
2354 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2355 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2356 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2357 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2358 &BestDeallocFns);
2359 if (Selected)
2360 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2361 else {
2362 // If we failed to select an operator, all remaining functions are viable
2363 // but ambiguous.
2364 for (auto Fn : BestDeallocFns)
2365 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002366 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002367 }
2368
2369 // C++ [expr.new]p20:
2370 // [...] If the lookup finds a single matching deallocation
2371 // function, that function will be called; otherwise, no
2372 // deallocation function will be called.
2373 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002374 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002375
Richard Smithb2f0f052016-10-10 18:54:32 +00002376 // C++1z [expr.new]p23:
2377 // If the lookup finds a usual deallocation function (3.7.4.2)
2378 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002379 // as a placement deallocation function, would have been
2380 // selected as a match for the allocation function, the program
2381 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002382 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002383 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002384 UsualDeallocFnInfo Info(*this,
2385 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002386 // Core issue, per mail to core reflector, 2016-10-09:
2387 // If this is a member operator delete, and there is a corresponding
2388 // non-sized member operator delete, this isn't /really/ a sized
2389 // deallocation function, it just happens to have a size_t parameter.
2390 bool IsSizedDelete = Info.HasSizeT;
2391 if (IsSizedDelete && !FoundGlobalDelete) {
2392 auto NonSizedDelete =
2393 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2394 /*WantAlign*/Info.HasAlignValT);
2395 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2396 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2397 IsSizedDelete = false;
2398 }
2399
2400 if (IsSizedDelete) {
2401 SourceRange R = PlaceArgs.empty()
2402 ? SourceRange()
2403 : SourceRange(PlaceArgs.front()->getLocStart(),
2404 PlaceArgs.back()->getLocEnd());
2405 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2406 if (!OperatorDelete->isImplicit())
2407 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2408 << DeleteName;
2409 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002410 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002411
2412 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2413 Matches[0].first);
2414 } else if (!Matches.empty()) {
2415 // We found multiple suitable operators. Per [expr.new]p20, that means we
2416 // call no 'operator delete' function, but we should at least warn the user.
2417 // FIXME: Suppress this warning if the construction cannot throw.
2418 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2419 << DeleteName << AllocElemType;
2420
2421 for (auto &Match : Matches)
2422 Diag(Match.second->getLocation(),
2423 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002424 }
2425
Sebastian Redlfaf68082008-12-03 20:26:15 +00002426 return false;
2427}
2428
2429/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2430/// delete. These are:
2431/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002432/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002433/// void* operator new(std::size_t) throw(std::bad_alloc);
2434/// void* operator new[](std::size_t) throw(std::bad_alloc);
2435/// void operator delete(void *) throw();
2436/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002437/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002438/// void* operator new(std::size_t);
2439/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002440/// void operator delete(void *) noexcept;
2441/// void operator delete[](void *) noexcept;
2442/// // C++1y:
2443/// void* operator new(std::size_t);
2444/// void* operator new[](std::size_t);
2445/// void operator delete(void *) noexcept;
2446/// void operator delete[](void *) noexcept;
2447/// void operator delete(void *, std::size_t) noexcept;
2448/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002449/// @endcode
2450/// Note that the placement and nothrow forms of new are *not* implicitly
2451/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002452void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002453 if (GlobalNewDeleteDeclared)
2454 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002455
Douglas Gregor87f54062009-09-15 22:30:29 +00002456 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002457 // [...] The following allocation and deallocation functions (18.4) are
2458 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002459 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002460 //
Sebastian Redl37588092011-03-14 18:08:30 +00002461 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002462 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002463 // void* operator new[](std::size_t) throw(std::bad_alloc);
2464 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002465 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002466 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002467 // void* operator new(std::size_t);
2468 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002469 // void operator delete(void*) noexcept;
2470 // void operator delete[](void*) noexcept;
2471 // C++1y:
2472 // void* operator new(std::size_t);
2473 // void* operator new[](std::size_t);
2474 // void operator delete(void*) noexcept;
2475 // void operator delete[](void*) noexcept;
2476 // void operator delete(void*, std::size_t) noexcept;
2477 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002478 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002479 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002480 // new, operator new[], operator delete, operator delete[].
2481 //
2482 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2483 // "std" or "bad_alloc" as necessary to form the exception specification.
2484 // However, we do not make these implicit declarations visible to name
2485 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002486 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002487 // The "std::bad_alloc" class has not yet been declared, so build it
2488 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002489 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2490 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002491 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002492 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002493 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002494 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002495 }
Richard Smith59139022016-09-30 22:41:36 +00002496 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002497 // The "std::align_val_t" enum class has not yet been declared, so build it
2498 // implicitly.
2499 auto *AlignValT = EnumDecl::Create(
2500 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2501 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2502 AlignValT->setIntegerType(Context.getSizeType());
2503 AlignValT->setPromotionType(Context.getSizeType());
2504 AlignValT->setImplicit(true);
2505 StdAlignValT = AlignValT;
2506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002507
Sebastian Redlfaf68082008-12-03 20:26:15 +00002508 GlobalNewDeleteDeclared = true;
2509
2510 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2511 QualType SizeT = Context.getSizeType();
2512
Richard Smith96269c52016-09-29 22:49:46 +00002513 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2514 QualType Return, QualType Param) {
2515 llvm::SmallVector<QualType, 3> Params;
2516 Params.push_back(Param);
2517
2518 // Create up to four variants of the function (sized/aligned).
2519 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2520 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002521 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002522
2523 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2524 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2525 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002526 if (Sized)
2527 Params.push_back(SizeT);
2528
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002529 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002530 if (Aligned)
2531 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2532
2533 DeclareGlobalAllocationFunction(
2534 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2535
2536 if (Aligned)
2537 Params.pop_back();
2538 }
2539 }
2540 };
2541
2542 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2543 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2544 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2545 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002546}
2547
2548/// DeclareGlobalAllocationFunction - Declares a single implicit global
2549/// allocation function if it doesn't already exist.
2550void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002551 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002552 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002553 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2554
2555 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002556 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2557 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2558 Alloc != AllocEnd; ++Alloc) {
2559 // Only look at non-template functions, as it is the predefined,
2560 // non-templated allocation function we are trying to declare here.
2561 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002562 if (Func->getNumParams() == Params.size()) {
2563 llvm::SmallVector<QualType, 3> FuncParams;
2564 for (auto *P : Func->parameters())
2565 FuncParams.push_back(
2566 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2567 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002568 // Make the function visible to name lookup, even if we found it in
2569 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002570 // allocation function, or is suppressing that function.
2571 Func->setHidden(false);
Chandler Carruth93538422010-02-03 11:02:14 +00002572 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002573 }
Chandler Carruth93538422010-02-03 11:02:14 +00002574 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002575 }
2576 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002577
Richard Smithc015bc22014-02-07 22:39:53 +00002578 FunctionProtoType::ExtProtoInfo EPI;
2579
Richard Smithf8b417c2014-02-08 00:42:45 +00002580 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002581 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002582 = (Name.getCXXOverloadedOperator() == OO_New ||
2583 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002584 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002585 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002586 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002587 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002588 EPI.ExceptionSpec.Type = EST_Dynamic;
2589 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002590 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002591 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002592 EPI.ExceptionSpec =
2593 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002595
Richard Smith96269c52016-09-29 22:49:46 +00002596 QualType FnType = Context.getFunctionType(Return, Params, EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002597 FunctionDecl *Alloc =
Abramo Bagnaradff19302011-03-08 08:55:46 +00002598 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
2599 SourceLocation(), Name,
Craig Topperc3ec1492014-05-26 06:22:03 +00002600 FnType, /*TInfo=*/nullptr, SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002601 Alloc->setImplicit();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002602
Larisse Voufo404e1422015-02-04 02:34:32 +00002603 // Implicit sized deallocation functions always have default visibility.
2604 Alloc->addAttr(VisibilityAttr::CreateImplicit(Context,
2605 VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002606
Richard Smith96269c52016-09-29 22:49:46 +00002607 llvm::SmallVector<ParmVarDecl*, 3> ParamDecls;
2608 for (QualType T : Params) {
2609 ParamDecls.push_back(
2610 ParmVarDecl::Create(Context, Alloc, SourceLocation(), SourceLocation(),
2611 nullptr, T, /*TInfo=*/nullptr, SC_None, nullptr));
2612 ParamDecls.back()->setImplicit();
Richard Smithbdd14642014-02-04 01:14:30 +00002613 }
Richard Smith96269c52016-09-29 22:49:46 +00002614 Alloc->setParams(ParamDecls);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002615
John McCallcc14d1f2010-08-24 08:50:51 +00002616 Context.getTranslationUnitDecl()->addDecl(Alloc);
Richard Smithdebcd502014-05-16 02:14:42 +00002617 IdResolver.tryAddTopLevelDecl(Alloc, Name);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002618}
2619
Richard Smith1cdec012013-09-29 04:40:38 +00002620FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2621 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002622 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002623 DeclarationName Name) {
2624 DeclareGlobalNewDelete();
2625
2626 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2627 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2628
Richard Smithb2f0f052016-10-10 18:54:32 +00002629 // FIXME: It's possible for this to result in ambiguity, through a
2630 // user-declared variadic operator delete or the enable_if attribute. We
2631 // should probably not consider those cases to be usual deallocation
2632 // functions. But for now we just make an arbitrary choice in that case.
2633 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2634 Overaligned);
2635 assert(Result.FD && "operator delete missing from global scope?");
2636 return Result.FD;
2637}
Richard Smith1cdec012013-09-29 04:40:38 +00002638
Richard Smithb2f0f052016-10-10 18:54:32 +00002639FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2640 CXXRecordDecl *RD) {
2641 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002642
Richard Smithb2f0f052016-10-10 18:54:32 +00002643 FunctionDecl *OperatorDelete = nullptr;
2644 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2645 return nullptr;
2646 if (OperatorDelete)
2647 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002648
Richard Smithb2f0f052016-10-10 18:54:32 +00002649 // If there's no class-specific operator delete, look up the global
2650 // non-array delete.
2651 return FindUsualDeallocationFunction(
2652 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2653 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002654}
2655
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002656bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2657 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002658 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002659 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002660 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002661 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002662
John McCall27b18f82009-11-17 02:14:36 +00002663 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002664 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002665
Chandler Carruthb6f99172010-06-28 00:30:51 +00002666 Found.suppressDiagnostics();
2667
Richard Smithb2f0f052016-10-10 18:54:32 +00002668 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002669
Richard Smithb2f0f052016-10-10 18:54:32 +00002670 // C++17 [expr.delete]p10:
2671 // If the deallocation functions have class scope, the one without a
2672 // parameter of type std::size_t is selected.
2673 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2674 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2675 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002676
Richard Smithb2f0f052016-10-10 18:54:32 +00002677 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002678 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002679 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002680
Richard Smithb2f0f052016-10-10 18:54:32 +00002681 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002682 if (Operator->isDeleted()) {
2683 if (Diagnose) {
2684 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002685 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002686 }
2687 return true;
2688 }
2689
Richard Smith921bd202012-02-26 09:11:52 +00002690 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002691 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002692 return true;
2693
John McCall66a87592010-08-04 00:31:26 +00002694 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002695 }
John McCall66a87592010-08-04 00:31:26 +00002696
Richard Smithb2f0f052016-10-10 18:54:32 +00002697 // We found multiple suitable operators; complain about the ambiguity.
2698 // FIXME: The standard doesn't say to do this; it appears that the intent
2699 // is that this should never happen.
2700 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002701 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002702 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2703 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002704 for (auto &Match : Matches)
2705 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002706 }
John McCall66a87592010-08-04 00:31:26 +00002707 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002708 }
2709
2710 // We did find operator delete/operator delete[] declarations, but
2711 // none of them were suitable.
2712 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002713 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002714 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2715 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002716
Richard Smithb2f0f052016-10-10 18:54:32 +00002717 for (NamedDecl *D : Found)
2718 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002719 diag::note_member_declared_here) << Name;
2720 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002721 return true;
2722 }
2723
Craig Topperc3ec1492014-05-26 06:22:03 +00002724 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002725 return false;
2726}
2727
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002728namespace {
2729/// \brief Checks whether delete-expression, and new-expression used for
2730/// initializing deletee have the same array form.
2731class MismatchingNewDeleteDetector {
2732public:
2733 enum MismatchResult {
2734 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2735 NoMismatch,
2736 /// Indicates that variable is initialized with mismatching form of \a new.
2737 VarInitMismatches,
2738 /// Indicates that member is initialized with mismatching form of \a new.
2739 MemberInitMismatches,
2740 /// Indicates that 1 or more constructors' definitions could not been
2741 /// analyzed, and they will be checked again at the end of translation unit.
2742 AnalyzeLater
2743 };
2744
2745 /// \param EndOfTU True, if this is the final analysis at the end of
2746 /// translation unit. False, if this is the initial analysis at the point
2747 /// delete-expression was encountered.
2748 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002749 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002750 HasUndefinedConstructors(false) {}
2751
2752 /// \brief Checks whether pointee of a delete-expression is initialized with
2753 /// matching form of new-expression.
2754 ///
2755 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2756 /// point where delete-expression is encountered, then a warning will be
2757 /// issued immediately. If return value is \c AnalyzeLater at the point where
2758 /// delete-expression is seen, then member will be analyzed at the end of
2759 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2760 /// couldn't be analyzed. If at least one constructor initializes the member
2761 /// with matching type of new, the return value is \c NoMismatch.
2762 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2763 /// \brief Analyzes a class member.
2764 /// \param Field Class member to analyze.
2765 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2766 /// for deleting the \p Field.
2767 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002768 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002769 /// List of mismatching new-expressions used for initialization of the pointee
2770 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2771 /// Indicates whether delete-expression was in array form.
2772 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002773
2774private:
2775 const bool EndOfTU;
2776 /// \brief Indicates that there is at least one constructor without body.
2777 bool HasUndefinedConstructors;
2778 /// \brief Returns \c CXXNewExpr from given initialization expression.
2779 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002780 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002781 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2782 /// \brief Returns whether member is initialized with mismatching form of
2783 /// \c new either by the member initializer or in-class initialization.
2784 ///
2785 /// If bodies of all constructors are not visible at the end of translation
2786 /// unit or at least one constructor initializes member with the matching
2787 /// form of \c new, mismatch cannot be proven, and this function will return
2788 /// \c NoMismatch.
2789 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2790 /// \brief Returns whether variable is initialized with mismatching form of
2791 /// \c new.
2792 ///
2793 /// If variable is initialized with matching form of \c new or variable is not
2794 /// initialized with a \c new expression, this function will return true.
2795 /// If variable is initialized with mismatching form of \c new, returns false.
2796 /// \param D Variable to analyze.
2797 bool hasMatchingVarInit(const DeclRefExpr *D);
2798 /// \brief Checks whether the constructor initializes pointee with mismatching
2799 /// form of \c new.
2800 ///
2801 /// Returns true, if member is initialized with matching form of \c new in
2802 /// member initializer list. Returns false, if member is initialized with the
2803 /// matching form of \c new in this constructor's initializer or given
2804 /// constructor isn't defined at the point where delete-expression is seen, or
2805 /// member isn't initialized by the constructor.
2806 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2807 /// \brief Checks whether member is initialized with matching form of
2808 /// \c new in member initializer list.
2809 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2810 /// Checks whether member is initialized with mismatching form of \c new by
2811 /// in-class initializer.
2812 MismatchResult analyzeInClassInitializer();
2813};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002814}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002815
2816MismatchingNewDeleteDetector::MismatchResult
2817MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2818 NewExprs.clear();
2819 assert(DE && "Expected delete-expression");
2820 IsArrayForm = DE->isArrayForm();
2821 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2822 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2823 return analyzeMemberExpr(ME);
2824 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2825 if (!hasMatchingVarInit(D))
2826 return VarInitMismatches;
2827 }
2828 return NoMismatch;
2829}
2830
2831const CXXNewExpr *
2832MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2833 assert(E != nullptr && "Expected a valid initializer expression");
2834 E = E->IgnoreParenImpCasts();
2835 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2836 if (ILE->getNumInits() == 1)
2837 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2838 }
2839
2840 return dyn_cast_or_null<const CXXNewExpr>(E);
2841}
2842
2843bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2844 const CXXCtorInitializer *CI) {
2845 const CXXNewExpr *NE = nullptr;
2846 if (Field == CI->getMember() &&
2847 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2848 if (NE->isArray() == IsArrayForm)
2849 return true;
2850 else
2851 NewExprs.push_back(NE);
2852 }
2853 return false;
2854}
2855
2856bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2857 const CXXConstructorDecl *CD) {
2858 if (CD->isImplicit())
2859 return false;
2860 const FunctionDecl *Definition = CD;
2861 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2862 HasUndefinedConstructors = true;
2863 return EndOfTU;
2864 }
2865 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2866 if (hasMatchingNewInCtorInit(CI))
2867 return true;
2868 }
2869 return false;
2870}
2871
2872MismatchingNewDeleteDetector::MismatchResult
2873MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2874 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00002875 const Expr *InitExpr = Field->getInClassInitializer();
2876 if (!InitExpr)
2877 return EndOfTU ? NoMismatch : AnalyzeLater;
2878 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002879 if (NE->isArray() != IsArrayForm) {
2880 NewExprs.push_back(NE);
2881 return MemberInitMismatches;
2882 }
2883 }
2884 return NoMismatch;
2885}
2886
2887MismatchingNewDeleteDetector::MismatchResult
2888MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2889 bool DeleteWasArrayForm) {
2890 assert(Field != nullptr && "Analysis requires a valid class member.");
2891 this->Field = Field;
2892 IsArrayForm = DeleteWasArrayForm;
2893 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2894 for (const auto *CD : RD->ctors()) {
2895 if (hasMatchingNewInCtor(CD))
2896 return NoMismatch;
2897 }
2898 if (HasUndefinedConstructors)
2899 return EndOfTU ? NoMismatch : AnalyzeLater;
2900 if (!NewExprs.empty())
2901 return MemberInitMismatches;
2902 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
2903 : NoMismatch;
2904}
2905
2906MismatchingNewDeleteDetector::MismatchResult
2907MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
2908 assert(ME != nullptr && "Expected a member expression");
2909 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2910 return analyzeField(F, IsArrayForm);
2911 return NoMismatch;
2912}
2913
2914bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
2915 const CXXNewExpr *NE = nullptr;
2916 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
2917 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
2918 NE->isArray() != IsArrayForm) {
2919 NewExprs.push_back(NE);
2920 }
2921 }
2922 return NewExprs.empty();
2923}
2924
2925static void
2926DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
2927 const MismatchingNewDeleteDetector &Detector) {
2928 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
2929 FixItHint H;
2930 if (!Detector.IsArrayForm)
2931 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
2932 else {
2933 SourceLocation RSquare = Lexer::findLocationAfterToken(
2934 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
2935 SemaRef.getLangOpts(), true);
2936 if (RSquare.isValid())
2937 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
2938 }
2939 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
2940 << Detector.IsArrayForm << H;
2941
2942 for (const auto *NE : Detector.NewExprs)
2943 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
2944 << Detector.IsArrayForm;
2945}
2946
2947void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
2948 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
2949 return;
2950 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
2951 switch (Detector.analyzeDeleteExpr(DE)) {
2952 case MismatchingNewDeleteDetector::VarInitMismatches:
2953 case MismatchingNewDeleteDetector::MemberInitMismatches: {
2954 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
2955 break;
2956 }
2957 case MismatchingNewDeleteDetector::AnalyzeLater: {
2958 DeleteExprs[Detector.Field].push_back(
2959 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
2960 break;
2961 }
2962 case MismatchingNewDeleteDetector::NoMismatch:
2963 break;
2964 }
2965}
2966
2967void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
2968 bool DeleteWasArrayForm) {
2969 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
2970 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
2971 case MismatchingNewDeleteDetector::VarInitMismatches:
2972 llvm_unreachable("This analysis should have been done for class members.");
2973 case MismatchingNewDeleteDetector::AnalyzeLater:
2974 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
2975 "translation unit.");
2976 case MismatchingNewDeleteDetector::MemberInitMismatches:
2977 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
2978 break;
2979 case MismatchingNewDeleteDetector::NoMismatch:
2980 break;
2981 }
2982}
2983
Sebastian Redlbd150f42008-11-21 19:14:01 +00002984/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2985/// @code ::delete ptr; @endcode
2986/// or
2987/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00002988ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00002989Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00002990 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002991 // C++ [expr.delete]p1:
2992 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00002993 // non-explicit conversion function to a pointer type. The result has type
2994 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002995 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00002996 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2997
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002998 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00002999 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003000 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003001 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003002
John Wiegley01296292011-04-08 18:41:53 +00003003 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003004 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003005 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003006 if (Ex.isInvalid())
3007 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003008
John Wiegley01296292011-04-08 18:41:53 +00003009 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003010
Richard Smithccc11812013-05-21 19:05:48 +00003011 class DeleteConverter : public ContextualImplicitConverter {
3012 public:
3013 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003014
Craig Toppere14c0f82014-03-12 04:55:44 +00003015 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003016 // FIXME: If we have an operator T* and an operator void*, we must pick
3017 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003018 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003019 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003020 return true;
3021 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003022 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003023
Richard Smithccc11812013-05-21 19:05:48 +00003024 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003025 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003026 return S.Diag(Loc, diag::err_delete_operand) << T;
3027 }
3028
3029 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003030 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003031 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3032 }
3033
3034 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003035 QualType T,
3036 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003037 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3038 }
3039
3040 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003041 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003042 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3043 << ConvTy;
3044 }
3045
3046 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003047 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003048 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3049 }
3050
3051 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003052 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003053 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3054 << ConvTy;
3055 }
3056
3057 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003058 QualType T,
3059 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003060 llvm_unreachable("conversion functions are permitted");
3061 }
3062 } Converter;
3063
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003064 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003065 if (Ex.isInvalid())
3066 return ExprError();
3067 Type = Ex.get()->getType();
3068 if (!Converter.match(Type))
3069 // FIXME: PerformContextualImplicitConversion should return ExprError
3070 // itself in this case.
3071 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003072
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003073 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003074 QualType PointeeElem = Context.getBaseElementType(Pointee);
3075
3076 if (unsigned AddressSpace = Pointee.getAddressSpace())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003077 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003078 diag::err_address_space_qualified_delete)
3079 << Pointee.getUnqualifiedType() << AddressSpace;
3080
Craig Topperc3ec1492014-05-26 06:22:03 +00003081 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003082 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003083 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003084 // effectively bans deletion of "void*". However, most compilers support
3085 // this, so we treat it as a warning unless we're in a SFINAE context.
3086 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003087 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003088 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003089 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003090 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003091 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003092 // FIXME: This can result in errors if the definition was imported from a
3093 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003094 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003095 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003096 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3097 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3098 }
3099 }
3100
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003101 if (Pointee->isArrayType() && !ArrayForm) {
3102 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003103 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003104 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003105 ArrayForm = true;
3106 }
3107
Anders Carlssona471db02009-08-16 20:29:29 +00003108 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3109 ArrayForm ? OO_Array_Delete : OO_Delete);
3110
Eli Friedmanae4280f2011-07-26 22:25:31 +00003111 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003112 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003113 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3114 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003115 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003116
John McCall284c48f2011-01-27 09:37:56 +00003117 // If we're allocating an array of records, check whether the
3118 // usual operator delete[] has a size_t parameter.
3119 if (ArrayForm) {
3120 // If the user specifically asked to use the global allocator,
3121 // we'll need to do the lookup into the class.
3122 if (UseGlobal)
3123 UsualArrayDeleteWantsSize =
3124 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3125
3126 // Otherwise, the usual operator delete[] should be the
3127 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003128 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003129 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003130 UsualDeallocFnInfo(*this,
3131 DeclAccessPair::make(OperatorDelete, AS_public))
3132 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003133 }
3134
Richard Smitheec915d62012-02-18 04:13:32 +00003135 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003136 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003137 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003138 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003139 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3140 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003141 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003142
Nico Weber5a9259c2016-01-15 21:45:31 +00003143 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3144 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3145 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3146 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003148
Richard Smithb2f0f052016-10-10 18:54:32 +00003149 if (!OperatorDelete) {
3150 bool IsComplete = isCompleteType(StartLoc, Pointee);
3151 bool CanProvideSize =
3152 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3153 Pointee.isDestructedType());
3154 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3155
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003156 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003157 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3158 Overaligned, DeleteName);
3159 }
Mike Stump11289f42009-09-09 15:08:12 +00003160
Eli Friedmanfa0df832012-02-02 03:46:19 +00003161 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003162
Douglas Gregorfa778132011-02-01 15:50:11 +00003163 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003164 if (PointeeRD) {
3165 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00003166 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00003167 PDiag(diag::err_access_dtor) << PointeeElem);
3168 }
3169 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003170 }
3171
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003172 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003173 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3174 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003175 AnalyzeDeleteExprMismatch(Result);
3176 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003177}
3178
Nico Weber5a9259c2016-01-15 21:45:31 +00003179void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3180 bool IsDelete, bool CallCanBeVirtual,
3181 bool WarnOnNonAbstractTypes,
3182 SourceLocation DtorLoc) {
3183 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
3184 return;
3185
3186 // C++ [expr.delete]p3:
3187 // In the first alternative (delete object), if the static type of the
3188 // object to be deleted is different from its dynamic type, the static
3189 // type shall be a base class of the dynamic type of the object to be
3190 // deleted and the static type shall have a virtual destructor or the
3191 // behavior is undefined.
3192 //
3193 const CXXRecordDecl *PointeeRD = dtor->getParent();
3194 // Note: a final class cannot be derived from, no issue there
3195 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3196 return;
3197
3198 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3199 if (PointeeRD->isAbstract()) {
3200 // If the class is abstract, we warn by default, because we're
3201 // sure the code has undefined behavior.
3202 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3203 << ClassType;
3204 } else if (WarnOnNonAbstractTypes) {
3205 // Otherwise, if this is not an array delete, it's a bit suspect,
3206 // but not necessarily wrong.
3207 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3208 << ClassType;
3209 }
3210 if (!IsDelete) {
3211 std::string TypeStr;
3212 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3213 Diag(DtorLoc, diag::note_delete_non_virtual)
3214 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3215 }
3216}
3217
Richard Smith03a4aa32016-06-23 19:02:52 +00003218Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3219 SourceLocation StmtLoc,
3220 ConditionKind CK) {
3221 ExprResult E =
3222 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3223 if (E.isInvalid())
3224 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003225 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3226 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003227}
3228
Douglas Gregor633caca2009-11-23 23:44:04 +00003229/// \brief Check the use of the given variable as a C++ condition in an if,
3230/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003231ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003232 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003233 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003234 if (ConditionVar->isInvalidDecl())
3235 return ExprError();
3236
Douglas Gregor633caca2009-11-23 23:44:04 +00003237 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003238
Douglas Gregor633caca2009-11-23 23:44:04 +00003239 // C++ [stmt.select]p2:
3240 // The declarator shall not specify a function or an array.
3241 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003242 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003243 diag::err_invalid_use_of_function_type)
3244 << ConditionVar->getSourceRange());
3245 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003246 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003247 diag::err_invalid_use_of_array_type)
3248 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003249
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003250 ExprResult Condition = DeclRefExpr::Create(
3251 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3252 /*enclosing*/ false, ConditionVar->getLocation(),
3253 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003254
Eli Friedmanfa0df832012-02-02 03:46:19 +00003255 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003256
Richard Smith03a4aa32016-06-23 19:02:52 +00003257 switch (CK) {
3258 case ConditionKind::Boolean:
3259 return CheckBooleanCondition(StmtLoc, Condition.get());
3260
Richard Smithb130fe72016-06-23 19:16:49 +00003261 case ConditionKind::ConstexprIf:
3262 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3263
Richard Smith03a4aa32016-06-23 19:02:52 +00003264 case ConditionKind::Switch:
3265 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003266 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003267
Richard Smith03a4aa32016-06-23 19:02:52 +00003268 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003269}
3270
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003271/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003272ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003273 // C++ 6.4p4:
3274 // The value of a condition that is an initialized declaration in a statement
3275 // other than a switch statement is the value of the declared variable
3276 // implicitly converted to type bool. If that conversion is ill-formed, the
3277 // program is ill-formed.
3278 // The value of a condition that is an expression is the value of the
3279 // expression, implicitly converted to bool.
3280 //
Richard Smithb130fe72016-06-23 19:16:49 +00003281 // FIXME: Return this value to the caller so they don't need to recompute it.
3282 llvm::APSInt Value(/*BitWidth*/1);
3283 return (IsConstexpr && !CondExpr->isValueDependent())
3284 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3285 CCEK_ConstexprIf)
3286 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003287}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003288
3289/// Helper function to determine whether this is the (deprecated) C++
3290/// conversion from a string literal to a pointer to non-const char or
3291/// non-const wchar_t (for narrow and wide string literals,
3292/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003293bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003294Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3295 // Look inside the implicit cast, if it exists.
3296 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3297 From = Cast->getSubExpr();
3298
3299 // A string literal (2.13.4) that is not a wide string literal can
3300 // be converted to an rvalue of type "pointer to char"; a wide
3301 // string literal can be converted to an rvalue of type "pointer
3302 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003303 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003304 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003305 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003306 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003307 // This conversion is considered only when there is an
3308 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003309 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3310 switch (StrLit->getKind()) {
3311 case StringLiteral::UTF8:
3312 case StringLiteral::UTF16:
3313 case StringLiteral::UTF32:
3314 // We don't allow UTF literals to be implicitly converted
3315 break;
3316 case StringLiteral::Ascii:
3317 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3318 ToPointeeType->getKind() == BuiltinType::Char_S);
3319 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003320 return Context.typesAreCompatible(Context.getWideCharType(),
3321 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003322 }
3323 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003324 }
3325
3326 return false;
3327}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003328
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003329static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003330 SourceLocation CastLoc,
3331 QualType Ty,
3332 CastKind Kind,
3333 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003334 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003335 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003336 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003337 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003338 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003339 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003340 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003341 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003342
Richard Smith72d74052013-07-20 19:41:36 +00003343 if (S.RequireNonAbstractType(CastLoc, Ty,
3344 diag::err_allocation_of_abstract_type))
3345 return ExprError();
3346
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003347 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003348 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003349
Richard Smith5179eb72016-06-28 19:03:57 +00003350 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3351 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003352 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003353 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003354
Richard Smithf8adcdc2014-07-17 05:12:35 +00003355 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003356 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003357 ConstructorArgs, HadMultipleCandidates,
3358 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3359 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003360 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003361 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003362
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003363 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003365
John McCalle3027922010-08-25 11:45:40 +00003366 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003367 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003368
Richard Smithd3f2d322015-02-24 21:16:19 +00003369 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003370 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003371 return ExprError();
3372
Douglas Gregora4253922010-04-16 22:17:36 +00003373 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003374 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3375 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003376 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003377 if (Result.isInvalid())
3378 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003379 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003380 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3381 CK_UserDefinedConversion, Result.get(),
3382 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003383
Douglas Gregor668443e2011-01-20 00:18:04 +00003384 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003385 }
3386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003387}
Douglas Gregora4253922010-04-16 22:17:36 +00003388
Douglas Gregor5fb53972009-01-14 15:45:31 +00003389/// PerformImplicitConversion - Perform an implicit conversion of the
3390/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003391/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003392/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003393/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003394ExprResult
3395Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003396 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003397 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003398 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003399 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003400 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003401 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3402 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003403 if (Res.isInvalid())
3404 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003405 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003406 break;
John Wiegley01296292011-04-08 18:41:53 +00003407 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003408
Anders Carlsson110b07b2009-09-15 06:28:28 +00003409 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003410
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003411 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003412 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003413 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003414 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003415 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003416 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003417
Anders Carlsson110b07b2009-09-15 06:28:28 +00003418 // If the user-defined conversion is specified by a conversion function,
3419 // the initial standard conversion sequence converts the source type to
3420 // the implicit object parameter of the conversion function.
3421 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003422 } else {
3423 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003424 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003425 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003426 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003427 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003428 // initial standard conversion sequence converts the source type to
3429 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003430 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3431 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003432 }
Richard Smith72d74052013-07-20 19:41:36 +00003433 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003434 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003435 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003436 PerformImplicitConversion(From, BeforeToType,
3437 ICS.UserDefined.Before, AA_Converting,
3438 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003439 if (Res.isInvalid())
3440 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003441 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003442 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003443
3444 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003445 = BuildCXXCastArgument(*this,
3446 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003447 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003448 CastKind, cast<CXXMethodDecl>(FD),
3449 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003450 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003451 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003452
3453 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003454 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003455
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003456 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003457
Richard Smith507840d2011-11-29 22:48:16 +00003458 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3459 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003460 }
John McCall0d1da222010-01-12 00:44:57 +00003461
3462 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003463 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003464 PDiag(diag::err_typecheck_ambiguous_condition)
3465 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003466 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003467
Douglas Gregor39c16d42008-10-24 04:54:22 +00003468 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003469 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003470
3471 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003472 bool Diagnosed =
3473 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3474 From->getType(), From, Action);
3475 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003476 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003477 }
3478
3479 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003480 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003481}
3482
Richard Smith507840d2011-11-29 22:48:16 +00003483/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003484/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003485/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003486/// expression. Flavor is the context in which we're performing this
3487/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003488ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003489Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003490 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003491 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003492 CheckedConversionKind CCK) {
3493 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003494
Mike Stump87c57ac2009-05-16 07:39:55 +00003495 // Overall FIXME: we are recomputing too many types here and doing far too
3496 // much extra work. What this means is that we need to keep track of more
3497 // information that is computed when we try the implicit conversion initially,
3498 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003499 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003500
Douglas Gregor2fe98832008-11-03 19:09:14 +00003501 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003502 // FIXME: When can ToType be a reference type?
3503 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003504 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003505 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003506 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003507 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003508 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003509 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003510 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003511 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3512 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003513 ConstructorArgs, /*HadMultipleCandidates*/ false,
3514 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3515 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003516 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003517 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003518 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3519 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003520 From, /*HadMultipleCandidates*/ false,
3521 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3522 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003523 }
3524
Douglas Gregor980fb162010-04-29 18:24:40 +00003525 // Resolve overloaded function references.
3526 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3527 DeclAccessPair Found;
3528 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3529 true, Found);
3530 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003531 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003532
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003533 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003534 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535
Douglas Gregor980fb162010-04-29 18:24:40 +00003536 From = FixOverloadedFunctionReference(From, Found, Fn);
3537 FromType = From->getType();
3538 }
3539
Richard Smitha23ab512013-05-23 00:30:41 +00003540 // If we're converting to an atomic type, first convert to the corresponding
3541 // non-atomic type.
3542 QualType ToAtomicType;
3543 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3544 ToAtomicType = ToType;
3545 ToType = ToAtomic->getValueType();
3546 }
3547
George Burgess IV8d141e02015-12-14 22:00:49 +00003548 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003549 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003550 switch (SCS.First) {
3551 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003552 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3553 FromType = FromAtomic->getValueType().getUnqualifiedType();
3554 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3555 From, /*BasePath=*/nullptr, VK_RValue);
3556 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003557 break;
3558
Eli Friedman946b7b52012-01-24 22:51:26 +00003559 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003560 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003561 ExprResult FromRes = DefaultLvalueConversion(From);
3562 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003563 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003564 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003565 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003566 }
John McCall34376a62010-12-04 03:47:34 +00003567
Douglas Gregor39c16d42008-10-24 04:54:22 +00003568 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003569 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003570 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003571 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003572 break;
3573
3574 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003575 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003576 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003577 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003578 break;
3579
3580 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003581 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003582 }
3583
Richard Smith507840d2011-11-29 22:48:16 +00003584 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003585 switch (SCS.Second) {
3586 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003587 // C++ [except.spec]p5:
3588 // [For] assignment to and initialization of pointers to functions,
3589 // pointers to member functions, and references to functions: the
3590 // target entity shall allow at least the exceptions allowed by the
3591 // source value in the assignment or initialization.
3592 switch (Action) {
3593 case AA_Assigning:
3594 case AA_Initializing:
3595 // Note, function argument passing and returning are initialization.
3596 case AA_Passing:
3597 case AA_Returning:
3598 case AA_Sending:
3599 case AA_Passing_CFAudited:
3600 if (CheckExceptionSpecCompatibility(From, ToType))
3601 return ExprError();
3602 break;
3603
3604 case AA_Casting:
3605 case AA_Converting:
3606 // Casts and implicit conversions are not initialization, so are not
3607 // checked for exception specification mismatches.
3608 break;
3609 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003610 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003611 break;
3612
3613 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003614 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003615 if (ToType->isBooleanType()) {
3616 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3617 SCS.Second == ICK_Integral_Promotion &&
3618 "only enums with fixed underlying type can promote to bool");
3619 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003620 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003621 } else {
3622 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003623 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003624 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003625 break;
3626
3627 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003628 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003629 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003630 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003631 break;
3632
3633 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003634 case ICK_Complex_Conversion: {
3635 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3636 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3637 CastKind CK;
3638 if (FromEl->isRealFloatingType()) {
3639 if (ToEl->isRealFloatingType())
3640 CK = CK_FloatingComplexCast;
3641 else
3642 CK = CK_FloatingComplexToIntegralComplex;
3643 } else if (ToEl->isRealFloatingType()) {
3644 CK = CK_IntegralComplexToFloatingComplex;
3645 } else {
3646 CK = CK_IntegralComplexCast;
3647 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003648 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003649 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003650 break;
John McCall8cb679e2010-11-15 09:13:47 +00003651 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003652
Douglas Gregor39c16d42008-10-24 04:54:22 +00003653 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003654 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003655 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003656 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003657 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00003658 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003659 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003660 break;
3661
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003662 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003663 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003664 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003665 break;
3666
John McCall31168b02011-06-15 23:02:42 +00003667 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003668 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003669 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003670 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00003671 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003672 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003673 diag::ext_typecheck_convert_incompatible_pointer)
3674 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003675 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003676 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003677 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003678 diag::ext_typecheck_convert_incompatible_pointer)
3679 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003680 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00003681
Douglas Gregor33823722011-06-11 01:09:30 +00003682 if (From->getType()->isObjCObjectPointerType() &&
3683 ToType->isObjCObjectPointerType())
3684 EmitRelatedResultTypeNote(From);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003685 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00003686 else if (getLangOpts().ObjCAutoRefCount &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00003687 !CheckObjCARCUnavailableWeakConversion(ToType,
Fariborz Jahanianf2913402011-07-08 17:41:42 +00003688 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00003689 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003690 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003691 diag::err_arc_weak_unavailable_assign);
3692 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003693 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00003694 diag::err_arc_convesion_of_weak_unavailable)
3695 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00003696 << From->getSourceRange();
3697 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003698
John McCall8cb679e2010-11-15 09:13:47 +00003699 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003700 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003701 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003702 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00003703
3704 // Make sure we extend blocks if necessary.
3705 // FIXME: doing this here is really ugly.
3706 if (Kind == CK_BlockPointerToObjCPointerCast) {
3707 ExprResult E = From;
3708 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003709 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00003710 }
Fariborz Jahanian374089e2013-07-31 17:12:26 +00003711 if (getLangOpts().ObjCAutoRefCount)
3712 CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00003713 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003714 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003715 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003716 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003717
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003718 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00003719 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003720 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003721 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003722 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00003723 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003724 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00003725
3726 // We may not have been able to figure out what this member pointer resolved
3727 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00003728 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003729 (void)isCompleteType(From->getExprLoc(), From->getType());
3730 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00003731 }
David Majnemerd96b9972014-08-08 00:10:39 +00003732
Richard Smith507840d2011-11-29 22:48:16 +00003733 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003734 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003735 break;
3736 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003737
Abramo Bagnara7ccce982011-04-07 09:26:19 +00003738 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003739 // Perform half-to-boolean conversion via float.
3740 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003741 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003742 FromType = Context.FloatTy;
3743 }
3744
Richard Smith507840d2011-11-29 22:48:16 +00003745 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003746 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003747 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003748 break;
3749
Douglas Gregor88d292c2010-05-13 16:44:06 +00003750 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00003751 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003752 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003753 ToType.getNonReferenceType(),
3754 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003755 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003756 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00003757 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003758 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00003759
Richard Smith507840d2011-11-29 22:48:16 +00003760 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3761 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003762 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003763 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00003764 }
3765
Douglas Gregor46188682010-05-18 22:42:18 +00003766 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003767 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003768 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003769 break;
3770
George Burgess IVdf1ed002016-01-13 01:52:39 +00003771 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00003772 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00003773 Expr *Elem = prepareVectorSplat(ToType, From).get();
3774 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3775 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003776 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00003777 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003778
Douglas Gregor46188682010-05-18 22:42:18 +00003779 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00003780 // Case 1. x -> _Complex y
3781 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3782 QualType ElType = ToComplex->getElementType();
3783 bool isFloatingComplex = ElType->isRealFloatingType();
3784
3785 // x -> y
3786 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3787 // do nothing
3788 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003789 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003790 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00003791 } else {
3792 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003793 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003794 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00003795 }
3796 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00003797 From = ImpCastExprToType(From, ToType,
3798 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003799 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00003800
3801 // Case 2. _Complex x -> y
3802 } else {
3803 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3804 assert(FromComplex);
3805
3806 QualType ElType = FromComplex->getElementType();
3807 bool isFloatingComplex = ElType->isRealFloatingType();
3808
3809 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00003810 From = ImpCastExprToType(From, ElType,
3811 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00003812 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003813 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003814
3815 // x -> y
3816 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3817 // do nothing
3818 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003819 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003820 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003821 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003822 } else {
3823 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003824 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003825 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003826 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003827 }
3828 }
Douglas Gregor46188682010-05-18 22:42:18 +00003829 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00003830
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00003831 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003832 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003833 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00003834 break;
3835 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003836
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003837 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003838 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003839 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00003840 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3841 if (FromRes.isInvalid())
3842 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003843 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003844 assert ((ConvTy == Sema::Compatible) &&
3845 "Improper transparent union conversion");
3846 (void)ConvTy;
3847 break;
3848 }
3849
Guy Benyei259f9f42013-02-07 16:05:33 +00003850 case ICK_Zero_Event_Conversion:
3851 From = ImpCastExprToType(From, ToType,
3852 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003853 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00003854 break;
3855
Douglas Gregor46188682010-05-18 22:42:18 +00003856 case ICK_Lvalue_To_Rvalue:
3857 case ICK_Array_To_Pointer:
3858 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003859 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00003860 case ICK_Qualification:
3861 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00003862 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00003863 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003864 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003865 }
3866
3867 switch (SCS.Third) {
3868 case ICK_Identity:
3869 // Nothing to do.
3870 break;
3871
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003872 case ICK_Function_Conversion:
3873 // If both sides are functions (or pointers/references to them), there could
3874 // be incompatible exception declarations.
3875 if (CheckExceptionSpecCompatibility(From, ToType))
3876 return ExprError();
3877
3878 From = ImpCastExprToType(From, ToType, CK_NoOp,
3879 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3880 break;
3881
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003882 case ICK_Qualification: {
3883 // The qualification keeps the category of the inner expression, unless the
3884 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00003885 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003886 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00003887 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003888 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00003889
Douglas Gregore981bb02011-03-14 16:13:32 +00003890 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003891 !getLangOpts().WritableStrings) {
3892 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3893 ? diag::ext_deprecated_string_literal_conversion
3894 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00003895 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003896 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00003897
Douglas Gregor39c16d42008-10-24 04:54:22 +00003898 break;
Richard Smitha23ab512013-05-23 00:30:41 +00003899 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003900
Douglas Gregor39c16d42008-10-24 04:54:22 +00003901 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003902 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003903 }
3904
Douglas Gregor298f43d2012-04-12 20:42:30 +00003905 // If this conversion sequence involved a scalar -> atomic conversion, perform
3906 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00003907 if (!ToAtomicType.isNull()) {
3908 assert(Context.hasSameType(
3909 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3910 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003911 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00003912 }
3913
George Burgess IV8d141e02015-12-14 22:00:49 +00003914 // If this conversion sequence succeeded and involved implicitly converting a
3915 // _Nullable type to a _Nonnull one, complain.
3916 if (CCK == CCK_ImplicitConversion)
3917 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
3918 From->getLocStart());
3919
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003920 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003921}
3922
Chandler Carruth8e172c62011-05-01 06:51:22 +00003923/// \brief Check the completeness of a type in a unary type trait.
3924///
3925/// If the particular type trait requires a complete type, tries to complete
3926/// it. If completing the type fails, a diagnostic is emitted and false
3927/// returned. If completing the type succeeds or no completion was required,
3928/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00003929static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00003930 SourceLocation Loc,
3931 QualType ArgTy) {
3932 // C++0x [meta.unary.prop]p3:
3933 // For all of the class templates X declared in this Clause, instantiating
3934 // that template with a template argument that is a class template
3935 // specialization may result in the implicit instantiation of the template
3936 // argument if and only if the semantics of X require that the argument
3937 // must be a complete type.
3938 // We apply this rule to all the type trait expressions used to implement
3939 // these class templates. We also try to follow any GCC documented behavior
3940 // in these expressions to ensure portability of standard libraries.
3941 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00003942 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00003943 // is_complete_type somewhat obviously cannot require a complete type.
3944 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003945 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003946
3947 // These traits are modeled on the type predicates in C++0x
3948 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3949 // requiring a complete type, as whether or not they return true cannot be
3950 // impacted by the completeness of the type.
3951 case UTT_IsVoid:
3952 case UTT_IsIntegral:
3953 case UTT_IsFloatingPoint:
3954 case UTT_IsArray:
3955 case UTT_IsPointer:
3956 case UTT_IsLvalueReference:
3957 case UTT_IsRvalueReference:
3958 case UTT_IsMemberFunctionPointer:
3959 case UTT_IsMemberObjectPointer:
3960 case UTT_IsEnum:
3961 case UTT_IsUnion:
3962 case UTT_IsClass:
3963 case UTT_IsFunction:
3964 case UTT_IsReference:
3965 case UTT_IsArithmetic:
3966 case UTT_IsFundamental:
3967 case UTT_IsObject:
3968 case UTT_IsScalar:
3969 case UTT_IsCompound:
3970 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003971 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003972
3973 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
3974 // which requires some of its traits to have the complete type. However,
3975 // the completeness of the type cannot impact these traits' semantics, and
3976 // so they don't require it. This matches the comments on these traits in
3977 // Table 49.
3978 case UTT_IsConst:
3979 case UTT_IsVolatile:
3980 case UTT_IsSigned:
3981 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00003982
3983 // This type trait always returns false, checking the type is moot.
3984 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00003985 return true;
3986
David Majnemer213bea32015-11-16 06:58:51 +00003987 // C++14 [meta.unary.prop]:
3988 // If T is a non-union class type, T shall be a complete type.
3989 case UTT_IsEmpty:
3990 case UTT_IsPolymorphic:
3991 case UTT_IsAbstract:
3992 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
3993 if (!RD->isUnion())
3994 return !S.RequireCompleteType(
3995 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
3996 return true;
3997
3998 // C++14 [meta.unary.prop]:
3999 // If T is a class type, T shall be a complete type.
4000 case UTT_IsFinal:
4001 case UTT_IsSealed:
4002 if (ArgTy->getAsCXXRecordDecl())
4003 return !S.RequireCompleteType(
4004 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4005 return true;
4006
4007 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
4008 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004009 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004010 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004011 case UTT_IsStandardLayout:
4012 case UTT_IsPOD:
4013 case UTT_IsLiteral:
David Majnemer213bea32015-11-16 06:58:51 +00004014
Alp Toker73287bf2014-01-20 00:24:09 +00004015 case UTT_IsDestructible:
4016 case UTT_IsNothrowDestructible:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004017 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004018
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004019 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00004020 // [meta.unary.prop] despite not being named the same. They are specified
4021 // by both GCC and the Embarcadero C++ compiler, and require the complete
4022 // type due to the overarching C++0x type predicates being implemented
4023 // requiring the complete type.
4024 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004025 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004026 case UTT_HasNothrowConstructor:
4027 case UTT_HasNothrowCopy:
4028 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004029 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004030 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004031 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004032 case UTT_HasTrivialCopy:
4033 case UTT_HasTrivialDestructor:
4034 case UTT_HasVirtualDestructor:
4035 // Arrays of unknown bound are expressly allowed.
4036 QualType ElTy = ArgTy;
4037 if (ArgTy->isIncompleteArrayType())
4038 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
4039
4040 // The void type is expressly allowed.
4041 if (ElTy->isVoidType())
4042 return true;
4043
4044 return !S.RequireCompleteType(
4045 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004046 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004047}
4048
Joao Matosc9523d42013-03-27 01:34:16 +00004049static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4050 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004051 bool (CXXRecordDecl::*HasTrivial)() const,
4052 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004053 bool (CXXMethodDecl::*IsDesiredOp)() const)
4054{
4055 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4056 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4057 return true;
4058
4059 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4060 DeclarationNameInfo NameInfo(Name, KeyLoc);
4061 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4062 if (Self.LookupQualifiedName(Res, RD)) {
4063 bool FoundOperator = false;
4064 Res.suppressDiagnostics();
4065 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4066 Op != OpEnd; ++Op) {
4067 if (isa<FunctionTemplateDecl>(*Op))
4068 continue;
4069
4070 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4071 if((Operator->*IsDesiredOp)()) {
4072 FoundOperator = true;
4073 const FunctionProtoType *CPT =
4074 Operator->getType()->getAs<FunctionProtoType>();
4075 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Alp Toker73287bf2014-01-20 00:24:09 +00004076 if (!CPT || !CPT->isNothrow(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004077 return false;
4078 }
4079 }
4080 return FoundOperator;
4081 }
4082 return false;
4083}
4084
Alp Toker95e7ff22014-01-01 05:57:51 +00004085static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004086 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004087 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004088
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004089 ASTContext &C = Self.Context;
4090 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004091 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004092 // Type trait expressions corresponding to the primary type category
4093 // predicates in C++0x [meta.unary.cat].
4094 case UTT_IsVoid:
4095 return T->isVoidType();
4096 case UTT_IsIntegral:
4097 return T->isIntegralType(C);
4098 case UTT_IsFloatingPoint:
4099 return T->isFloatingType();
4100 case UTT_IsArray:
4101 return T->isArrayType();
4102 case UTT_IsPointer:
4103 return T->isPointerType();
4104 case UTT_IsLvalueReference:
4105 return T->isLValueReferenceType();
4106 case UTT_IsRvalueReference:
4107 return T->isRValueReferenceType();
4108 case UTT_IsMemberFunctionPointer:
4109 return T->isMemberFunctionPointerType();
4110 case UTT_IsMemberObjectPointer:
4111 return T->isMemberDataPointerType();
4112 case UTT_IsEnum:
4113 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004114 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004115 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004116 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004117 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004118 case UTT_IsFunction:
4119 return T->isFunctionType();
4120
4121 // Type trait expressions which correspond to the convenient composition
4122 // predicates in C++0x [meta.unary.comp].
4123 case UTT_IsReference:
4124 return T->isReferenceType();
4125 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004126 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004127 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004128 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004129 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004130 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004131 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004132 // Note: semantic analysis depends on Objective-C lifetime types to be
4133 // considered scalar types. However, such types do not actually behave
4134 // like scalar types at run time (since they may require retain/release
4135 // operations), so we report them as non-scalar.
4136 if (T->isObjCLifetimeType()) {
4137 switch (T.getObjCLifetime()) {
4138 case Qualifiers::OCL_None:
4139 case Qualifiers::OCL_ExplicitNone:
4140 return true;
4141
4142 case Qualifiers::OCL_Strong:
4143 case Qualifiers::OCL_Weak:
4144 case Qualifiers::OCL_Autoreleasing:
4145 return false;
4146 }
4147 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004148
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004149 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004150 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004151 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004152 case UTT_IsMemberPointer:
4153 return T->isMemberPointerType();
4154
4155 // Type trait expressions which correspond to the type property predicates
4156 // in C++0x [meta.unary.prop].
4157 case UTT_IsConst:
4158 return T.isConstQualified();
4159 case UTT_IsVolatile:
4160 return T.isVolatileQualified();
4161 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004162 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004163 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004164 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004165 case UTT_IsStandardLayout:
4166 return T->isStandardLayoutType();
4167 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004168 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004169 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004170 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004171 case UTT_IsEmpty:
4172 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4173 return !RD->isUnion() && RD->isEmpty();
4174 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004175 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004176 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004177 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004178 return false;
4179 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004180 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004181 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004182 return false;
David Majnemer213bea32015-11-16 06:58:51 +00004183 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4184 // even then only when it is used with the 'interface struct ...' syntax
4185 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004186 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004187 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004188 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004189 case UTT_IsSealed:
4190 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004191 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004192 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004193 case UTT_IsSigned:
4194 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004195 case UTT_IsUnsigned:
4196 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004197
4198 // Type trait expressions which query classes regarding their construction,
4199 // destruction, and copying. Rather than being based directly on the
4200 // related type predicates in the standard, they are specified by both
4201 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4202 // specifications.
4203 //
4204 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4205 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004206 //
4207 // Note that these builtins do not behave as documented in g++: if a class
4208 // has both a trivial and a non-trivial special member of a particular kind,
4209 // they return false! For now, we emulate this behavior.
4210 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4211 // does not correctly compute triviality in the presence of multiple special
4212 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004213 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004214 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4215 // If __is_pod (type) is true then the trait is true, else if type is
4216 // a cv class or union type (or array thereof) with a trivial default
4217 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004218 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004219 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004220 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4221 return RD->hasTrivialDefaultConstructor() &&
4222 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004223 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004224 case UTT_HasTrivialMoveConstructor:
4225 // This trait is implemented by MSVC 2012 and needed to parse the
4226 // standard library headers. Specifically this is used as the logic
4227 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004228 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004229 return true;
4230 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4231 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4232 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004233 case UTT_HasTrivialCopy:
4234 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4235 // If __is_pod (type) is true or type is a reference type then
4236 // the trait is true, else if type is a cv class or union type
4237 // with a trivial copy constructor ([class.copy]) then the trait
4238 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004239 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004240 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004241 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4242 return RD->hasTrivialCopyConstructor() &&
4243 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004244 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004245 case UTT_HasTrivialMoveAssign:
4246 // This trait is implemented by MSVC 2012 and needed to parse the
4247 // standard library headers. Specifically it is used as the logic
4248 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004249 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004250 return true;
4251 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4252 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4253 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004254 case UTT_HasTrivialAssign:
4255 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4256 // If type is const qualified or is a reference type then the
4257 // trait is false. Otherwise if __is_pod (type) is true then the
4258 // trait is true, else if type is a cv class or union type with
4259 // a trivial copy assignment ([class.copy]) then the trait is
4260 // true, else it is false.
4261 // Note: the const and reference restrictions are interesting,
4262 // given that const and reference members don't prevent a class
4263 // from having a trivial copy assignment operator (but do cause
4264 // errors if the copy assignment operator is actually used, q.v.
4265 // [class.copy]p12).
4266
Richard Smith92f241f2012-12-08 02:53:02 +00004267 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004268 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004269 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004270 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004271 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4272 return RD->hasTrivialCopyAssignment() &&
4273 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004274 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004275 case UTT_IsDestructible:
4276 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004277 // C++14 [meta.unary.prop]:
4278 // For reference types, is_destructible<T>::value is true.
4279 if (T->isReferenceType())
4280 return true;
4281
4282 // Objective-C++ ARC: autorelease types don't require destruction.
4283 if (T->isObjCLifetimeType() &&
4284 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4285 return true;
4286
4287 // C++14 [meta.unary.prop]:
4288 // For incomplete types and function types, is_destructible<T>::value is
4289 // false.
4290 if (T->isIncompleteType() || T->isFunctionType())
4291 return false;
4292
4293 // C++14 [meta.unary.prop]:
4294 // For object types and given U equal to remove_all_extents_t<T>, if the
4295 // expression std::declval<U&>().~U() is well-formed when treated as an
4296 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4297 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4298 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4299 if (!Destructor)
4300 return false;
4301 // C++14 [dcl.fct.def.delete]p2:
4302 // A program that refers to a deleted function implicitly or
4303 // explicitly, other than to declare it, is ill-formed.
4304 if (Destructor->isDeleted())
4305 return false;
4306 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4307 return false;
4308 if (UTT == UTT_IsNothrowDestructible) {
4309 const FunctionProtoType *CPT =
4310 Destructor->getType()->getAs<FunctionProtoType>();
4311 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4312 if (!CPT || !CPT->isNothrow(C))
4313 return false;
4314 }
4315 }
4316 return true;
4317
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004318 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004319 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004320 // If __is_pod (type) is true or type is a reference type
4321 // then the trait is true, else if type is a cv class or union
4322 // type (or array thereof) with a trivial destructor
4323 // ([class.dtor]) then the trait is true, else it is
4324 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004325 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004326 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004327
John McCall31168b02011-06-15 23:02:42 +00004328 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004329 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004330 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4331 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004332
Richard Smith92f241f2012-12-08 02:53:02 +00004333 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4334 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004335 return false;
4336 // TODO: Propagate nothrowness for implicitly declared special members.
4337 case UTT_HasNothrowAssign:
4338 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4339 // If type is const qualified or is a reference type then the
4340 // trait is false. Otherwise if __has_trivial_assign (type)
4341 // is true then the trait is true, else if type is a cv class
4342 // or union type with copy assignment operators that are known
4343 // not to throw an exception then the trait is true, else it is
4344 // false.
4345 if (C.getBaseElementType(T).isConstQualified())
4346 return false;
4347 if (T->isReferenceType())
4348 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004349 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004350 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004351
Joao Matosc9523d42013-03-27 01:34:16 +00004352 if (const RecordType *RT = T->getAs<RecordType>())
4353 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4354 &CXXRecordDecl::hasTrivialCopyAssignment,
4355 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4356 &CXXMethodDecl::isCopyAssignmentOperator);
4357 return false;
4358 case UTT_HasNothrowMoveAssign:
4359 // This trait is implemented by MSVC 2012 and needed to parse the
4360 // standard library headers. Specifically this is used as the logic
4361 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004362 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004363 return true;
4364
4365 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4366 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4367 &CXXRecordDecl::hasTrivialMoveAssignment,
4368 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4369 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004370 return false;
4371 case UTT_HasNothrowCopy:
4372 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4373 // If __has_trivial_copy (type) is true then the trait is true, else
4374 // if type is a cv class or union type with copy constructors that are
4375 // known not to throw an exception then the trait is true, else it is
4376 // false.
John McCall31168b02011-06-15 23:02:42 +00004377 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004378 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004379 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4380 if (RD->hasTrivialCopyConstructor() &&
4381 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004382 return true;
4383
4384 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004385 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004386 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004387 // A template constructor is never a copy constructor.
4388 // FIXME: However, it may actually be selected at the actual overload
4389 // resolution point.
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004390 if (isa<FunctionTemplateDecl>(ND))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004391 continue;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004392 const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004393 if (Constructor->isCopyConstructor(FoundTQs)) {
4394 FoundConstructor = true;
4395 const FunctionProtoType *CPT
4396 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004397 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4398 if (!CPT)
4399 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004400 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004401 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004402 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004403 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004404 }
4405 }
4406
Richard Smith938f40b2011-06-11 17:19:42 +00004407 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004408 }
4409 return false;
4410 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004411 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004412 // If __has_trivial_constructor (type) is true then the trait is
4413 // true, else if type is a cv class or union type (or array
4414 // thereof) with a default constructor that is known not to
4415 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004416 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004417 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004418 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4419 if (RD->hasTrivialDefaultConstructor() &&
4420 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004421 return true;
4422
Alp Tokerb4bca412014-01-20 00:23:47 +00004423 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004424 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004425 // FIXME: In C++0x, a constructor template can be a default constructor.
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004426 if (isa<FunctionTemplateDecl>(ND))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004427 continue;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004428 const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND);
Sebastian Redlc15c3262010-09-13 22:02:47 +00004429 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004430 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004431 const FunctionProtoType *CPT
4432 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004433 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4434 if (!CPT)
4435 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004436 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004437 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004438 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004439 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004440 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004441 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004442 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004443 }
4444 return false;
4445 case UTT_HasVirtualDestructor:
4446 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4447 // If type is a class type with a virtual destructor ([class.dtor])
4448 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004449 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004450 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004451 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004452 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004453
4454 // These type trait expressions are modeled on the specifications for the
4455 // Embarcadero C++0x type trait functions:
4456 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4457 case UTT_IsCompleteType:
4458 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4459 // Returns True if and only if T is a complete type at the point of the
4460 // function call.
4461 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004462 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004463}
Sebastian Redl5822f082009-02-07 20:10:22 +00004464
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004465/// \brief Determine whether T has a non-trivial Objective-C lifetime in
4466/// ARC mode.
4467static bool hasNontrivialObjCLifetime(QualType T) {
4468 switch (T.getObjCLifetime()) {
4469 case Qualifiers::OCL_ExplicitNone:
4470 return false;
4471
4472 case Qualifiers::OCL_Strong:
4473 case Qualifiers::OCL_Weak:
4474 case Qualifiers::OCL_Autoreleasing:
4475 return true;
4476
4477 case Qualifiers::OCL_None:
4478 return T->isObjCLifetimeType();
4479 }
4480
4481 llvm_unreachable("Unknown ObjC lifetime qualifier");
4482}
4483
Alp Tokercbb90342013-12-13 20:49:58 +00004484static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4485 QualType RhsT, SourceLocation KeyLoc);
4486
Douglas Gregor29c42f22012-02-24 07:38:34 +00004487static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4488 ArrayRef<TypeSourceInfo *> Args,
4489 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004490 if (Kind <= UTT_Last)
4491 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4492
Alp Tokercbb90342013-12-13 20:49:58 +00004493 if (Kind <= BTT_Last)
4494 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4495 Args[1]->getType(), RParenLoc);
4496
Douglas Gregor29c42f22012-02-24 07:38:34 +00004497 switch (Kind) {
Alp Toker73287bf2014-01-20 00:24:09 +00004498 case clang::TT_IsConstructible:
4499 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004500 case clang::TT_IsTriviallyConstructible: {
4501 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004502 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004503 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004504 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004505 // definition for is_constructible, as defined below, is known to call
4506 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004507 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004508 // The predicate condition for a template specialization
4509 // is_constructible<T, Args...> shall be satisfied if and only if the
4510 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004511 // variable t:
4512 //
4513 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004514 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004515
4516 // Precondition: T and all types in the parameter pack Args shall be
4517 // complete types, (possibly cv-qualified) void, or arrays of
4518 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004519 for (const auto *TSI : Args) {
4520 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004521 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004522 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004523
Simon Pilgrim75c26882016-09-30 14:25:09 +00004524 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004525 diag::err_incomplete_type_used_in_type_trait_expr))
4526 return false;
4527 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004528
David Majnemer9658ecc2015-11-13 05:32:43 +00004529 // Make sure the first argument is not incomplete nor a function type.
4530 QualType T = Args[0]->getType();
4531 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004532 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004533
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004534 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004535 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004536 if (RD && RD->isAbstract())
4537 return false;
4538
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004539 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4540 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004541 ArgExprs.reserve(Args.size() - 1);
4542 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004543 QualType ArgTy = Args[I]->getType();
4544 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4545 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004546 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004547 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4548 ArgTy.getNonLValueExprType(S.Context),
4549 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004550 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004551 for (Expr &E : OpaqueArgExprs)
4552 ArgExprs.push_back(&E);
4553
Simon Pilgrim75c26882016-09-30 14:25:09 +00004554 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004555 // trap at translation unit scope.
4556 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
4557 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4558 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4559 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4560 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4561 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004562 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004563 if (Init.Failed())
4564 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004565
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004566 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004567 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4568 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004569
Alp Toker73287bf2014-01-20 00:24:09 +00004570 if (Kind == clang::TT_IsConstructible)
4571 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004572
Alp Toker73287bf2014-01-20 00:24:09 +00004573 if (Kind == clang::TT_IsNothrowConstructible)
4574 return S.canThrow(Result.get()) == CT_Cannot;
4575
4576 if (Kind == clang::TT_IsTriviallyConstructible) {
4577 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4578 // lifetime, this is a non-trivial construction.
4579 if (S.getLangOpts().ObjCAutoRefCount &&
David Majnemer9658ecc2015-11-13 05:32:43 +00004580 hasNontrivialObjCLifetime(T.getNonReferenceType()))
Alp Toker73287bf2014-01-20 00:24:09 +00004581 return false;
4582
4583 // The initialization succeeded; now make sure there are no non-trivial
4584 // calls.
4585 return !Result.get()->hasNonTrivialCall(S.Context);
4586 }
4587
4588 llvm_unreachable("unhandled type trait");
4589 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004590 }
Alp Tokercbb90342013-12-13 20:49:58 +00004591 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004592 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004593
Douglas Gregor29c42f22012-02-24 07:38:34 +00004594 return false;
4595}
4596
Simon Pilgrim75c26882016-09-30 14:25:09 +00004597ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4598 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004599 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004600 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004601
Alp Toker95e7ff22014-01-01 05:57:51 +00004602 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4603 *this, Kind, KWLoc, Args[0]->getType()))
4604 return ExprError();
4605
Douglas Gregor29c42f22012-02-24 07:38:34 +00004606 bool Dependent = false;
4607 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4608 if (Args[I]->getType()->isDependentType()) {
4609 Dependent = true;
4610 break;
4611 }
4612 }
Alp Tokercbb90342013-12-13 20:49:58 +00004613
4614 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004615 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004616 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4617
4618 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4619 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004620}
4621
Alp Toker88f64e62013-12-13 21:19:30 +00004622ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4623 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004624 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004625 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004626 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00004627
Douglas Gregor29c42f22012-02-24 07:38:34 +00004628 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4629 TypeSourceInfo *TInfo;
4630 QualType T = GetTypeFromParser(Args[I], &TInfo);
4631 if (!TInfo)
4632 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004633
4634 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004635 }
Alp Tokercbb90342013-12-13 20:49:58 +00004636
Douglas Gregor29c42f22012-02-24 07:38:34 +00004637 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4638}
4639
Alp Tokercbb90342013-12-13 20:49:58 +00004640static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4641 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004642 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4643 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004644
4645 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004646 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004647 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004648 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004649 // Base and Derived are not unions and name the same class type without
4650 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004651
John McCall388ef532011-01-28 22:02:36 +00004652 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4653 if (!lhsRecord) return false;
4654
4655 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4656 if (!rhsRecord) return false;
4657
4658 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4659 == (lhsRecord == rhsRecord));
4660
4661 if (lhsRecord == rhsRecord)
4662 return !lhsRecord->getDecl()->isUnion();
4663
4664 // C++0x [meta.rel]p2:
4665 // If Base and Derived are class types and are different types
4666 // (ignoring possible cv-qualifiers) then Derived shall be a
4667 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004668 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00004669 diag::err_incomplete_type_used_in_type_trait_expr))
4670 return false;
4671
4672 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4673 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4674 }
John Wiegley65497cc2011-04-27 23:09:49 +00004675 case BTT_IsSame:
4676 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00004677 case BTT_TypeCompatible:
4678 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4679 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00004680 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00004681 case BTT_IsConvertibleTo: {
4682 // C++0x [meta.rel]p4:
4683 // Given the following function prototype:
4684 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004685 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00004686 // typename add_rvalue_reference<T>::type create();
4687 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004688 // the predicate condition for a template specialization
4689 // is_convertible<From, To> shall be satisfied if and only if
4690 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00004691 // well-formed, including any implicit conversions to the return
4692 // type of the function:
4693 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004694 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00004695 // return create<From>();
4696 // }
4697 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004698 // Access checking is performed as if in a context unrelated to To and
4699 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00004700 // of the return-statement (including conversions to the return type)
4701 // is considered.
4702 //
4703 // We model the initialization as a copy-initialization of a temporary
4704 // of the appropriate type, which for this expression is identical to the
4705 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004706
4707 // Functions aren't allowed to return function or array types.
4708 if (RhsT->isFunctionType() || RhsT->isArrayType())
4709 return false;
4710
4711 // A return statement in a void function must have void type.
4712 if (RhsT->isVoidType())
4713 return LhsT->isVoidType();
4714
4715 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00004716 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004717 return false;
4718
4719 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00004720 if (LhsT->isObjectType() || LhsT->isFunctionType())
4721 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004722
4723 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00004724 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00004725 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00004726 Expr::getValueKindForType(LhsT));
4727 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004728 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00004729 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004730
4731 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00004732 // trap at translation unit scope.
4733 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00004734 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4735 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004736 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004737 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00004738 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00004739
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004740 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00004741 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4742 }
Alp Toker73287bf2014-01-20 00:24:09 +00004743
David Majnemerb3d96882016-05-23 17:21:55 +00004744 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00004745 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00004746 case BTT_IsTriviallyAssignable: {
4747 // C++11 [meta.unary.prop]p3:
4748 // is_trivially_assignable is defined as:
4749 // is_assignable<T, U>::value is true and the assignment, as defined by
4750 // is_assignable, is known to call no operation that is not trivial
4751 //
4752 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004753 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00004754 // treated as an unevaluated operand (Clause 5).
4755 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004756 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00004757 // void, or arrays of unknown bound.
4758 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004759 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004760 diag::err_incomplete_type_used_in_type_trait_expr))
4761 return false;
4762 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004763 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004764 diag::err_incomplete_type_used_in_type_trait_expr))
4765 return false;
4766
4767 // cv void is never assignable.
4768 if (LhsT->isVoidType() || RhsT->isVoidType())
4769 return false;
4770
Simon Pilgrim75c26882016-09-30 14:25:09 +00004771 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00004772 // declval<U>().
4773 if (LhsT->isObjectType() || LhsT->isFunctionType())
4774 LhsT = Self.Context.getRValueReferenceType(LhsT);
4775 if (RhsT->isObjectType() || RhsT->isFunctionType())
4776 RhsT = Self.Context.getRValueReferenceType(RhsT);
4777 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4778 Expr::getValueKindForType(LhsT));
4779 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4780 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004781
4782 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00004783 // trap at translation unit scope.
4784 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
4785 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4786 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004787 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4788 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004789 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4790 return false;
4791
David Majnemerb3d96882016-05-23 17:21:55 +00004792 if (BTT == BTT_IsAssignable)
4793 return true;
4794
Alp Toker73287bf2014-01-20 00:24:09 +00004795 if (BTT == BTT_IsNothrowAssignable)
4796 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004797
Alp Toker73287bf2014-01-20 00:24:09 +00004798 if (BTT == BTT_IsTriviallyAssignable) {
4799 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4800 // lifetime, this is a non-trivial assignment.
4801 if (Self.getLangOpts().ObjCAutoRefCount &&
4802 hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
4803 return false;
4804
4805 return !Result.get()->hasNonTrivialCall(Self.Context);
4806 }
4807
4808 llvm_unreachable("unhandled type trait");
4809 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00004810 }
Alp Tokercbb90342013-12-13 20:49:58 +00004811 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004812 }
4813 llvm_unreachable("Unknown type trait or not implemented");
4814}
4815
John Wiegley6242b6a2011-04-28 00:16:57 +00004816ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4817 SourceLocation KWLoc,
4818 ParsedType Ty,
4819 Expr* DimExpr,
4820 SourceLocation RParen) {
4821 TypeSourceInfo *TSInfo;
4822 QualType T = GetTypeFromParser(Ty, &TSInfo);
4823 if (!TSInfo)
4824 TSInfo = Context.getTrivialTypeSourceInfo(T);
4825
4826 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4827}
4828
4829static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4830 QualType T, Expr *DimExpr,
4831 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004832 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00004833
4834 switch(ATT) {
4835 case ATT_ArrayRank:
4836 if (T->isArrayType()) {
4837 unsigned Dim = 0;
4838 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4839 ++Dim;
4840 T = AT->getElementType();
4841 }
4842 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00004843 }
John Wiegleyd3522222011-04-28 02:06:46 +00004844 return 0;
4845
John Wiegley6242b6a2011-04-28 00:16:57 +00004846 case ATT_ArrayExtent: {
4847 llvm::APSInt Value;
4848 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00004849 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00004850 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00004851 false).isInvalid())
4852 return 0;
4853 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00004854 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4855 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00004856 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00004857 }
Richard Smithf4c51d92012-02-04 09:53:13 +00004858 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00004859
4860 if (T->isArrayType()) {
4861 unsigned D = 0;
4862 bool Matched = false;
4863 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4864 if (Dim == D) {
4865 Matched = true;
4866 break;
4867 }
4868 ++D;
4869 T = AT->getElementType();
4870 }
4871
John Wiegleyd3522222011-04-28 02:06:46 +00004872 if (Matched && T->isArrayType()) {
4873 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4874 return CAT->getSize().getLimitedValue();
4875 }
John Wiegley6242b6a2011-04-28 00:16:57 +00004876 }
John Wiegleyd3522222011-04-28 02:06:46 +00004877 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00004878 }
4879 }
4880 llvm_unreachable("Unknown type trait or not implemented");
4881}
4882
4883ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4884 SourceLocation KWLoc,
4885 TypeSourceInfo *TSInfo,
4886 Expr* DimExpr,
4887 SourceLocation RParen) {
4888 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00004889
Chandler Carruthc5276e52011-05-01 08:48:21 +00004890 // FIXME: This should likely be tracked as an APInt to remove any host
4891 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004892 uint64_t Value = 0;
4893 if (!T->isDependentType())
4894 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4895
Chandler Carruthc5276e52011-05-01 08:48:21 +00004896 // While the specification for these traits from the Embarcadero C++
4897 // compiler's documentation says the return type is 'unsigned int', Clang
4898 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4899 // compiler, there is no difference. On several other platforms this is an
4900 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004901 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4902 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00004903}
4904
John Wiegleyf9f65842011-04-25 06:54:41 +00004905ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004906 SourceLocation KWLoc,
4907 Expr *Queried,
4908 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004909 // If error parsing the expression, ignore.
4910 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004911 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00004912
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004913 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004914
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004915 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00004916}
4917
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004918static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4919 switch (ET) {
4920 case ET_IsLValueExpr: return E->isLValue();
4921 case ET_IsRValueExpr: return E->isRValue();
4922 }
4923 llvm_unreachable("Expression trait not covered by switch");
4924}
4925
John Wiegleyf9f65842011-04-25 06:54:41 +00004926ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004927 SourceLocation KWLoc,
4928 Expr *Queried,
4929 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004930 if (Queried->isTypeDependent()) {
4931 // Delay type-checking for type-dependent expressions.
4932 } else if (Queried->getType()->isPlaceholderType()) {
4933 ExprResult PE = CheckPlaceholderExpr(Queried);
4934 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004935 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004936 }
4937
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004938 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00004939
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004940 return new (Context)
4941 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00004942}
4943
Richard Trieu82402a02011-09-15 21:56:47 +00004944QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004945 ExprValueKind &VK,
4946 SourceLocation Loc,
4947 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004948 assert(!LHS.get()->getType()->isPlaceholderType() &&
4949 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00004950 "placeholders should have been weeded out by now");
4951
4952 // The LHS undergoes lvalue conversions if this is ->*.
4953 if (isIndirect) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004954 LHS = DefaultLvalueConversion(LHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00004955 if (LHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004956 }
4957
4958 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004959 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00004960 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004961
Sebastian Redl5822f082009-02-07 20:10:22 +00004962 const char *OpSpelling = isIndirect ? "->*" : ".*";
4963 // C++ 5.5p2
4964 // The binary operator .* [p3: ->*] binds its second operand, which shall
4965 // be of type "pointer to member of T" (where T is a completely-defined
4966 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00004967 QualType RHSType = RHS.get()->getType();
4968 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004969 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00004970 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00004971 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00004972 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004973 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004974
Sebastian Redl5822f082009-02-07 20:10:22 +00004975 QualType Class(MemPtr->getClass(), 0);
4976
Douglas Gregord07ba342010-10-13 20:41:14 +00004977 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
4978 // member pointer points must be completely-defined. However, there is no
4979 // reason for this semantic distinction, and the rule is not enforced by
4980 // other compilers. Therefore, we do not check this property, as it is
4981 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00004982
Sebastian Redl5822f082009-02-07 20:10:22 +00004983 // C++ 5.5p2
4984 // [...] to its first operand, which shall be of class T or of a class of
4985 // which T is an unambiguous and accessible base class. [p3: a pointer to
4986 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00004987 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00004988 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004989 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
4990 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00004991 else {
4992 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00004993 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00004994 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00004995 return QualType();
4996 }
4997 }
4998
Richard Trieu82402a02011-09-15 21:56:47 +00004999 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005000 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005001 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5002 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005003 return QualType();
5004 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005005
Richard Smith0f59cb32015-12-18 21:45:41 +00005006 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005007 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005008 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005009 return QualType();
5010 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005011
5012 CXXCastPath BasePath;
5013 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5014 SourceRange(LHS.get()->getLocStart(),
5015 RHS.get()->getLocEnd()),
5016 &BasePath))
5017 return QualType();
5018
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005019 // Cast LHS to type of use.
5020 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005021 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005022 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005023 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005024 }
5025
Richard Trieu82402a02011-09-15 21:56:47 +00005026 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005027 // Diagnose use of pointer-to-member type which when used as
5028 // the functional cast in a pointer-to-member expression.
5029 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5030 return QualType();
5031 }
John McCall7decc9e2010-11-18 06:31:45 +00005032
Sebastian Redl5822f082009-02-07 20:10:22 +00005033 // C++ 5.5p2
5034 // The result is an object or a function of the type specified by the
5035 // second operand.
5036 // The cv qualifiers are the union of those in the pointer and the left side,
5037 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005038 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005039 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005040
Douglas Gregor1d042092011-01-26 16:40:18 +00005041 // C++0x [expr.mptr.oper]p6:
5042 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005043 // ill-formed if the second operand is a pointer to member function with
5044 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5045 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005046 // is a pointer to member function with ref-qualifier &&.
5047 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5048 switch (Proto->getRefQualifier()) {
5049 case RQ_None:
5050 // Do nothing
5051 break;
5052
5053 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005054 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005055 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005056 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005057 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005058
Douglas Gregor1d042092011-01-26 16:40:18 +00005059 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005060 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005061 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005062 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005063 break;
5064 }
5065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005066
John McCall7decc9e2010-11-18 06:31:45 +00005067 // C++ [expr.mptr.oper]p6:
5068 // The result of a .* expression whose second operand is a pointer
5069 // to a data member is of the same value category as its
5070 // first operand. The result of a .* expression whose second
5071 // operand is a pointer to a member function is a prvalue. The
5072 // result of an ->* expression is an lvalue if its second operand
5073 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005074 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005075 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005076 return Context.BoundMemberTy;
5077 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005078 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005079 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005080 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005081 }
John McCall7decc9e2010-11-18 06:31:45 +00005082
Sebastian Redl5822f082009-02-07 20:10:22 +00005083 return Result;
5084}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005085
Richard Smith2414bca2016-04-25 19:30:37 +00005086/// \brief Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005087///
5088/// This is part of the parameter validation for the ? operator. If either
5089/// value operand is a class type, the two operands are attempted to be
5090/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005091/// It returns true if the program is ill-formed and has already been diagnosed
5092/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005093static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5094 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005095 bool &HaveConversion,
5096 QualType &ToType) {
5097 HaveConversion = false;
5098 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005099
5100 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005101 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005102 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005103 // The process for determining whether an operand expression E1 of type T1
5104 // can be converted to match an operand expression E2 of type T2 is defined
5105 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005106 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5107 // implicitly converted to type "lvalue reference to T2", subject to the
5108 // constraint that in the conversion the reference must bind directly to
5109 // an lvalue.
5110 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5111 // implicitly conveted to the type "rvalue reference to R2", subject to
5112 // the constraint that the reference must bind directly.
5113 if (To->isLValue() || To->isXValue()) {
5114 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5115 : Self.Context.getRValueReferenceType(ToType);
5116
Douglas Gregor838fcc32010-03-26 20:14:36 +00005117 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005118
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005119 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005120 if (InitSeq.isDirectReferenceBinding()) {
5121 ToType = T;
5122 HaveConversion = true;
5123 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005125
Douglas Gregor838fcc32010-03-26 20:14:36 +00005126 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005127 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005128 }
John McCall65eb8792010-02-25 01:37:24 +00005129
Sebastian Redl1a99f442009-04-16 17:51:27 +00005130 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5131 // -- if E1 and E2 have class type, and the underlying class types are
5132 // the same or one is a base class of the other:
5133 QualType FTy = From->getType();
5134 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005135 const RecordType *FRec = FTy->getAs<RecordType>();
5136 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005137 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005138 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5139 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5140 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005141 // E1 can be converted to match E2 if the class of T2 is the
5142 // same type as, or a base class of, the class of T1, and
5143 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005144 if (FRec == TRec || FDerivedFromT) {
5145 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005146 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005147 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005148 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005149 HaveConversion = true;
5150 return false;
5151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005152
Douglas Gregor838fcc32010-03-26 20:14:36 +00005153 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005154 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005155 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005157
Douglas Gregor838fcc32010-03-26 20:14:36 +00005158 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005159 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005160
Douglas Gregor838fcc32010-03-26 20:14:36 +00005161 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5162 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005163 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005164 // an rvalue).
5165 //
5166 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5167 // to the array-to-pointer or function-to-pointer conversions.
5168 if (!TTy->getAs<TagType>())
5169 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005170
Douglas Gregor838fcc32010-03-26 20:14:36 +00005171 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005172 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005173 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005174 ToType = TTy;
5175 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005176 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005177
Sebastian Redl1a99f442009-04-16 17:51:27 +00005178 return false;
5179}
5180
5181/// \brief Try to find a common type for two according to C++0x 5.16p5.
5182///
5183/// This is part of the parameter validation for the ? operator. If either
5184/// value operand is a class type, overload resolution is used to find a
5185/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005186static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005187 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005188 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005189 OverloadCandidateSet CandidateSet(QuestionLoc,
5190 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005191 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005192 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005193
5194 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005195 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005196 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005197 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00005198 ExprResult LHSRes =
5199 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
5200 Best->Conversions[0], Sema::AA_Converting);
5201 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005202 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005203 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005204
5205 ExprResult RHSRes =
5206 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
5207 Best->Conversions[1], Sema::AA_Converting);
5208 if (RHSRes.isInvalid())
5209 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005210 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005211 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005212 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005213 return false;
John Wiegley01296292011-04-08 18:41:53 +00005214 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005215
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005216 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005217
5218 // Emit a better diagnostic if one of the expressions is a null pointer
5219 // constant and the other is a pointer type. In this case, the user most
5220 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005221 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005222 return true;
5223
5224 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005225 << LHS.get()->getType() << RHS.get()->getType()
5226 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005227 return true;
5228
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005229 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005230 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005231 << LHS.get()->getType() << RHS.get()->getType()
5232 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005233 // FIXME: Print the possible common types by printing the return types of
5234 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005235 break;
5236
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005237 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005238 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005239 }
5240 return true;
5241}
5242
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005243/// \brief Perform an "extended" implicit conversion as returned by
5244/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005245static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005246 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005247 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005248 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005249 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005250 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005251 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005252 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005253 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005254
John Wiegley01296292011-04-08 18:41:53 +00005255 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005256 return false;
5257}
5258
Sebastian Redl1a99f442009-04-16 17:51:27 +00005259/// \brief Check the operands of ?: under C++ semantics.
5260///
5261/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5262/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005263QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5264 ExprResult &RHS, ExprValueKind &VK,
5265 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005266 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005267 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5268 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005269
Richard Smith45edb702012-08-07 22:06:48 +00005270 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005271 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00005272 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005273 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005274 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005275 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005276 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005277 }
5278
John McCall7decc9e2010-11-18 06:31:45 +00005279 // Assume r-value.
5280 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005281 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005282
Sebastian Redl1a99f442009-04-16 17:51:27 +00005283 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005284 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005285 return Context.DependentTy;
5286
Richard Smith45edb702012-08-07 22:06:48 +00005287 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005288 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005289 QualType LTy = LHS.get()->getType();
5290 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005291 bool LVoid = LTy->isVoidType();
5292 bool RVoid = RTy->isVoidType();
5293 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005294 // ... one of the following shall hold:
5295 // -- The second or the third operand (but not both) is a (possibly
5296 // parenthesized) throw-expression; the result is of the type
5297 // and value category of the other.
5298 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5299 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5300 if (LThrow != RThrow) {
5301 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5302 VK = NonThrow->getValueKind();
5303 // DR (no number yet): the result is a bit-field if the
5304 // non-throw-expression operand is a bit-field.
5305 OK = NonThrow->getObjectKind();
5306 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005307 }
5308
Sebastian Redl1a99f442009-04-16 17:51:27 +00005309 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005310 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005311 if (LVoid && RVoid)
5312 return Context.VoidTy;
5313
5314 // Neither holds, error.
5315 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5316 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005317 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005318 return QualType();
5319 }
5320
5321 // Neither is void.
5322
Richard Smithf2b084f2012-08-08 06:13:49 +00005323 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005324 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005325 // either has (cv) class type [...] an attempt is made to convert each of
5326 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005327 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005328 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005329 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005330 QualType L2RType, R2LType;
5331 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005332 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005333 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005334 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005335 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005336
Sebastian Redl1a99f442009-04-16 17:51:27 +00005337 // If both can be converted, [...] the program is ill-formed.
5338 if (HaveL2R && HaveR2L) {
5339 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005340 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005341 return QualType();
5342 }
5343
5344 // If exactly one conversion is possible, that conversion is applied to
5345 // the chosen operand and the converted operands are used in place of the
5346 // original operands for the remainder of this section.
5347 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005348 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005349 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005350 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005351 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005352 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005353 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005354 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005355 }
5356 }
5357
Richard Smithf2b084f2012-08-08 06:13:49 +00005358 // C++11 [expr.cond]p3
5359 // if both are glvalues of the same value category and the same type except
5360 // for cv-qualification, an attempt is made to convert each of those
5361 // operands to the type of the other.
5362 ExprValueKind LVK = LHS.get()->getValueKind();
5363 ExprValueKind RVK = RHS.get()->getValueKind();
5364 if (!Context.hasSameType(LTy, RTy) &&
5365 Context.hasSameUnqualifiedType(LTy, RTy) &&
5366 LVK == RVK && LVK != VK_RValue) {
5367 // Since the unqualified types are reference-related and we require the
5368 // result to be as if a reference bound directly, the only conversion
5369 // we can perform is to add cv-qualifiers.
5370 Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
5371 Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
5372 if (RCVR.isStrictSupersetOf(LCVR)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005373 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005374 LTy = LHS.get()->getType();
5375 }
5376 else if (LCVR.isStrictSupersetOf(RCVR)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005377 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005378 RTy = RHS.get()->getType();
5379 }
5380 }
5381
5382 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005383 // If the second and third operands are glvalues of the same value
5384 // category and have the same type, the result is of that type and
5385 // value category and it is a bit-field if the second or the third
5386 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005387 // We only extend this to bitfields, not to the crazy other kinds of
5388 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005389 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005390 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005391 LHS.get()->isOrdinaryOrBitFieldObject() &&
5392 RHS.get()->isOrdinaryOrBitFieldObject()) {
5393 VK = LHS.get()->getValueKind();
5394 if (LHS.get()->getObjectKind() == OK_BitField ||
5395 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005396 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005397
5398 // If we have function pointer types, unify them anyway to unify their
5399 // exception specifications, if any.
5400 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5401 Qualifiers Qs = LTy.getQualifiers();
5402 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS, nullptr,
5403 /*ConvertArgs*/false);
5404 LTy = Context.getQualifiedType(LTy, Qs);
5405
5406 assert(!LTy.isNull() && "failed to find composite pointer type for "
5407 "canonically equivalent function ptr types");
5408 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5409 }
5410
John McCall7decc9e2010-11-18 06:31:45 +00005411 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005412 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005413
Richard Smithf2b084f2012-08-08 06:13:49 +00005414 // C++11 [expr.cond]p5
5415 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005416 // do not have the same type, and either has (cv) class type, ...
5417 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5418 // ... overload resolution is used to determine the conversions (if any)
5419 // to be applied to the operands. If the overload resolution fails, the
5420 // program is ill-formed.
5421 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5422 return QualType();
5423 }
5424
Richard Smithf2b084f2012-08-08 06:13:49 +00005425 // C++11 [expr.cond]p6
5426 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005427 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005428 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5429 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005430 if (LHS.isInvalid() || RHS.isInvalid())
5431 return QualType();
5432 LTy = LHS.get()->getType();
5433 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005434
5435 // After those conversions, one of the following shall hold:
5436 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005437 // is of that type. If the operands have class type, the result
5438 // is a prvalue temporary of the result type, which is
5439 // copy-initialized from either the second operand or the third
5440 // operand depending on the value of the first operand.
5441 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5442 if (LTy->isRecordType()) {
5443 // The operands have class type. Make a temporary copy.
David Blaikie6154ef92012-09-10 22:05:41 +00005444 if (RequireNonAbstractType(QuestionLoc, LTy,
5445 diag::err_allocation_of_abstract_type))
5446 return QualType();
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005447 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005448
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005449 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5450 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005451 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005452 if (LHSCopy.isInvalid())
5453 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005454
5455 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5456 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005457 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005458 if (RHSCopy.isInvalid())
5459 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005460
John Wiegley01296292011-04-08 18:41:53 +00005461 LHS = LHSCopy;
5462 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005463 }
5464
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005465 // If we have function pointer types, unify them anyway to unify their
5466 // exception specifications, if any.
5467 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5468 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5469 assert(!LTy.isNull() && "failed to find composite pointer type for "
5470 "canonically equivalent function ptr types");
5471 }
5472
Sebastian Redl1a99f442009-04-16 17:51:27 +00005473 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005474 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005475
Douglas Gregor46188682010-05-18 22:42:18 +00005476 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005477 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005478 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5479 /*AllowBothBool*/true,
5480 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005481
Sebastian Redl1a99f442009-04-16 17:51:27 +00005482 // -- The second and third operands have arithmetic or enumeration type;
5483 // the usual arithmetic conversions are performed to bring them to a
5484 // common type, and the result is of that type.
5485 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005486 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005487 if (LHS.isInvalid() || RHS.isInvalid())
5488 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005489 if (ResTy.isNull()) {
5490 Diag(QuestionLoc,
5491 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5492 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5493 return QualType();
5494 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005495
5496 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5497 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5498
5499 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005500 }
5501
5502 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005503 // type and the other is a null pointer constant, or both are null
5504 // pointer constants, at least one of which is non-integral; pointer
5505 // conversions and qualification conversions are performed to bring them
5506 // to their composite pointer type. The result is of the composite
5507 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005508 // -- The second and third operands have pointer to member type, or one has
5509 // pointer to member type and the other is a null pointer constant;
5510 // pointer to member conversions and qualification conversions are
5511 // performed to bring them to a common type, whose cv-qualification
5512 // shall match the cv-qualification of either the second or the third
5513 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005514 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005515 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Craig Topperc3ec1492014-05-26 06:22:03 +00005516 isSFINAEContext() ? nullptr
5517 : &NonStandardCompositeType);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005518 if (!Composite.isNull()) {
5519 if (NonStandardCompositeType)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005520 Diag(QuestionLoc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005521 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
5522 << LTy << RTy << Composite
John Wiegley01296292011-04-08 18:41:53 +00005523 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005524
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005525 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005526 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005527
Douglas Gregor697a3912010-04-01 22:47:07 +00005528 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005529 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5530 if (!Composite.isNull())
5531 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005532
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005533 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005534 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005535 return QualType();
5536
Sebastian Redl1a99f442009-04-16 17:51:27 +00005537 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005538 << LHS.get()->getType() << RHS.get()->getType()
5539 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005540 return QualType();
5541}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005542
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005543static FunctionProtoType::ExceptionSpecInfo
5544mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5545 FunctionProtoType::ExceptionSpecInfo ESI2,
5546 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5547 ExceptionSpecificationType EST1 = ESI1.Type;
5548 ExceptionSpecificationType EST2 = ESI2.Type;
5549
5550 // If either of them can throw anything, that is the result.
5551 if (EST1 == EST_None) return ESI1;
5552 if (EST2 == EST_None) return ESI2;
5553 if (EST1 == EST_MSAny) return ESI1;
5554 if (EST2 == EST_MSAny) return ESI2;
5555
5556 // If either of them is non-throwing, the result is the other.
5557 if (EST1 == EST_DynamicNone) return ESI2;
5558 if (EST2 == EST_DynamicNone) return ESI1;
5559 if (EST1 == EST_BasicNoexcept) return ESI2;
5560 if (EST2 == EST_BasicNoexcept) return ESI1;
5561
5562 // If either of them is a non-value-dependent computed noexcept, that
5563 // determines the result.
5564 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5565 !ESI2.NoexceptExpr->isValueDependent())
5566 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5567 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5568 !ESI1.NoexceptExpr->isValueDependent())
5569 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5570 // If we're left with value-dependent computed noexcept expressions, we're
5571 // stuck. Before C++17, we can just drop the exception specification entirely,
5572 // since it's not actually part of the canonical type. And this should never
5573 // happen in C++17, because it would mean we were computing the composite
5574 // pointer type of dependent types, which should never happen.
5575 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
5576 assert(!S.getLangOpts().CPlusPlus1z &&
5577 "computing composite pointer type of dependent types");
5578 return FunctionProtoType::ExceptionSpecInfo();
5579 }
5580
5581 // Switch over the possibilities so that people adding new values know to
5582 // update this function.
5583 switch (EST1) {
5584 case EST_None:
5585 case EST_DynamicNone:
5586 case EST_MSAny:
5587 case EST_BasicNoexcept:
5588 case EST_ComputedNoexcept:
5589 llvm_unreachable("handled above");
5590
5591 case EST_Dynamic: {
5592 // This is the fun case: both exception specifications are dynamic. Form
5593 // the union of the two lists.
5594 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5595 llvm::SmallPtrSet<QualType, 8> Found;
5596 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5597 for (QualType E : Exceptions)
5598 if (Found.insert(S.Context.getCanonicalType(E)).second)
5599 ExceptionTypeStorage.push_back(E);
5600
5601 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5602 Result.Exceptions = ExceptionTypeStorage;
5603 return Result;
5604 }
5605
5606 case EST_Unevaluated:
5607 case EST_Uninstantiated:
5608 case EST_Unparsed:
5609 llvm_unreachable("shouldn't see unresolved exception specifications here");
5610 }
5611
5612 llvm_unreachable("invalid ExceptionSpecificationType");
5613}
5614
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005615/// \brief Find a merged pointer type and convert the two expressions to it.
5616///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005617/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005618/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005619/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005620/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005621///
Douglas Gregor19175ff2010-04-16 23:20:25 +00005622/// \param Loc The location of the operator requiring these two expressions to
5623/// be converted to the composite pointer type.
5624///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005625/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
5626/// a non-standard (but still sane) composite type to which both expressions
5627/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
5628/// will be set true.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005629///
5630/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005631QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00005632 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005633 bool *NonStandardCompositeType,
5634 bool ConvertArgs) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005635 if (NonStandardCompositeType)
5636 *NonStandardCompositeType = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005637
David Blaikiebbafb8a2012-03-11 07:00:24 +00005638 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005639
5640 // C++1z [expr]p14:
5641 // The composite pointer type of two operands p1 and p2 having types T1
5642 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005643 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005644
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005645 // where at least one is a pointer or pointer to member type or
5646 // std::nullptr_t is:
5647 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5648 T1->isNullPtrType();
5649 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5650 T2->isNullPtrType();
5651 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00005652 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005653
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005654 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5655 // This can't actually happen, following the standard, but we also use this
5656 // to implement the end of [expr.conv], which hits this case.
5657 //
5658 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5659 if (T1IsPointerLike &&
5660 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005661 if (ConvertArgs)
5662 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5663 ? CK_NullToMemberPointer
5664 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005665 return T1;
5666 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005667 if (T2IsPointerLike &&
5668 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005669 if (ConvertArgs)
5670 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5671 ? CK_NullToMemberPointer
5672 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005673 return T2;
5674 }
Mike Stump11289f42009-09-09 15:08:12 +00005675
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005676 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005677 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005678 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005679 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
5680 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005681
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005682 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5683 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5684 // the union of cv1 and cv2;
5685 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5686 // "pointer to function", where the function types are otherwise the same,
5687 // "pointer to function";
5688 // FIXME: This rule is defective: it should also permit removing noexcept
5689 // from a pointer to member function. As a Clang extension, we also
5690 // permit removing 'noreturn', so we generalize this rule to;
5691 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5692 // "pointer to member function" and the pointee types can be unified
5693 // by a function pointer conversion, that conversion is applied
5694 // before checking the following rules.
5695 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5696 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5697 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5698 // respectively;
5699 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5700 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5701 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5702 // T1 or the cv-combined type of T1 and T2, respectively;
5703 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5704 // T2;
5705 //
5706 // If looked at in the right way, these bullets all do the same thing.
5707 // What we do here is, we build the two possible cv-combined types, and try
5708 // the conversions in both directions. If only one works, or if the two
5709 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00005710 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005711 //
5712 // Note that this will fail to find a composite pointer type for "pointer
5713 // to void" and "pointer to function". We can't actually perform the final
5714 // conversion in this case, even though a composite pointer type formally
5715 // exists.
5716 SmallVector<unsigned, 4> QualifierUnion;
5717 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005718 QualType Composite1 = T1;
5719 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005720 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005721 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005722 const PointerType *Ptr1, *Ptr2;
5723 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5724 (Ptr2 = Composite2->getAs<PointerType>())) {
5725 Composite1 = Ptr1->getPointeeType();
5726 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005727
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005728 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005729 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005730 if (NonStandardCompositeType &&
5731 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5732 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005733
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005734 QualifierUnion.push_back(
5735 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00005736 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005737 continue;
5738 }
Mike Stump11289f42009-09-09 15:08:12 +00005739
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005740 const MemberPointerType *MemPtr1, *MemPtr2;
5741 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5742 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5743 Composite1 = MemPtr1->getPointeeType();
5744 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005745
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005746 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005747 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005748 if (NonStandardCompositeType &&
5749 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5750 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005751
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005752 QualifierUnion.push_back(
5753 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5754 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5755 MemPtr2->getClass()));
5756 continue;
5757 }
Mike Stump11289f42009-09-09 15:08:12 +00005758
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005759 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00005760
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005761 // Cannot unwrap any more types.
5762 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005763 }
Mike Stump11289f42009-09-09 15:08:12 +00005764
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005765 // Apply the function pointer conversion to unify the types. We've already
5766 // unwrapped down to the function types, and we want to merge rather than
5767 // just convert, so do this ourselves rather than calling
5768 // IsFunctionConversion.
5769 //
5770 // FIXME: In order to match the standard wording as closely as possible, we
5771 // currently only do this under a single level of pointers. Ideally, we would
5772 // allow this in general, and set NeedConstBefore to the relevant depth on
5773 // the side(s) where we changed anything.
5774 if (QualifierUnion.size() == 1) {
5775 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5776 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5777 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5778 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5779
5780 // The result is noreturn if both operands are.
5781 bool Noreturn =
5782 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5783 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5784 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5785
5786 // The result is nothrow if both operands are.
5787 SmallVector<QualType, 8> ExceptionTypeStorage;
5788 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
5789 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
5790 ExceptionTypeStorage);
5791
5792 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
5793 FPT1->getParamTypes(), EPI1);
5794 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
5795 FPT2->getParamTypes(), EPI2);
5796 }
5797 }
5798 }
5799
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005800 if (NeedConstBefore && NonStandardCompositeType) {
5801 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005802 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005803 // requirements of C++ [conv.qual]p4 bullet 3.
5804 for (unsigned I = 0; I != NeedConstBefore; ++I) {
5805 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
5806 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
5807 *NonStandardCompositeType = true;
5808 }
5809 }
5810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005811
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005812 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005813 auto MOC = MemberOfClass.rbegin();
5814 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
5815 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
5816 auto Classes = *MOC++;
5817 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005818 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005819 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005820 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00005821 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005822 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005823 } else {
5824 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005825 Composite1 =
5826 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5827 Composite2 =
5828 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005829 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005830 }
5831
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005832 struct Conversion {
5833 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005834 Expr *&E1, *&E2;
5835 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00005836 InitializedEntity Entity;
5837 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005838 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00005839 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00005840
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005841 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
5842 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00005843 : S(S), E1(E1), E2(E2), Composite(Composite),
5844 Entity(InitializedEntity::InitializeTemporary(Composite)),
5845 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
5846 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
5847 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005848
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005849 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005850 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
5851 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005852 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005853 E1 = E1Result.getAs<Expr>();
5854
5855 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
5856 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005857 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005858 E2 = E2Result.getAs<Expr>();
5859
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005860 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005861 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005862 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00005863
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005864 // Try to convert to each composite pointer type.
5865 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005866 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
5867 if (ConvertArgs && C1.perform())
5868 return QualType();
5869 return C1.Composite;
5870 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005871 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005872
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005873 if (C1.Viable == C2.Viable) {
5874 // Either Composite1 and Composite2 are viable and are different, or
5875 // neither is viable.
5876 // FIXME: How both be viable and different?
5877 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005878 }
5879
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005880 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005881 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
5882 return QualType();
5883
5884 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005885}
Anders Carlsson85a307d2009-05-17 18:41:29 +00005886
John McCalldadc5752010-08-24 06:29:42 +00005887ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00005888 if (!E)
5889 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005890
John McCall31168b02011-06-15 23:02:42 +00005891 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
5892
5893 // If the result is a glvalue, we shouldn't bind it.
5894 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005895 return E;
Mike Stump11289f42009-09-09 15:08:12 +00005896
John McCall31168b02011-06-15 23:02:42 +00005897 // In ARC, calls that return a retainable type can return retained,
5898 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005899 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00005900 E->getType()->isObjCRetainableType()) {
5901
5902 bool ReturnsRetained;
5903
5904 // For actual calls, we compute this by examining the type of the
5905 // called value.
5906 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5907 Expr *Callee = Call->getCallee()->IgnoreParens();
5908 QualType T = Callee->getType();
5909
5910 if (T == Context.BoundMemberTy) {
5911 // Handle pointer-to-members.
5912 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5913 T = BinOp->getRHS()->getType();
5914 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5915 T = Mem->getMemberDecl()->getType();
5916 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005917
John McCall31168b02011-06-15 23:02:42 +00005918 if (const PointerType *Ptr = T->getAs<PointerType>())
5919 T = Ptr->getPointeeType();
5920 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
5921 T = Ptr->getPointeeType();
5922 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
5923 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00005924
John McCall31168b02011-06-15 23:02:42 +00005925 const FunctionType *FTy = T->getAs<FunctionType>();
5926 assert(FTy && "call to value not of function type?");
5927 ReturnsRetained = FTy->getExtInfo().getProducesResult();
5928
5929 // ActOnStmtExpr arranges things so that StmtExprs of retainable
5930 // type always produce a +1 object.
5931 } else if (isa<StmtExpr>(E)) {
5932 ReturnsRetained = true;
5933
Ted Kremeneke65b0862012-03-06 20:05:56 +00005934 // We hit this case with the lambda conversion-to-block optimization;
5935 // we don't want any extra casts here.
5936 } else if (isa<CastExpr>(E) &&
5937 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005938 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005939
John McCall31168b02011-06-15 23:02:42 +00005940 // For message sends and property references, we try to find an
5941 // actual method. FIXME: we should infer retention by selector in
5942 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00005943 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00005944 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005945 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
5946 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00005947 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
5948 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00005949 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
5950 D = ArrayLit->getArrayWithObjectsMethod();
5951 } else if (ObjCDictionaryLiteral *DictLit
5952 = dyn_cast<ObjCDictionaryLiteral>(E)) {
5953 D = DictLit->getDictWithObjectsMethod();
5954 }
John McCall31168b02011-06-15 23:02:42 +00005955
5956 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00005957
5958 // Don't do reclaims on performSelector calls; despite their
5959 // return type, the invoked method doesn't necessarily actually
5960 // return an object.
5961 if (!ReturnsRetained &&
5962 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005963 return E;
John McCall31168b02011-06-15 23:02:42 +00005964 }
5965
John McCall16de4d22011-11-14 19:53:16 +00005966 // Don't reclaim an object of Class type.
5967 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005968 return E;
John McCall16de4d22011-11-14 19:53:16 +00005969
Tim Shen4a05bb82016-06-21 20:29:17 +00005970 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00005971
John McCall2d637d22011-09-10 06:18:15 +00005972 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
5973 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005974 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
5975 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00005976 }
5977
David Blaikiebbafb8a2012-03-11 07:00:24 +00005978 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005979 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00005980
Peter Collingbournec331a1e2012-01-26 03:33:51 +00005981 // Search for the base element type (cf. ASTContext::getBaseElementType) with
5982 // a fast path for the common case that the type is directly a RecordType.
5983 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00005984 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00005985 while (!RT) {
5986 switch (T->getTypeClass()) {
5987 case Type::Record:
5988 RT = cast<RecordType>(T);
5989 break;
5990 case Type::ConstantArray:
5991 case Type::IncompleteArray:
5992 case Type::VariableArray:
5993 case Type::DependentSizedArray:
5994 T = cast<ArrayType>(T)->getElementType().getTypePtr();
5995 break;
5996 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005997 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00005998 }
5999 }
Mike Stump11289f42009-09-09 15:08:12 +00006000
Richard Smithfd555f62012-02-22 02:04:18 +00006001 // That should be enough to guarantee that this type is complete, if we're
6002 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006003 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006004 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006005 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006006
6007 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006008 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006009
John McCall31168b02011-06-15 23:02:42 +00006010 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006011 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006012 CheckDestructorAccess(E->getExprLoc(), Destructor,
6013 PDiag(diag::err_access_dtor_temp)
6014 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006015 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6016 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006017
Richard Smithfd555f62012-02-22 02:04:18 +00006018 // If destructor is trivial, we can avoid the extra copy.
6019 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006020 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006021
John McCall28fc7092011-11-10 05:35:25 +00006022 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006023 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006024 }
Richard Smitheec915d62012-02-18 04:13:32 +00006025
6026 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006027 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6028
6029 if (IsDecltype)
6030 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6031
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006032 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006033}
6034
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006035ExprResult
John McCall5d413782010-12-06 08:20:24 +00006036Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006037 if (SubExpr.isInvalid())
6038 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006039
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006040 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006041}
6042
John McCall28fc7092011-11-10 05:35:25 +00006043Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006044 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006045
Eli Friedman3bda6b12012-02-02 23:15:15 +00006046 CleanupVarDeclMarking();
6047
John McCall28fc7092011-11-10 05:35:25 +00006048 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6049 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006050 assert(Cleanup.exprNeedsCleanups() ||
6051 ExprCleanupObjects.size() == FirstCleanup);
6052 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006053 return SubExpr;
6054
Craig Topper5fc8fc22014-08-27 06:28:36 +00006055 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6056 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006057
Tim Shen4a05bb82016-06-21 20:29:17 +00006058 auto *E = ExprWithCleanups::Create(
6059 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006060 DiscardCleanupsInEvaluationContext();
6061
6062 return E;
6063}
6064
John McCall5d413782010-12-06 08:20:24 +00006065Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006066 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006067
Eli Friedman3bda6b12012-02-02 23:15:15 +00006068 CleanupVarDeclMarking();
6069
Tim Shen4a05bb82016-06-21 20:29:17 +00006070 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006071 return SubStmt;
6072
6073 // FIXME: In order to attach the temporaries, wrap the statement into
6074 // a StmtExpr; currently this is only used for asm statements.
6075 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6076 // a new AsmStmtWithTemporaries.
Nico Webera2a0eb92012-12-29 20:03:39 +00006077 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006078 SourceLocation(),
6079 SourceLocation());
6080 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6081 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006082 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006083}
6084
Richard Smithfd555f62012-02-22 02:04:18 +00006085/// Process the expression contained within a decltype. For such expressions,
6086/// certain semantic checks on temporaries are delayed until this point, and
6087/// are omitted for the 'topmost' call in the decltype expression. If the
6088/// topmost call bound a temporary, strip that temporary off the expression.
6089ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006090 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006091
6092 // C++11 [expr.call]p11:
6093 // If a function call is a prvalue of object type,
6094 // -- if the function call is either
6095 // -- the operand of a decltype-specifier, or
6096 // -- the right operand of a comma operator that is the operand of a
6097 // decltype-specifier,
6098 // a temporary object is not introduced for the prvalue.
6099
6100 // Recursively rebuild ParenExprs and comma expressions to strip out the
6101 // outermost CXXBindTemporaryExpr, if any.
6102 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6103 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6104 if (SubExpr.isInvalid())
6105 return ExprError();
6106 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006107 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006108 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006109 }
6110 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6111 if (BO->getOpcode() == BO_Comma) {
6112 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6113 if (RHS.isInvalid())
6114 return ExprError();
6115 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006116 return E;
6117 return new (Context) BinaryOperator(
6118 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6119 BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
Richard Smithfd555f62012-02-22 02:04:18 +00006120 }
6121 }
6122
6123 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006124 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6125 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006126 if (TopCall)
6127 E = TopCall;
6128 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006129 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006130
6131 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006132 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00006133
Richard Smithf86b0ae2012-07-28 19:54:11 +00006134 // In MS mode, don't perform any extra checking of call return types within a
6135 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006136 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006137 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006138
Richard Smithfd555f62012-02-22 02:04:18 +00006139 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006140 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6141 I != N; ++I) {
6142 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006143 if (Call == TopCall)
6144 continue;
6145
David Majnemerced8bdf2015-02-25 17:36:15 +00006146 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006147 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006148 Call, Call->getDirectCallee()))
6149 return ExprError();
6150 }
6151
6152 // Now all relevant types are complete, check the destructors are accessible
6153 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006154 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6155 I != N; ++I) {
6156 CXXBindTemporaryExpr *Bind =
6157 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006158 if (Bind == TopBind)
6159 continue;
6160
6161 CXXTemporary *Temp = Bind->getTemporary();
6162
6163 CXXRecordDecl *RD =
6164 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6165 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6166 Temp->setDestructor(Destructor);
6167
Richard Smith7d847b12012-05-11 22:20:10 +00006168 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6169 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006170 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006171 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006172 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6173 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006174
6175 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006176 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006177 }
6178
6179 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006180 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006181}
6182
Richard Smith79c927b2013-11-06 19:31:51 +00006183/// Note a set of 'operator->' functions that were used for a member access.
6184static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006185 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006186 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6187 // FIXME: Make this configurable?
6188 unsigned Limit = 9;
6189 if (OperatorArrows.size() > Limit) {
6190 // Produce Limit-1 normal notes and one 'skipping' note.
6191 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6192 SkipCount = OperatorArrows.size() - (Limit - 1);
6193 }
6194
6195 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6196 if (I == SkipStart) {
6197 S.Diag(OperatorArrows[I]->getLocation(),
6198 diag::note_operator_arrows_suppressed)
6199 << SkipCount;
6200 I += SkipCount;
6201 } else {
6202 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6203 << OperatorArrows[I]->getCallResultType();
6204 ++I;
6205 }
6206 }
6207}
6208
Nico Weber964d3322015-02-16 22:35:45 +00006209ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6210 SourceLocation OpLoc,
6211 tok::TokenKind OpKind,
6212 ParsedType &ObjectType,
6213 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006214 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006215 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006216 if (Result.isInvalid()) return ExprError();
6217 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006218
John McCall526ab472011-10-25 17:37:35 +00006219 Result = CheckPlaceholderExpr(Base);
6220 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006221 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006222
John McCallb268a282010-08-23 23:25:46 +00006223 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006224 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006225 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006226 // If we have a pointer to a dependent type and are using the -> operator,
6227 // the object type is the type that the pointer points to. We might still
6228 // have enough information about that type to do something useful.
6229 if (OpKind == tok::arrow)
6230 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6231 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006232
John McCallba7bf592010-08-24 05:47:05 +00006233 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006234 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006235 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006236 }
Mike Stump11289f42009-09-09 15:08:12 +00006237
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006238 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006239 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006240 // returned, with the original second operand.
6241 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006242 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006243 bool NoArrowOperatorFound = false;
6244 bool FirstIteration = true;
6245 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006246 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006247 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006248 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006249 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006250
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006251 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006252 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6253 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006254 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006255 noteOperatorArrows(*this, OperatorArrows);
6256 Diag(OpLoc, diag::note_operator_arrow_depth)
6257 << getLangOpts().ArrowDepth;
6258 return ExprError();
6259 }
6260
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006261 Result = BuildOverloadedArrowExpr(
6262 S, Base, OpLoc,
6263 // When in a template specialization and on the first loop iteration,
6264 // potentially give the default diagnostic (with the fixit in a
6265 // separate note) instead of having the error reported back to here
6266 // and giving a diagnostic with a fixit attached to the error itself.
6267 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006268 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006269 : &NoArrowOperatorFound);
6270 if (Result.isInvalid()) {
6271 if (NoArrowOperatorFound) {
6272 if (FirstIteration) {
6273 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006274 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006275 << FixItHint::CreateReplacement(OpLoc, ".");
6276 OpKind = tok::period;
6277 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006278 }
6279 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6280 << BaseType << Base->getSourceRange();
6281 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006282 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006283 Diag(CD->getLocStart(),
6284 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006285 }
6286 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006287 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006288 }
John McCallb268a282010-08-23 23:25:46 +00006289 Base = Result.get();
6290 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006291 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006292 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006293 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006294 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006295 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6296 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006297 return ExprError();
6298 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006299 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006300 }
Mike Stump11289f42009-09-09 15:08:12 +00006301
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006302 if (OpKind == tok::arrow &&
6303 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006304 BaseType = BaseType->getPointeeType();
6305 }
Mike Stump11289f42009-09-09 15:08:12 +00006306
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006307 // Objective-C properties allow "." access on Objective-C pointer types,
6308 // so adjust the base type to the object type itself.
6309 if (BaseType->isObjCObjectPointerType())
6310 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006311
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006312 // C++ [basic.lookup.classref]p2:
6313 // [...] If the type of the object expression is of pointer to scalar
6314 // type, the unqualified-id is looked up in the context of the complete
6315 // postfix-expression.
6316 //
6317 // This also indicates that we could be parsing a pseudo-destructor-name.
6318 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006319 // expressions or normal member (ivar or property) access expressions, and
6320 // it's legal for the type to be incomplete if this is a pseudo-destructor
6321 // call. We'll do more incomplete-type checks later in the lookup process,
6322 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006323 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006324 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006325 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006326 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006327 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006328 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006329 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006330 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006331 }
Mike Stump11289f42009-09-09 15:08:12 +00006332
Douglas Gregor3024f072012-04-16 07:05:22 +00006333 // The object type must be complete (or dependent), or
6334 // C++11 [expr.prim.general]p3:
6335 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006336 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006337 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006338 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006339 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006340 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006341 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006342
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006343 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006344 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006345 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006346 // type C (or of pointer to a class type C), the unqualified-id is looked
6347 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006348 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006349 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006350}
6351
Simon Pilgrim75c26882016-09-30 14:25:09 +00006352static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006353 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006354 if (Base->hasPlaceholderType()) {
6355 ExprResult result = S.CheckPlaceholderExpr(Base);
6356 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006357 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006358 }
6359 ObjectType = Base->getType();
6360
David Blaikie1d578782011-12-16 16:03:09 +00006361 // C++ [expr.pseudo]p2:
6362 // The left-hand side of the dot operator shall be of scalar type. The
6363 // left-hand side of the arrow operator shall be of pointer to scalar type.
6364 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006365 // Note that this is rather different from the normal handling for the
6366 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006367 if (OpKind == tok::arrow) {
6368 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6369 ObjectType = Ptr->getPointeeType();
6370 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006371 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006372 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6373 << ObjectType << true
6374 << FixItHint::CreateReplacement(OpLoc, ".");
6375 if (S.isSFINAEContext())
6376 return true;
6377
6378 OpKind = tok::period;
6379 }
6380 }
6381
6382 return false;
6383}
6384
John McCalldadc5752010-08-24 06:29:42 +00006385ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006386 SourceLocation OpLoc,
6387 tok::TokenKind OpKind,
6388 const CXXScopeSpec &SS,
6389 TypeSourceInfo *ScopeTypeInfo,
6390 SourceLocation CCLoc,
6391 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006392 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006393 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006394
Eli Friedman0ce4de42012-01-25 04:35:06 +00006395 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006396 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6397 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006398
Douglas Gregorc5c57342012-09-10 14:57:06 +00006399 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6400 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006401 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006402 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006403 else {
Nico Weber58829272012-01-23 05:50:57 +00006404 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6405 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006406 return ExprError();
6407 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006408 }
6409
6410 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006411 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006412 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006413 if (DestructedTypeInfo) {
6414 QualType DestructedType = DestructedTypeInfo->getType();
6415 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006416 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006417 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6418 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6419 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6420 << ObjectType << DestructedType << Base->getSourceRange()
6421 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006422
John McCall31168b02011-06-15 23:02:42 +00006423 // Recover by setting the destructed type to the object type.
6424 DestructedType = ObjectType;
6425 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregor678f90d2010-02-25 01:56:36 +00006426 DestructedTypeStart);
John McCall31168b02011-06-15 23:02:42 +00006427 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
Simon Pilgrim75c26882016-09-30 14:25:09 +00006428 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006429 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006430
John McCall31168b02011-06-15 23:02:42 +00006431 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6432 // Okay: just pretend that the user provided the correctly-qualified
6433 // type.
6434 } else {
6435 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6436 << ObjectType << DestructedType << Base->getSourceRange()
6437 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6438 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006439
John McCall31168b02011-06-15 23:02:42 +00006440 // Recover by setting the destructed type to the object type.
6441 DestructedType = ObjectType;
6442 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6443 DestructedTypeStart);
6444 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6445 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006446 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006447 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006448
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006449 // C++ [expr.pseudo]p2:
6450 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6451 // form
6452 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006453 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006454 //
6455 // shall designate the same scalar type.
6456 if (ScopeTypeInfo) {
6457 QualType ScopeType = ScopeTypeInfo->getType();
6458 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006459 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006460
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006461 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006462 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006463 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006464 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006465
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006466 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006467 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006468 }
6469 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006470
John McCallb268a282010-08-23 23:25:46 +00006471 Expr *Result
6472 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6473 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006474 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006475 ScopeTypeInfo,
6476 CCLoc,
6477 TildeLoc,
6478 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006479
David Majnemerced8bdf2015-02-25 17:36:15 +00006480 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006481}
6482
John McCalldadc5752010-08-24 06:29:42 +00006483ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006484 SourceLocation OpLoc,
6485 tok::TokenKind OpKind,
6486 CXXScopeSpec &SS,
6487 UnqualifiedId &FirstTypeName,
6488 SourceLocation CCLoc,
6489 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006490 UnqualifiedId &SecondTypeName) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006491 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6492 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6493 "Invalid first type name in pseudo-destructor");
6494 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6495 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6496 "Invalid second type name in pseudo-destructor");
6497
Eli Friedman0ce4de42012-01-25 04:35:06 +00006498 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006499 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6500 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006501
6502 // Compute the object type that we should use for name lookup purposes. Only
6503 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006504 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006505 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006506 if (ObjectType->isRecordType())
6507 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006508 else if (ObjectType->isDependentType())
6509 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006511
6512 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006513 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006514 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006515 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006516 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006517 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006518 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006519 SecondTypeName.StartLocation,
Fariborz Jahanian87967422011-02-08 18:05:59 +00006520 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006521 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006522 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6523 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006524 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006525 // couldn't find anything useful in scope. Just store the identifier and
6526 // it's location, and we'll perform (qualified) name lookup again at
6527 // template instantiation time.
6528 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6529 SecondTypeName.StartLocation);
6530 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006531 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006532 diag::err_pseudo_dtor_destructor_non_type)
6533 << SecondTypeName.Identifier << ObjectType;
6534 if (isSFINAEContext())
6535 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006536
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006537 // Recover by assuming we had the right type all along.
6538 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006539 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006540 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006541 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006542 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006543 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006544 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006545 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006546 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006547 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006548 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006549 TemplateId->TemplateNameLoc,
6550 TemplateId->LAngleLoc,
6551 TemplateArgsPtr,
6552 TemplateId->RAngleLoc);
6553 if (T.isInvalid() || !T.get()) {
6554 // Recover by assuming we had the right type all along.
6555 DestructedType = ObjectType;
6556 } else
6557 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006559
6560 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006561 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006562 if (!DestructedType.isNull()) {
6563 if (!DestructedTypeInfo)
6564 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006565 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006566 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6567 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006568
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006569 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006570 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006571 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006572 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006573 FirstTypeName.Identifier) {
6574 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006575 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006576 FirstTypeName.StartLocation,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006577 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006578 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006579 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006580 diag::err_pseudo_dtor_destructor_non_type)
6581 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006582
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006583 if (isSFINAEContext())
6584 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006585
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006586 // Just drop this type. It's unnecessary anyway.
6587 ScopeType = QualType();
6588 } else
6589 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006590 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006591 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006592 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006593 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006594 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006595 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006596 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006597 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006598 TemplateId->TemplateNameLoc,
6599 TemplateId->LAngleLoc,
6600 TemplateArgsPtr,
6601 TemplateId->RAngleLoc);
6602 if (T.isInvalid() || !T.get()) {
6603 // Recover by dropping this type.
6604 ScopeType = QualType();
6605 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006606 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006607 }
6608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006609
Douglas Gregor90ad9222010-02-24 23:02:30 +00006610 if (!ScopeType.isNull() && !ScopeTypeInfo)
6611 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6612 FirstTypeName.StartLocation);
6613
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006614
John McCallb268a282010-08-23 23:25:46 +00006615 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00006616 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006617 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00006618}
6619
David Blaikie1d578782011-12-16 16:03:09 +00006620ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6621 SourceLocation OpLoc,
6622 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006623 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006624 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00006625 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006626 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6627 return ExprError();
6628
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006629 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6630 false);
David Blaikie1d578782011-12-16 16:03:09 +00006631
6632 TypeLocBuilder TLB;
6633 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6634 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6635 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6636 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6637
6638 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006639 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006640 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00006641}
6642
John Wiegley01296292011-04-08 18:41:53 +00006643ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00006644 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006645 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00006646 if (Method->getParent()->isLambda() &&
6647 Method->getConversionType()->isBlockPointerType()) {
6648 // This is a lambda coversion to block pointer; check if the argument
6649 // is a LambdaExpr.
6650 Expr *SubE = E;
6651 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6652 if (CE && CE->getCastKind() == CK_NoOp)
6653 SubE = CE->getSubExpr();
6654 SubE = SubE->IgnoreParens();
6655 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6656 SubE = BE->getSubExpr();
6657 if (isa<LambdaExpr>(SubE)) {
6658 // For the conversion to block pointer on a lambda expression, we
6659 // construct a special BlockLiteral instead; this doesn't really make
6660 // a difference in ARC, but outside of ARC the resulting block literal
6661 // follows the normal lifetime rules for block literals instead of being
6662 // autoreleased.
6663 DiagnosticErrorTrap Trap(Diags);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006664 PushExpressionEvaluationContext(PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00006665 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6666 E->getExprLoc(),
6667 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006668 PopExpressionEvaluationContext();
6669
Eli Friedman98b01ed2012-03-01 04:01:32 +00006670 if (Exp.isInvalid())
6671 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6672 return Exp;
6673 }
6674 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00006675
Craig Topperc3ec1492014-05-26 06:22:03 +00006676 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006677 FoundDecl, Method);
6678 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00006679 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00006680
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00006681 MemberExpr *ME = new (Context) MemberExpr(
6682 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6683 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006684 if (HadMultipleCandidates)
6685 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00006686 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006687
Alp Toker314cc812014-01-25 16:55:45 +00006688 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00006689 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6690 ResultType = ResultType.getNonLValueExprType(Context);
6691
Douglas Gregor27381f32009-11-23 12:27:39 +00006692 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006693 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00006694 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006695 return CE;
6696}
6697
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006698ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6699 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00006700 // If the operand is an unresolved lookup expression, the expression is ill-
6701 // formed per [over.over]p1, because overloaded function names cannot be used
6702 // without arguments except in explicit contexts.
6703 ExprResult R = CheckPlaceholderExpr(Operand);
6704 if (R.isInvalid())
6705 return R;
6706
6707 // The operand may have been modified when checking the placeholder type.
6708 Operand = R.get();
6709
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006710 if (ActiveTemplateInstantiations.empty() &&
6711 Operand->HasSideEffects(Context, false)) {
6712 // The expression operand for noexcept is in an unevaluated expression
6713 // context, so side effects could result in unintended consequences.
6714 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6715 }
6716
Richard Smithf623c962012-04-17 00:58:00 +00006717 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006718 return new (Context)
6719 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006720}
6721
6722ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6723 Expr *Operand, SourceLocation RParen) {
6724 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00006725}
6726
Eli Friedmanf798f652012-05-24 22:04:19 +00006727static bool IsSpecialDiscardedValue(Expr *E) {
6728 // In C++11, discarded-value expressions of a certain form are special,
6729 // according to [expr]p10:
6730 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6731 // expression is an lvalue of volatile-qualified type and it has
6732 // one of the following forms:
6733 E = E->IgnoreParens();
6734
Eli Friedmanc49c2262012-05-24 22:36:31 +00006735 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006736 if (isa<DeclRefExpr>(E))
6737 return true;
6738
Eli Friedmanc49c2262012-05-24 22:36:31 +00006739 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006740 if (isa<ArraySubscriptExpr>(E))
6741 return true;
6742
Eli Friedmanc49c2262012-05-24 22:36:31 +00006743 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006744 if (isa<MemberExpr>(E))
6745 return true;
6746
Eli Friedmanc49c2262012-05-24 22:36:31 +00006747 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006748 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6749 if (UO->getOpcode() == UO_Deref)
6750 return true;
6751
6752 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00006753 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006754 if (BO->isPtrMemOp())
6755 return true;
6756
Eli Friedmanc49c2262012-05-24 22:36:31 +00006757 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00006758 if (BO->getOpcode() == BO_Comma)
6759 return IsSpecialDiscardedValue(BO->getRHS());
6760 }
6761
Eli Friedmanc49c2262012-05-24 22:36:31 +00006762 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00006763 // operands are one of the above, or
6764 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6765 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6766 IsSpecialDiscardedValue(CO->getFalseExpr());
6767 // The related edge case of "*x ?: *x".
6768 if (BinaryConditionalOperator *BCO =
6769 dyn_cast<BinaryConditionalOperator>(E)) {
6770 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6771 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6772 IsSpecialDiscardedValue(BCO->getFalseExpr());
6773 }
6774
6775 // Objective-C++ extensions to the rule.
6776 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6777 return true;
6778
6779 return false;
6780}
6781
John McCall34376a62010-12-04 03:47:34 +00006782/// Perform the conversions required for an expression used in a
6783/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00006784ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00006785 if (E->hasPlaceholderType()) {
6786 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006787 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006788 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00006789 }
6790
John McCallfee942d2010-12-02 02:07:15 +00006791 // C99 6.3.2.1:
6792 // [Except in specific positions,] an lvalue that does not have
6793 // array type is converted to the value stored in the
6794 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00006795 if (E->isRValue()) {
6796 // In C, function designators (i.e. expressions of function type)
6797 // are r-values, but we still want to do function-to-pointer decay
6798 // on them. This is both technically correct and convenient for
6799 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006800 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00006801 return DefaultFunctionArrayConversion(E);
6802
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006803 return E;
John McCalld68b2d02011-06-27 21:24:11 +00006804 }
John McCallfee942d2010-12-02 02:07:15 +00006805
Eli Friedmanf798f652012-05-24 22:04:19 +00006806 if (getLangOpts().CPlusPlus) {
6807 // The C++11 standard defines the notion of a discarded-value expression;
6808 // normally, we don't need to do anything to handle it, but if it is a
6809 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6810 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006811 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00006812 E->getType().isVolatileQualified() &&
6813 IsSpecialDiscardedValue(E)) {
6814 ExprResult Res = DefaultLvalueConversion(E);
6815 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006816 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006817 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006818 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006819 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00006820 }
John McCall34376a62010-12-04 03:47:34 +00006821
6822 // GCC seems to also exclude expressions of incomplete enum type.
6823 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6824 if (!T->getDecl()->isComplete()) {
6825 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006826 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006827 return E;
John McCall34376a62010-12-04 03:47:34 +00006828 }
6829 }
6830
John Wiegley01296292011-04-08 18:41:53 +00006831 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6832 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006833 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006834 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00006835
John McCallca61b652010-12-04 12:29:11 +00006836 if (!E->getType()->isVoidType())
6837 RequireCompleteType(E->getExprLoc(), E->getType(),
6838 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006839 return E;
John McCall34376a62010-12-04 03:47:34 +00006840}
6841
Faisal Valia17d19f2013-11-07 05:17:06 +00006842// If we can unambiguously determine whether Var can never be used
6843// in a constant expression, return true.
6844// - if the variable and its initializer are non-dependent, then
6845// we can unambiguously check if the variable is a constant expression.
6846// - if the initializer is not value dependent - we can determine whether
6847// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00006848// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00006849// never be a constant expression.
6850// - FXIME: if the initializer is dependent, we can still do some analysis and
6851// identify certain cases unambiguously as non-const by using a Visitor:
6852// - such as those that involve odr-use of a ParmVarDecl, involve a new
6853// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00006854static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00006855 ASTContext &Context) {
6856 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006857 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006858
6859 // If there is no initializer - this can not be a constant expression.
6860 if (!Var->getAnyInitializer(DefVD)) return true;
6861 assert(DefVD);
6862 if (DefVD->isWeak()) return false;
6863 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00006864
Faisal Valia17d19f2013-11-07 05:17:06 +00006865 Expr *Init = cast<Expr>(Eval->Value);
6866
6867 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00006868 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
6869 // of value-dependent expressions, and use it here to determine whether the
6870 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00006871 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00006872 }
6873
Simon Pilgrim75c26882016-09-30 14:25:09 +00006874 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00006875}
6876
Simon Pilgrim75c26882016-09-30 14:25:09 +00006877/// \brief Check if the current lambda has any potential captures
6878/// that must be captured by any of its enclosing lambdas that are ready to
6879/// capture. If there is a lambda that can capture a nested
6880/// potential-capture, go ahead and do so. Also, check to see if any
6881/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00006882/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00006883
Faisal Valiab3d6462013-12-07 20:22:44 +00006884static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
6885 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
6886
Simon Pilgrim75c26882016-09-30 14:25:09 +00006887 assert(!S.isUnevaluatedContext());
6888 assert(S.CurContext->isDependentContext());
6889 assert(CurrentLSI->CallOperator == S.CurContext &&
Faisal Valiab3d6462013-12-07 20:22:44 +00006890 "The current call operator must be synchronized with Sema's CurContext");
6891
6892 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
6893
6894 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
6895 S.FunctionScopes.data(), S.FunctionScopes.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00006896
Faisal Valiab3d6462013-12-07 20:22:44 +00006897 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00006898 // lambda (within a generic outer lambda), must be captured by an
6899 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00006900 const unsigned NumPotentialCaptures =
6901 CurrentLSI->getNumPotentialVariableCaptures();
6902 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006903 Expr *VarExpr = nullptr;
6904 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006905 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00006906 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00006907 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00006908 // need to check enclosing lambda's for speculative captures.
6909 // For e.g.:
6910 // Even though 'x' is not odr-used, it should be captured.
6911 // int test() {
6912 // const int x = 10;
6913 // auto L = [=](auto a) {
6914 // (void) +x + a;
6915 // };
6916 // }
6917 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00006918 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00006919 continue;
6920
6921 // If we have a capture-capable lambda for the variable, go ahead and
6922 // capture the variable in that lambda (and all its enclosing lambdas).
6923 if (const Optional<unsigned> Index =
6924 getStackIndexOfNearestEnclosingCaptureCapableLambda(
6925 FunctionScopesArrayRef, Var, S)) {
6926 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6927 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
6928 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00006929 }
6930 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00006931 VariableCanNeverBeAConstantExpression(Var, S.Context);
6932 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
6933 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00006934 // can not be used in a constant expression - which means
6935 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00006936 // capture violation early, if the variable is un-captureable.
6937 // This is purely for diagnosing errors early. Otherwise, this
6938 // error would get diagnosed when the lambda becomes capture ready.
6939 QualType CaptureType, DeclRefType;
6940 SourceLocation ExprLoc = VarExpr->getExprLoc();
6941 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006942 /*EllipsisLoc*/ SourceLocation(),
6943 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00006944 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00006945 // We will never be able to capture this variable, and we need
6946 // to be able to in any and all instantiations, so diagnose it.
6947 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006948 /*EllipsisLoc*/ SourceLocation(),
6949 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00006950 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00006951 }
6952 }
6953 }
6954
Faisal Valiab3d6462013-12-07 20:22:44 +00006955 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00006956 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00006957 // If we have a capture-capable lambda for 'this', go ahead and capture
6958 // 'this' in that lambda (and all its enclosing lambdas).
6959 if (const Optional<unsigned> Index =
6960 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Craig Topperc3ec1492014-05-26 06:22:03 +00006961 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00006962 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6963 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
6964 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
6965 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00006966 }
6967 }
Faisal Valiab3d6462013-12-07 20:22:44 +00006968
6969 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00006970 CurrentLSI->clearPotentialCaptures();
6971}
6972
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006973static ExprResult attemptRecovery(Sema &SemaRef,
6974 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00006975 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006976 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
6977 Consumer.getLookupResult().getLookupKind());
6978 const CXXScopeSpec *SS = Consumer.getSS();
6979 CXXScopeSpec NewSS;
6980
6981 // Use an approprate CXXScopeSpec for building the expr.
6982 if (auto *NNS = TC.getCorrectionSpecifier())
6983 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
6984 else if (SS && !TC.WillReplaceSpecifier())
6985 NewSS = *SS;
6986
Richard Smithde6d6c42015-12-29 19:43:10 +00006987 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00006988 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006989 R.addDecl(ND);
6990 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00006991 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006992 CXXRecordDecl *Record = nullptr;
6993 if (auto *NNS = TC.getCorrectionSpecifier())
6994 Record = NNS->getAsType()->getAsCXXRecordDecl();
6995 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00006996 Record =
6997 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
6998 if (Record)
6999 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007000
7001 // Detect and handle the case where the decl might be an implicit
7002 // member.
7003 bool MightBeImplicitMember;
7004 if (!Consumer.isAddressOfOperand())
7005 MightBeImplicitMember = true;
7006 else if (!NewSS.isEmpty())
7007 MightBeImplicitMember = false;
7008 else if (R.isOverloadedResult())
7009 MightBeImplicitMember = false;
7010 else if (R.isUnresolvableResult())
7011 MightBeImplicitMember = true;
7012 else
7013 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7014 isa<IndirectFieldDecl>(ND) ||
7015 isa<MSPropertyDecl>(ND);
7016
7017 if (MightBeImplicitMember)
7018 return SemaRef.BuildPossibleImplicitMemberExpr(
7019 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007020 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007021 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7022 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7023 Ivar->getIdentifier());
7024 }
7025 }
7026
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007027 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7028 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007029}
7030
Kaelyn Takata6c759512014-10-27 18:07:37 +00007031namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007032class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7033 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7034
7035public:
7036 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7037 : TypoExprs(TypoExprs) {}
7038 bool VisitTypoExpr(TypoExpr *TE) {
7039 TypoExprs.insert(TE);
7040 return true;
7041 }
7042};
7043
Kaelyn Takata6c759512014-10-27 18:07:37 +00007044class TransformTypos : public TreeTransform<TransformTypos> {
7045 typedef TreeTransform<TransformTypos> BaseTransform;
7046
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007047 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7048 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007049 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007050 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007051 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007052 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007053
7054 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7055 /// If the TypoExprs were successfully corrected, then the diagnostics should
7056 /// suggest the corrections. Otherwise the diagnostics will not suggest
7057 /// anything (having been passed an empty TypoCorrection).
7058 void EmitAllDiagnostics() {
7059 for (auto E : TypoExprs) {
7060 TypoExpr *TE = cast<TypoExpr>(E);
7061 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007062 if (State.DiagHandler) {
7063 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7064 ExprResult Replacement = TransformCache[TE];
7065
7066 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7067 // TypoCorrection, replacing the existing decls. This ensures the right
7068 // NamedDecl is used in diagnostics e.g. in the case where overload
7069 // resolution was used to select one from several possible decls that
7070 // had been stored in the TypoCorrection.
7071 if (auto *ND = getDeclFromExpr(
7072 Replacement.isInvalid() ? nullptr : Replacement.get()))
7073 TC.setCorrectionDecl(ND);
7074
7075 State.DiagHandler(TC);
7076 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007077 SemaRef.clearDelayedTypo(TE);
7078 }
7079 }
7080
7081 /// \brief If corrections for the first TypoExpr have been exhausted for a
7082 /// given combination of the other TypoExprs, retry those corrections against
7083 /// the next combination of substitutions for the other TypoExprs by advancing
7084 /// to the next potential correction of the second TypoExpr. For the second
7085 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7086 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7087 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7088 /// TransformCache). Returns true if there is still any untried combinations
7089 /// of corrections.
7090 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7091 for (auto TE : TypoExprs) {
7092 auto &State = SemaRef.getTypoExprState(TE);
7093 TransformCache.erase(TE);
7094 if (!State.Consumer->finished())
7095 return true;
7096 State.Consumer->resetCorrectionStream();
7097 }
7098 return false;
7099 }
7100
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007101 NamedDecl *getDeclFromExpr(Expr *E) {
7102 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7103 E = OverloadResolution[OE];
7104
7105 if (!E)
7106 return nullptr;
7107 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007108 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007109 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007110 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007111 // FIXME: Add any other expr types that could be be seen by the delayed typo
7112 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007113 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007114 return nullptr;
7115 }
7116
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007117 ExprResult TryTransform(Expr *E) {
7118 Sema::SFINAETrap Trap(SemaRef);
7119 ExprResult Res = TransformExpr(E);
7120 if (Trap.hasErrorOccurred() || Res.isInvalid())
7121 return ExprError();
7122
7123 return ExprFilter(Res.get());
7124 }
7125
Kaelyn Takata6c759512014-10-27 18:07:37 +00007126public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007127 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7128 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007129
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007130 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7131 MultiExprArg Args,
7132 SourceLocation RParenLoc,
7133 Expr *ExecConfig = nullptr) {
7134 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7135 RParenLoc, ExecConfig);
7136 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007137 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007138 Expr *ResultCall = Result.get();
7139 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7140 ResultCall = BE->getSubExpr();
7141 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7142 OverloadResolution[OE] = CE->getCallee();
7143 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007144 }
7145 return Result;
7146 }
7147
Kaelyn Takata6c759512014-10-27 18:07:37 +00007148 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7149
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007150 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7151
Saleem Abdulrasool407f36b2016-02-07 02:30:55 +00007152 ExprResult TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
7153 return Owned(E);
7154 }
7155
Saleem Abdulrasool02e19a12016-02-07 02:30:59 +00007156 ExprResult TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
7157 return Owned(E);
7158 }
7159
Kaelyn Takata6c759512014-10-27 18:07:37 +00007160 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007161 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007162 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007163 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007164
Kaelyn Takata6c759512014-10-27 18:07:37 +00007165 // Exit if either the transform was valid or if there were no TypoExprs
7166 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007167 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007168 !CheckAndAdvanceTypoExprCorrectionStreams())
7169 break;
7170 }
7171
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007172 // Ensure none of the TypoExprs have multiple typo correction candidates
7173 // with the same edit length that pass all the checks and filters.
7174 // TODO: Properly handle various permutations of possible corrections when
7175 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007176 // Also, disable typo correction while attempting the transform when
7177 // handling potentially ambiguous typo corrections as any new TypoExprs will
7178 // have been introduced by the application of one of the correction
7179 // candidates and add little to no value if corrected.
7180 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007181 while (!AmbiguousTypoExprs.empty()) {
7182 auto TE = AmbiguousTypoExprs.back();
7183 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007184 auto &State = SemaRef.getTypoExprState(TE);
7185 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007186 TransformCache.erase(TE);
7187 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007188 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007189 TransformCache.erase(TE);
7190 Res = ExprError();
7191 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007192 }
7193 AmbiguousTypoExprs.remove(TE);
7194 State.Consumer->restoreSavedPosition();
7195 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007196 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007197 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007198
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007199 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007200 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007201 FindTypoExprs(TypoExprs).TraverseStmt(E);
7202
Kaelyn Takata6c759512014-10-27 18:07:37 +00007203 EmitAllDiagnostics();
7204
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007205 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007206 }
7207
7208 ExprResult TransformTypoExpr(TypoExpr *E) {
7209 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7210 // cached transformation result if there is one and the TypoExpr isn't the
7211 // first one that was encountered.
7212 auto &CacheEntry = TransformCache[E];
7213 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7214 return CacheEntry;
7215 }
7216
7217 auto &State = SemaRef.getTypoExprState(E);
7218 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7219
7220 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7221 // typo correction and return it.
7222 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007223 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007224 continue;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007225 ExprResult NE = State.RecoveryHandler ?
7226 State.RecoveryHandler(SemaRef, E, TC) :
7227 attemptRecovery(SemaRef, *State.Consumer, TC);
7228 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007229 // Check whether there may be a second viable correction with the same
7230 // edit distance; if so, remember this TypoExpr may have an ambiguous
7231 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007232 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007233 if ((Next = State.Consumer->peekNextCorrection()) &&
7234 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7235 AmbiguousTypoExprs.insert(E);
7236 } else {
7237 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007238 }
7239 assert(!NE.isUnset() &&
7240 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007241 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007242 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007243 }
7244 return CacheEntry = ExprError();
7245 }
7246};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007247}
Faisal Valia17d19f2013-11-07 05:17:06 +00007248
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007249ExprResult
7250Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7251 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007252 // If the current evaluation context indicates there are uncorrected typos
7253 // and the current expression isn't guaranteed to not have typos, try to
7254 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007255 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007256 (E->isTypeDependent() || E->isValueDependent() ||
7257 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007258 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7259 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7260 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007261 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007262 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007263 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007264 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007265 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007266 ExprEvalContexts.back().NumTypos -= TyposResolved;
7267 return Result;
7268 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007269 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007270 }
7271 return E;
7272}
7273
Richard Smith945f8d32013-01-14 22:39:08 +00007274ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007275 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007276 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007277 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007278 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007279
7280 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007281 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007282
7283 // If we are an init-expression in a lambdas init-capture, we should not
7284 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007285 // containing full-expression is done).
7286 // template<class ... Ts> void test(Ts ... t) {
7287 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7288 // return a;
7289 // }() ...);
7290 // }
7291 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7292 // when we parse the lambda introducer, and teach capturing (but not
7293 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7294 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7295 // lambda where we've entered the introducer but not the body, or represent a
7296 // lambda where we've entered the body, depending on where the
7297 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007298 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007299 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007300 return ExprError();
7301
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007302 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007303 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007304 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007305 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007306 if (FullExpr.isInvalid())
7307 return ExprError();
7308 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007309
Richard Smith945f8d32013-01-14 22:39:08 +00007310 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007311 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007312 if (FullExpr.isInvalid())
7313 return ExprError();
7314
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007315 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007316 if (FullExpr.isInvalid())
7317 return ExprError();
7318 }
John Wiegley01296292011-04-08 18:41:53 +00007319
Kaelyn Takata49d84322014-11-11 23:26:56 +00007320 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7321 if (FullExpr.isInvalid())
7322 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007323
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007324 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007325
Simon Pilgrim75c26882016-09-30 14:25:09 +00007326 // At the end of this full expression (which could be a deeply nested
7327 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007328 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007329 // Consider the following code:
7330 // void f(int, int);
7331 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007332 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007333 // const int x = 10, y = 20;
7334 // auto L = [=](auto a) {
7335 // auto M = [=](auto b) {
7336 // f(x, b); <-- requires x to be captured by L and M
7337 // f(y, a); <-- requires y to be captured by L, but not all Ms
7338 // };
7339 // };
7340 // }
7341
Simon Pilgrim75c26882016-09-30 14:25:09 +00007342 // FIXME: Also consider what happens for something like this that involves
7343 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007344 // void f() {
7345 // const int n = 0;
7346 // auto L = [&](auto a) {
7347 // +n + ({ 0; a; });
7348 // };
7349 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007350 //
7351 // Here, we see +n, and then the full-expression 0; ends, so we don't
7352 // capture n (and instead remove it from our list of potential captures),
7353 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007354 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007355
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007356 LambdaScopeInfo *const CurrentLSI = getCurLambda();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007357 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007358 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007359 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007360 // By ensuring we are in the context of a lambda's call operator
7361 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007362 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007363 // PR, a proper fix would entail :
7364 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007365 // - Add to Sema an integer holding the smallest (outermost) scope
7366 // index that we are *lexically* within, and save/restore/set to
7367 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007368 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007369 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007370 // stop at the outermost enclosing lexical scope."
7371 const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
7372 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007373 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007374 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7375 *this);
John McCall5d413782010-12-06 08:20:24 +00007376 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007377}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007378
7379StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7380 if (!FullStmt) return StmtError();
7381
John McCall5d413782010-12-06 08:20:24 +00007382 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007383}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007384
Simon Pilgrim75c26882016-09-30 14:25:09 +00007385Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007386Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7387 CXXScopeSpec &SS,
7388 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007389 DeclarationName TargetName = TargetNameInfo.getName();
7390 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007391 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007392
Douglas Gregor43edb322011-10-24 22:31:10 +00007393 // If the name itself is dependent, then the result is dependent.
7394 if (TargetName.isDependentName())
7395 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007396
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007397 // Do the redeclaration lookup in the current scope.
7398 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7399 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007400 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007401 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007402
Douglas Gregor43edb322011-10-24 22:31:10 +00007403 switch (R.getResultKind()) {
7404 case LookupResult::Found:
7405 case LookupResult::FoundOverloaded:
7406 case LookupResult::FoundUnresolvedValue:
7407 case LookupResult::Ambiguous:
7408 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007409
Douglas Gregor43edb322011-10-24 22:31:10 +00007410 case LookupResult::NotFound:
7411 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007412
Douglas Gregor43edb322011-10-24 22:31:10 +00007413 case LookupResult::NotFoundInCurrentInstantiation:
7414 return IER_Dependent;
7415 }
David Blaikie8a40f702012-01-17 06:56:22 +00007416
7417 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007418}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007419
Simon Pilgrim75c26882016-09-30 14:25:09 +00007420Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007421Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7422 bool IsIfExists, CXXScopeSpec &SS,
7423 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007424 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007425
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007426 // Check for unexpanded parameter packs.
7427 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
7428 collectUnexpandedParameterPacks(SS, Unexpanded);
7429 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
7430 if (!Unexpanded.empty()) {
7431 DiagnoseUnexpandedParameterPacks(KeywordLoc,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007432 IsIfExists? UPPC_IfExists
7433 : UPPC_IfNotExists,
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007434 Unexpanded);
7435 return IER_Error;
7436 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007437
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007438 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7439}