blob: 3392d1021844c16ebe7dbb8b7e84bec413900059 [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
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001153 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001154 // 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
Serge Pavlov38526372016-11-12 15:38:55 +00001224 // Handle errors like: int({0})
1225 if (exprs.size() == 1 && !canInitializeWithParenthesizedList(Ty) &&
1226 LParenLoc.isValid() && RParenLoc.isValid())
1227 if (auto IList = dyn_cast<InitListExpr>(exprs[0])) {
1228 Diag(TInfo->getTypeLoc().getLocStart(), diag::err_list_init_in_parens)
1229 << Ty << IList->getSourceRange()
1230 << FixItHint::CreateRemoval(LParenLoc)
1231 << FixItHint::CreateRemoval(RParenLoc);
1232 LParenLoc = RParenLoc = SourceLocation();
1233 }
1234
Richard Smithb8c414c2016-06-30 20:24:30 +00001235 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1236 // Avoid creating a non-type-dependent expression that contains typos.
1237 // Non-type-dependent expressions are liable to be discarded without
1238 // checking for embedded typos.
1239 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1240 !Result.get()->isTypeDependent())
1241 Result = CorrectDelayedTyposInExpr(Result.get());
1242 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001243}
1244
1245/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1246/// Can be interpreted either as function-style casting ("int(x)")
1247/// or class type construction ("ClassType(x,y,z)")
1248/// or creation of a value-initialized type ("int()").
1249ExprResult
1250Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1251 SourceLocation LParenLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001252 MultiExprArg Exprs,
Douglas Gregor2b88c112010-09-08 00:15:04 +00001253 SourceLocation RParenLoc) {
1254 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001255 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001256
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001257 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001258 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1259 RParenLoc);
Douglas Gregor0950e412009-03-13 21:01:28 +00001260 }
1261
Sebastian Redld74dd492012-02-12 18:41:05 +00001262 bool ListInitialization = LParenLoc.isInvalid();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001263 assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
Sebastian Redld74dd492012-02-12 18:41:05 +00001264 && "List initialization must have initializer list as expression.");
1265 SourceRange FullRange = SourceRange(TyBeginLoc,
1266 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1267
Douglas Gregordd04d332009-01-16 18:33:17 +00001268 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001269 // If the expression list is a single expression, the type conversion
1270 // expression is equivalent (in definedness, and if defined in meaning) to the
1271 // corresponding cast expression.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001272 if (Exprs.size() == 1 && !ListInitialization) {
John McCallb50451a2011-10-05 07:41:44 +00001273 Expr *Arg = Exprs[0];
John McCallb50451a2011-10-05 07:41:44 +00001274 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001275 }
1276
David Majnemer7eddcff2015-09-14 07:05:00 +00001277 // C++14 [expr.type.conv]p2: The expression T(), where T is a
1278 // simple-type-specifier or typename-specifier for a non-array complete
1279 // object type or the (possibly cv-qualified) void type, creates a prvalue
1280 // of the specified type, whose value is that produced by value-initializing
1281 // an object of type T.
Eli Friedman576cbd02012-02-29 00:00:28 +00001282 QualType ElemTy = Ty;
1283 if (Ty->isArrayType()) {
1284 if (!ListInitialization)
1285 return ExprError(Diag(TyBeginLoc,
1286 diag::err_value_init_for_array_type) << FullRange);
1287 ElemTy = Context.getBaseElementType(Ty);
1288 }
1289
David Majnemer7eddcff2015-09-14 07:05:00 +00001290 if (!ListInitialization && Ty->isFunctionType())
1291 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_function_type)
1292 << FullRange);
1293
Eli Friedman576cbd02012-02-29 00:00:28 +00001294 if (!Ty->isVoidType() &&
1295 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001296 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001297 return ExprError();
1298
1299 if (RequireNonAbstractType(TyBeginLoc, Ty,
1300 diag::err_allocation_of_abstract_type))
1301 return ExprError();
1302
Douglas Gregor8ec51732010-09-08 21:40:08 +00001303 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001304 InitializationKind Kind =
1305 Exprs.size() ? ListInitialization
1306 ? InitializationKind::CreateDirectList(TyBeginLoc)
1307 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
1308 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1309 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1310 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001311
Richard Smith90061902013-09-23 02:20:00 +00001312 if (Result.isInvalid() || !ListInitialization)
1313 return Result;
1314
1315 Expr *Inner = Result.get();
1316 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1317 Inner = BTE->getSubExpr();
Richard Smith1ae689c2015-01-28 22:06:01 +00001318 if (!isa<CXXTemporaryObjectExpr>(Inner)) {
1319 // If we created a CXXTemporaryObjectExpr, that node also represents the
1320 // functional cast. Otherwise, create an explicit cast to represent
1321 // the syntactic form of a functional-style cast that was used here.
1322 //
1323 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1324 // would give a more consistent AST representation than using a
1325 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1326 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001327 QualType ResultType = Result.get()->getType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001328 Result = CXXFunctionalCastExpr::Create(
Richard Smith90061902013-09-23 02:20:00 +00001329 Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001330 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
Sebastian Redl2b80af42012-02-13 19:55:43 +00001331 }
1332
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001333 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001334}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001335
Richard Smithb2f0f052016-10-10 18:54:32 +00001336/// \brief Determine whether the given function is a non-placement
1337/// deallocation function.
1338static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1339 if (FD->isInvalidDecl())
1340 return false;
1341
1342 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1343 return Method->isUsualDeallocationFunction();
1344
1345 if (FD->getOverloadedOperator() != OO_Delete &&
1346 FD->getOverloadedOperator() != OO_Array_Delete)
1347 return false;
1348
1349 unsigned UsualParams = 1;
1350
1351 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1352 S.Context.hasSameUnqualifiedType(
1353 FD->getParamDecl(UsualParams)->getType(),
1354 S.Context.getSizeType()))
1355 ++UsualParams;
1356
1357 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1358 S.Context.hasSameUnqualifiedType(
1359 FD->getParamDecl(UsualParams)->getType(),
1360 S.Context.getTypeDeclType(S.getStdAlignValT())))
1361 ++UsualParams;
1362
1363 return UsualParams == FD->getNumParams();
1364}
1365
1366namespace {
1367 struct UsualDeallocFnInfo {
1368 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001369 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001370 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smithf75dcbe2016-10-11 00:21:10 +00001371 HasSizeT(false), HasAlignValT(false), CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001372 // A function template declaration is never a usual deallocation function.
1373 if (!FD)
1374 return;
1375 if (FD->getNumParams() == 3)
1376 HasAlignValT = HasSizeT = true;
1377 else if (FD->getNumParams() == 2) {
1378 HasSizeT = FD->getParamDecl(1)->getType()->isIntegerType();
1379 HasAlignValT = !HasSizeT;
1380 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001381
1382 // In CUDA, determine how much we'd like / dislike to call this.
1383 if (S.getLangOpts().CUDA)
1384 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1385 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001386 }
1387
1388 operator bool() const { return FD; }
1389
Richard Smithf75dcbe2016-10-11 00:21:10 +00001390 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1391 bool WantAlign) const {
1392 // C++17 [expr.delete]p10:
1393 // If the type has new-extended alignment, a function with a parameter
1394 // of type std::align_val_t is preferred; otherwise a function without
1395 // such a parameter is preferred
1396 if (HasAlignValT != Other.HasAlignValT)
1397 return HasAlignValT == WantAlign;
1398
1399 if (HasSizeT != Other.HasSizeT)
1400 return HasSizeT == WantSize;
1401
1402 // Use CUDA call preference as a tiebreaker.
1403 return CUDAPref > Other.CUDAPref;
1404 }
1405
Richard Smithb2f0f052016-10-10 18:54:32 +00001406 DeclAccessPair Found;
1407 FunctionDecl *FD;
1408 bool HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001409 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001410 };
1411}
1412
1413/// Determine whether a type has new-extended alignment. This may be called when
1414/// the type is incomplete (for a delete-expression with an incomplete pointee
1415/// type), in which case it will conservatively return false if the alignment is
1416/// not known.
1417static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1418 return S.getLangOpts().AlignedAllocation &&
1419 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1420 S.getASTContext().getTargetInfo().getNewAlign();
1421}
1422
1423/// Select the correct "usual" deallocation function to use from a selection of
1424/// deallocation functions (either global or class-scope).
1425static UsualDeallocFnInfo resolveDeallocationOverload(
1426 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1427 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1428 UsualDeallocFnInfo Best;
1429
Richard Smithb2f0f052016-10-10 18:54:32 +00001430 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001431 UsualDeallocFnInfo Info(S, I.getPair());
1432 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1433 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001434 continue;
1435
1436 if (!Best) {
1437 Best = Info;
1438 if (BestFns)
1439 BestFns->push_back(Info);
1440 continue;
1441 }
1442
Richard Smithf75dcbe2016-10-11 00:21:10 +00001443 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001444 continue;
1445
1446 // If more than one preferred function is found, all non-preferred
1447 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001448 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001449 BestFns->clear();
1450
1451 Best = Info;
1452 if (BestFns)
1453 BestFns->push_back(Info);
1454 }
1455
1456 return Best;
1457}
1458
1459/// Determine whether a given type is a class for which 'delete[]' would call
1460/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1461/// we need to store the array size (even if the type is
1462/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001463static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1464 QualType allocType) {
1465 const RecordType *record =
1466 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1467 if (!record) return false;
1468
1469 // Try to find an operator delete[] in class scope.
1470
1471 DeclarationName deleteName =
1472 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1473 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1474 S.LookupQualifiedName(ops, record->getDecl());
1475
1476 // We're just doing this for information.
1477 ops.suppressDiagnostics();
1478
1479 // Very likely: there's no operator delete[].
1480 if (ops.empty()) return false;
1481
1482 // If it's ambiguous, it should be illegal to call operator delete[]
1483 // on this thing, so it doesn't matter if we allocate extra space or not.
1484 if (ops.isAmbiguous()) return false;
1485
Richard Smithb2f0f052016-10-10 18:54:32 +00001486 // C++17 [expr.delete]p10:
1487 // If the deallocation functions have class scope, the one without a
1488 // parameter of type std::size_t is selected.
1489 auto Best = resolveDeallocationOverload(
1490 S, ops, /*WantSize*/false,
1491 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1492 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001493}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001494
Sebastian Redld74dd492012-02-12 18:41:05 +00001495/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001496///
Sebastian Redld74dd492012-02-12 18:41:05 +00001497/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001498/// @code new (memory) int[size][4] @endcode
1499/// or
1500/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001501///
1502/// \param StartLoc The first location of the expression.
1503/// \param UseGlobal True if 'new' was prefixed with '::'.
1504/// \param PlacementLParen Opening paren of the placement arguments.
1505/// \param PlacementArgs Placement new arguments.
1506/// \param PlacementRParen Closing paren of the placement arguments.
1507/// \param TypeIdParens If the type is in parens, the source range.
1508/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001509/// \param Initializer The initializing expression or initializer-list, or null
1510/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001511ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001512Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001513 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001514 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001515 Declarator &D, Expr *Initializer) {
Richard Smith74aeef52013-04-26 16:15:35 +00001516 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
Richard Smith30482bc2011-02-20 03:19:35 +00001517
Craig Topperc3ec1492014-05-26 06:22:03 +00001518 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001519 // If the specified type is an array, unwrap it and save the expression.
1520 if (D.getNumTypeObjects() > 0 &&
1521 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
James Dennettf14a6e52012-06-15 22:23:43 +00001522 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith30482bc2011-02-20 03:19:35 +00001523 if (TypeContainsAuto)
1524 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1525 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001526 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001527 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1528 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001529 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001530 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1531 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001532
Sebastian Redl351bb782008-12-02 14:43:59 +00001533 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001534 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001535 }
1536
Douglas Gregor73341c42009-09-11 00:18:58 +00001537 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001538 if (ArraySize) {
1539 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001540 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1541 break;
1542
1543 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1544 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001545 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001546 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001547 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1548 // shall be a converted constant expression (5.19) of type std::size_t
1549 // and shall evaluate to a strictly positive value.
1550 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1551 assert(IntWidth && "Builtin type of size 0?");
1552 llvm::APSInt Value(IntWidth);
1553 Array.NumElts
1554 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1555 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001556 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001557 } else {
1558 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001559 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001560 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001561 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001562 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001563 if (!Array.NumElts)
1564 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001565 }
1566 }
1567 }
1568 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001569
Craig Topperc3ec1492014-05-26 06:22:03 +00001570 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001571 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001572 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001573 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001574
Sebastian Redl6047f072012-02-16 12:22:20 +00001575 SourceRange DirectInitRange;
Serge Pavlov38526372016-11-12 15:38:55 +00001576 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001577 DirectInitRange = List->getSourceRange();
Serge Pavlov38526372016-11-12 15:38:55 +00001578 // Handle errors like: new int a({0})
1579 if (List->getNumExprs() == 1 &&
1580 !canInitializeWithParenthesizedList(AllocType))
1581 if (auto IList = dyn_cast<InitListExpr>(List->getExpr(0))) {
1582 Diag(TInfo->getTypeLoc().getLocStart(), diag::err_list_init_in_parens)
1583 << AllocType << List->getSourceRange()
1584 << FixItHint::CreateRemoval(List->getLocStart())
1585 << FixItHint::CreateRemoval(List->getLocEnd());
1586 DirectInitRange = SourceRange();
1587 Initializer = IList;
1588 }
1589 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001590
David Blaikie7b97aef2012-11-07 00:12:38 +00001591 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001592 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001593 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001594 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001595 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001596 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001597 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001598 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001599 DirectInitRange,
1600 Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001601 TypeContainsAuto);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001602}
1603
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001604static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1605 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001606 if (!Init)
1607 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001608 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1609 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001610 if (isa<ImplicitValueInitExpr>(Init))
1611 return true;
1612 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1613 return !CCE->isListInitialization() &&
1614 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001615 else if (Style == CXXNewExpr::ListInit) {
1616 assert(isa<InitListExpr>(Init) &&
1617 "Shouldn't create list CXXConstructExprs for arrays.");
1618 return true;
1619 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001620 return false;
1621}
1622
John McCalldadc5752010-08-24 06:29:42 +00001623ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001624Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001625 SourceLocation PlacementLParen,
1626 MultiExprArg PlacementArgs,
1627 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001628 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001629 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001630 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001631 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001632 SourceRange DirectInitRange,
1633 Expr *Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001634 bool TypeMayContainAuto) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001635 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001636 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001637
Sebastian Redl6047f072012-02-16 12:22:20 +00001638 CXXNewExpr::InitializationStyle initStyle;
1639 if (DirectInitRange.isValid()) {
1640 assert(Initializer && "Have parens but no initializer.");
1641 initStyle = CXXNewExpr::CallInit;
1642 } else if (Initializer && isa<InitListExpr>(Initializer))
1643 initStyle = CXXNewExpr::ListInit;
1644 else {
1645 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1646 isa<CXXConstructExpr>(Initializer)) &&
1647 "Initializer expression that cannot have been implicitly created.");
1648 initStyle = CXXNewExpr::NoInit;
1649 }
1650
1651 Expr **Inits = &Initializer;
1652 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001653 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1654 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1655 Inits = List->getExprs();
1656 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001657 }
1658
Richard Smith66204ec2014-03-12 17:42:45 +00001659 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00001660 if (TypeMayContainAuto && AllocType->isUndeducedType()) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001661 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001662 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1663 << AllocType << TypeRange);
Richard Smith66204ec2014-03-12 17:42:45 +00001664 if (initStyle == CXXNewExpr::ListInit ||
1665 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001666 return ExprError(Diag(Inits[0]->getLocStart(),
Richard Smith66204ec2014-03-12 17:42:45 +00001667 diag::err_auto_new_list_init)
Sebastian Redl6047f072012-02-16 12:22:20 +00001668 << AllocType << TypeRange);
1669 if (NumInits > 1) {
1670 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001671 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001672 diag::err_auto_new_ctor_multiple_expressions)
1673 << AllocType << TypeRange);
1674 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001675 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001676 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001677 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001678 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001679 << AllocType << Deduce->getType()
1680 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001681 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001682 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001683 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001684 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001685
Douglas Gregorcda95f42010-05-16 16:01:03 +00001686 // Per C++0x [expr.new]p5, the type being constructed may be a
1687 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001688 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001689 if (const ConstantArrayType *Array
1690 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001691 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1692 Context.getSizeType(),
1693 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001694 AllocType = Array->getElementType();
1695 }
1696 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001697
Douglas Gregor3999e152010-10-06 16:00:31 +00001698 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1699 return ExprError();
1700
Craig Topperc3ec1492014-05-26 06:22:03 +00001701 if (initStyle == CXXNewExpr::ListInit &&
1702 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001703 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1704 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001705 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001706 }
1707
Simon Pilgrim75c26882016-09-30 14:25:09 +00001708 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001709 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001710 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1711 AllocType->isObjCLifetimeType()) {
1712 AllocType = Context.getLifetimeQualifiedType(AllocType,
1713 AllocType->getObjCARCImplicitLifetime());
1714 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001715
John McCall31168b02011-06-15 23:02:42 +00001716 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001717
John McCall5e77d762013-04-16 07:28:30 +00001718 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1719 ExprResult result = CheckPlaceholderExpr(ArraySize);
1720 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001721 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001722 }
Richard Smith8dd34252012-02-04 07:07:42 +00001723 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1724 // integral or enumeration type with a non-negative value."
1725 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1726 // enumeration type, or a class type for which a single non-explicit
1727 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001728 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001729 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001730 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001731 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001732 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001733 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001734 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1735
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001736 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1737 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001738
Simon Pilgrim75c26882016-09-30 14:25:09 +00001739 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001740 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001741 // Diagnose the compatibility of this conversion.
1742 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1743 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001744 } else {
1745 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1746 protected:
1747 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001748
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001749 public:
1750 SizeConvertDiagnoser(Expr *ArraySize)
1751 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1752 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001753
1754 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1755 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001756 return S.Diag(Loc, diag::err_array_size_not_integral)
1757 << S.getLangOpts().CPlusPlus11 << T;
1758 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001759
1760 SemaDiagnosticBuilder diagnoseIncomplete(
1761 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001762 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1763 << T << ArraySize->getSourceRange();
1764 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001765
1766 SemaDiagnosticBuilder diagnoseExplicitConv(
1767 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001768 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1769 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001770
1771 SemaDiagnosticBuilder noteExplicitConv(
1772 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001773 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1774 << ConvTy->isEnumeralType() << ConvTy;
1775 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001776
1777 SemaDiagnosticBuilder diagnoseAmbiguous(
1778 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001779 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1780 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001781
1782 SemaDiagnosticBuilder noteAmbiguous(
1783 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001784 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1785 << ConvTy->isEnumeralType() << ConvTy;
1786 }
Richard Smithccc11812013-05-21 19:05:48 +00001787
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001788 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1789 QualType T,
1790 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001791 return S.Diag(Loc,
1792 S.getLangOpts().CPlusPlus11
1793 ? diag::warn_cxx98_compat_array_size_conversion
1794 : diag::ext_array_size_conversion)
1795 << T << ConvTy->isEnumeralType() << ConvTy;
1796 }
1797 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001798
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001799 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1800 SizeDiagnoser);
1801 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001802 if (ConvertedSize.isInvalid())
1803 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001804
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001805 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001806 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001807
Douglas Gregor0bf31402010-10-08 23:50:27 +00001808 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001809 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001810
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001811 // C++98 [expr.new]p7:
1812 // The expression in a direct-new-declarator shall have integral type
1813 // with a non-negative value.
1814 //
Richard Smith0511d232016-10-05 22:41:02 +00001815 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1816 // per CWG1464. Otherwise, if it's not a constant, we must have an
1817 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001818 if (!ArraySize->isValueDependent()) {
1819 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001820 // We've already performed any required implicit conversion to integer or
1821 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001822 // FIXME: Per CWG1464, we are required to check the value prior to
1823 // converting to size_t. This will never find a negative array size in
1824 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001825 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001826 if (Value.isSigned() && Value.isNegative()) {
1827 return ExprError(Diag(ArraySize->getLocStart(),
1828 diag::err_typecheck_negative_array_size)
1829 << ArraySize->getSourceRange());
1830 }
1831
1832 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001833 unsigned ActiveSizeBits =
1834 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00001835 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1836 return ExprError(Diag(ArraySize->getLocStart(),
1837 diag::err_array_too_large)
1838 << Value.toString(10)
1839 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001840 }
Richard Smith0511d232016-10-05 22:41:02 +00001841
1842 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00001843 } else if (TypeIdParens.isValid()) {
1844 // Can't have dynamic array size when the type-id is in parentheses.
1845 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1846 << ArraySize->getSourceRange()
1847 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1848 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001849
Douglas Gregorf2753b32010-07-13 15:54:32 +00001850 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001851 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001853
John McCall036f2f62011-05-15 07:14:44 +00001854 // Note that we do *not* convert the argument in any way. It can
1855 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001856 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001857
Craig Topperc3ec1492014-05-26 06:22:03 +00001858 FunctionDecl *OperatorNew = nullptr;
1859 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00001860 unsigned Alignment =
1861 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1862 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1863 bool PassAlignment = getLangOpts().AlignedAllocation &&
1864 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001865
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001866 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001867 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001868 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001869 SourceRange(PlacementLParen, PlacementRParen),
Richard Smithb2f0f052016-10-10 18:54:32 +00001870 UseGlobal, AllocType, ArraySize, PassAlignment,
1871 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001872 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001873
1874 // If this is an array allocation, compute whether the usual array
1875 // deallocation function for the type has a size_t parameter.
1876 bool UsualArrayDeleteWantsSize = false;
1877 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00001878 UsualArrayDeleteWantsSize =
1879 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00001880
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001881 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001882 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001883 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00001884 OperatorNew->getType()->getAs<FunctionProtoType>();
1885 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1886 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001887
Richard Smithd6f9e732014-05-13 19:56:21 +00001888 // We've already converted the placement args, just fill in any default
1889 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00001890 // argument. Skip the second parameter too if we're passing in the
1891 // alignment; we've already filled it in.
1892 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
1893 PassAlignment ? 2 : 1, PlacementArgs,
1894 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001895 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001896
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001897 if (!AllPlaceArgs.empty())
1898 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00001899
Richard Smithd6f9e732014-05-13 19:56:21 +00001900 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001901 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00001902
1903 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001904
Richard Smithb2f0f052016-10-10 18:54:32 +00001905 // Warn if the type is over-aligned and is being allocated by (unaligned)
1906 // global operator new.
1907 if (PlacementArgs.empty() && !PassAlignment &&
1908 (OperatorNew->isImplicit() ||
1909 (OperatorNew->getLocStart().isValid() &&
1910 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
1911 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00001912 Diag(StartLoc, diag::warn_overaligned_type)
1913 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00001914 << unsigned(Alignment / Context.getCharWidth())
1915 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00001916 }
1917 }
1918
Sebastian Redl6047f072012-02-16 12:22:20 +00001919 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001920 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1921 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00001922 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
1923 SourceRange InitRange(Inits[0]->getLocStart(),
1924 Inits[NumInits - 1]->getLocEnd());
1925 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1926 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001927 }
1928
Richard Smithdd2ca572012-11-26 08:32:48 +00001929 // If we can perform the initialization, and we've not already done so,
1930 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00001931 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001932 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00001933 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00001934 // The type we initialize is the complete type, including the array bound.
1935 QualType InitType;
1936 if (KnownArraySize)
1937 InitType = Context.getConstantArrayType(
1938 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
1939 *KnownArraySize),
1940 ArrayType::Normal, 0);
1941 else if (ArraySize)
1942 InitType =
1943 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
1944 else
1945 InitType = AllocType;
1946
Sebastian Redld74dd492012-02-12 18:41:05 +00001947 // C++11 [expr.new]p15:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001948 // A new-expression that creates an object of type T initializes that
1949 // object as follows:
1950 InitializationKind Kind
1951 // - If the new-initializer is omitted, the object is default-
1952 // initialized (8.5); if no initialization is performed,
1953 // the object has indeterminate value
Sebastian Redl6047f072012-02-16 12:22:20 +00001954 = initStyle == CXXNewExpr::NoInit
1955 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001956 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001957 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +00001958 : initStyle == CXXNewExpr::ListInit
1959 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1960 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1961 DirectInitRange.getBegin(),
1962 DirectInitRange.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001963
Douglas Gregor85dabae2009-12-16 01:38:02 +00001964 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001965 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00001966 InitializationSequence InitSeq(*this, Entity, Kind,
1967 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001968 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00001969 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00001970 if (FullInit.isInvalid())
1971 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001972
Sebastian Redl6047f072012-02-16 12:22:20 +00001973 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1974 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00001975 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00001976 if (CXXBindTemporaryExpr *Binder =
1977 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001978 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001979
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001980 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982
Douglas Gregor6642ca22010-02-26 05:06:18 +00001983 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00001984 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00001985 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1986 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001987 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00001988 }
1989 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00001990 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1991 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001992 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00001993 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00001994
John McCall928a2572011-07-13 20:12:57 +00001995 // C++0x [expr.new]p17:
1996 // If the new expression creates an array of objects of class type,
1997 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00001998 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1999 if (ArraySize && !BaseAllocType->isDependentType()) {
2000 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2001 if (CXXDestructorDecl *dtor = LookupDestructor(
2002 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2003 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002004 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002005 PDiag(diag::err_access_dtor)
2006 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002007 if (DiagnoseUseOfDecl(dtor, StartLoc))
2008 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002009 }
John McCall928a2572011-07-13 20:12:57 +00002010 }
2011 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002012
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002013 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00002014 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002015 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2016 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2017 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002018}
2019
Sebastian Redl6047f072012-02-16 12:22:20 +00002020/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002021/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002022bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002023 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002024 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2025 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002026 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002027 return Diag(Loc, diag::err_bad_new_type)
2028 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002029 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002030 return Diag(Loc, diag::err_bad_new_type)
2031 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002032 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002033 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002034 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002035 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002036 diag::err_allocation_of_abstract_type))
2037 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002038 else if (AllocType->isVariablyModifiedType())
2039 return Diag(Loc, diag::err_variably_modified_new_type)
2040 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00002041 else if (unsigned AddressSpace = AllocType.getAddressSpace())
2042 return Diag(Loc, diag::err_address_space_qualified_new)
2043 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002044 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002045 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2046 QualType BaseAllocType = Context.getBaseElementType(AT);
2047 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2048 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002049 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002050 << BaseAllocType;
2051 }
2052 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002053
Sebastian Redlbd150f42008-11-21 19:14:01 +00002054 return false;
2055}
2056
Richard Smithb2f0f052016-10-10 18:54:32 +00002057static bool
2058resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2059 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2060 FunctionDecl *&Operator,
2061 OverloadCandidateSet *AlignedCandidates = nullptr,
2062 Expr *AlignArg = nullptr) {
2063 OverloadCandidateSet Candidates(R.getNameLoc(),
2064 OverloadCandidateSet::CSK_Normal);
2065 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2066 Alloc != AllocEnd; ++Alloc) {
2067 // Even member operator new/delete are implicitly treated as
2068 // static, so don't use AddMemberCandidate.
2069 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2070
2071 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2072 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2073 /*ExplicitTemplateArgs=*/nullptr, Args,
2074 Candidates,
2075 /*SuppressUserConversions=*/false);
2076 continue;
2077 }
2078
2079 FunctionDecl *Fn = cast<FunctionDecl>(D);
2080 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2081 /*SuppressUserConversions=*/false);
2082 }
2083
2084 // Do the resolution.
2085 OverloadCandidateSet::iterator Best;
2086 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2087 case OR_Success: {
2088 // Got one!
2089 FunctionDecl *FnDecl = Best->Function;
2090 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2091 Best->FoundDecl) == Sema::AR_inaccessible)
2092 return true;
2093
2094 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002095 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002096 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002097
Richard Smithb2f0f052016-10-10 18:54:32 +00002098 case OR_No_Viable_Function:
2099 // C++17 [expr.new]p13:
2100 // If no matching function is found and the allocated object type has
2101 // new-extended alignment, the alignment argument is removed from the
2102 // argument list, and overload resolution is performed again.
2103 if (PassAlignment) {
2104 PassAlignment = false;
2105 AlignArg = Args[1];
2106 Args.erase(Args.begin() + 1);
2107 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2108 Operator, &Candidates, AlignArg);
2109 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002110
Richard Smithb2f0f052016-10-10 18:54:32 +00002111 // MSVC will fall back on trying to find a matching global operator new
2112 // if operator new[] cannot be found. Also, MSVC will leak by not
2113 // generating a call to operator delete or operator delete[], but we
2114 // will not replicate that bug.
2115 // FIXME: Find out how this interacts with the std::align_val_t fallback
2116 // once MSVC implements it.
2117 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2118 S.Context.getLangOpts().MSVCCompat) {
2119 R.clear();
2120 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2121 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2122 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2123 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2124 Operator, nullptr);
2125 }
Richard Smith1cdec012013-09-29 04:40:38 +00002126
Richard Smithb2f0f052016-10-10 18:54:32 +00002127 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2128 << R.getLookupName() << Range;
2129
2130 // If we have aligned candidates, only note the align_val_t candidates
2131 // from AlignedCandidates and the non-align_val_t candidates from
2132 // Candidates.
2133 if (AlignedCandidates) {
2134 auto IsAligned = [](OverloadCandidate &C) {
2135 return C.Function->getNumParams() > 1 &&
2136 C.Function->getParamDecl(1)->getType()->isAlignValT();
2137 };
2138 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2139
2140 // This was an overaligned allocation, so list the aligned candidates
2141 // first.
2142 Args.insert(Args.begin() + 1, AlignArg);
2143 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2144 R.getNameLoc(), IsAligned);
2145 Args.erase(Args.begin() + 1);
2146 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2147 IsUnaligned);
2148 } else {
2149 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2150 }
Richard Smith1cdec012013-09-29 04:40:38 +00002151 return true;
2152
Richard Smithb2f0f052016-10-10 18:54:32 +00002153 case OR_Ambiguous:
2154 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2155 << R.getLookupName() << Range;
2156 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2157 return true;
2158
2159 case OR_Deleted: {
2160 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2161 << Best->Function->isDeleted()
2162 << R.getLookupName()
2163 << S.getDeletedOrUnavailableSuffix(Best->Function)
2164 << Range;
2165 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2166 return true;
2167 }
2168 }
2169 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002170}
2171
Richard Smithb2f0f052016-10-10 18:54:32 +00002172
Sebastian Redlfaf68082008-12-03 20:26:15 +00002173/// FindAllocationFunctions - Finds the overloads of operator new and delete
2174/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002175bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2176 bool UseGlobal, QualType AllocType,
Richard Smithb2f0f052016-10-10 18:54:32 +00002177 bool IsArray, bool &PassAlignment,
2178 MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002179 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00002180 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002181 // --- Choosing an allocation function ---
2182 // C++ 5.3.4p8 - 14 & 18
2183 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2184 // in the scope of the allocated class.
2185 // 2) If an array size is given, look for operator new[], else look for
2186 // operator new.
2187 // 3) The first argument is always size_t. Append the arguments from the
2188 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002189
Richard Smithb2f0f052016-10-10 18:54:32 +00002190 SmallVector<Expr*, 8> AllocArgs;
2191 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2192
2193 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002194 // FIXME: Should the Sema create the expression and embed it in the syntax
2195 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002196 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002197 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002198 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002199 Context.getSizeType(),
2200 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002201 AllocArgs.push_back(&Size);
2202
2203 QualType AlignValT = Context.VoidTy;
2204 if (PassAlignment) {
2205 DeclareGlobalNewDelete();
2206 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2207 }
2208 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2209 if (PassAlignment)
2210 AllocArgs.push_back(&Align);
2211
2212 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002213
Douglas Gregor6642ca22010-02-26 05:06:18 +00002214 // C++ [expr.new]p8:
2215 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002216 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002217 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002218 // type, the allocation function's name is operator new[] and the
2219 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002220 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002221 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002222
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002223 QualType AllocElemType = Context.getBaseElementType(AllocType);
2224
Richard Smithb2f0f052016-10-10 18:54:32 +00002225 // Find the allocation function.
2226 {
2227 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2228
2229 // C++1z [expr.new]p9:
2230 // If the new-expression begins with a unary :: operator, the allocation
2231 // function's name is looked up in the global scope. Otherwise, if the
2232 // allocated type is a class type T or array thereof, the allocation
2233 // function's name is looked up in the scope of T.
2234 if (AllocElemType->isRecordType() && !UseGlobal)
2235 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2236
2237 // We can see ambiguity here if the allocation function is found in
2238 // multiple base classes.
2239 if (R.isAmbiguous())
2240 return true;
2241
2242 // If this lookup fails to find the name, or if the allocated type is not
2243 // a class type, the allocation function's name is looked up in the
2244 // global scope.
2245 if (R.empty())
2246 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2247
2248 assert(!R.empty() && "implicitly declared allocation functions not found");
2249 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2250
2251 // We do our own custom access checks below.
2252 R.suppressDiagnostics();
2253
2254 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2255 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002256 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002257 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002258
Richard Smithb2f0f052016-10-10 18:54:32 +00002259 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002260 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002261 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002262 return false;
2263 }
2264
Richard Smithb2f0f052016-10-10 18:54:32 +00002265 // Note, the name of OperatorNew might have been changed from array to
2266 // non-array by resolveAllocationOverload.
2267 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2268 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2269 ? OO_Array_Delete
2270 : OO_Delete);
2271
Douglas Gregor6642ca22010-02-26 05:06:18 +00002272 // C++ [expr.new]p19:
2273 //
2274 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002275 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002276 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002277 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002278 // the scope of T. If this lookup fails to find the name, or if
2279 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002280 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002281 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002282 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002283 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002284 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002285 LookupQualifiedName(FoundDelete, RD);
2286 }
John McCallfb6f5262010-03-18 08:19:33 +00002287 if (FoundDelete.isAmbiguous())
2288 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002289
Richard Smithb2f0f052016-10-10 18:54:32 +00002290 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002291 if (FoundDelete.empty()) {
2292 DeclareGlobalNewDelete();
2293 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2294 }
2295
2296 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002297
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002298 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002299
John McCalld3be2c82010-09-14 21:34:24 +00002300 // Whether we're looking for a placement operator delete is dictated
2301 // by whether we selected a placement operator new, not by whether
2302 // we had explicit placement arguments. This matters for things like
2303 // struct A { void *operator new(size_t, int = 0); ... };
2304 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002305 //
2306 // We don't have any definition for what a "placement allocation function"
2307 // is, but we assume it's any allocation function whose
2308 // parameter-declaration-clause is anything other than (size_t).
2309 //
2310 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2311 // This affects whether an exception from the constructor of an overaligned
2312 // type uses the sized or non-sized form of aligned operator delete.
2313 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2314 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002315
2316 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002317 // C++ [expr.new]p20:
2318 // A declaration of a placement deallocation function matches the
2319 // declaration of a placement allocation function if it has the
2320 // same number of parameters and, after parameter transformations
2321 // (8.3.5), all parameter types except the first are
2322 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002323 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002324 // To perform this comparison, we compute the function type that
2325 // the deallocation function should have, and use that type both
2326 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00002327 //
2328 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002329 QualType ExpectedFunctionType;
2330 {
2331 const FunctionProtoType *Proto
2332 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002333
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002334 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002335 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002336 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2337 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002338
John McCalldb40c7f2010-12-14 08:05:40 +00002339 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002340 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002341 EPI.Variadic = Proto->isVariadic();
Richard Smithb2f0f052016-10-10 18:54:32 +00002342 EPI.ExceptionSpec.Type = EST_BasicNoexcept;
John McCalldb40c7f2010-12-14 08:05:40 +00002343
Douglas Gregor6642ca22010-02-26 05:06:18 +00002344 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002345 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002346 }
2347
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002348 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002349 DEnd = FoundDelete.end();
2350 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002351 FunctionDecl *Fn = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002352 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6642ca22010-02-26 05:06:18 +00002353 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2354 // Perform template argument deduction to try to match the
2355 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002356 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002357 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2358 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002359 continue;
2360 } else
2361 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2362
2363 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002364 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002365 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002366
Richard Smithb2f0f052016-10-10 18:54:32 +00002367 if (getLangOpts().CUDA)
2368 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2369 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002370 // C++1y [expr.new]p22:
2371 // For a non-placement allocation function, the normal deallocation
2372 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002373 //
2374 // Per [expr.delete]p10, this lookup prefers a member operator delete
2375 // without a size_t argument, but prefers a non-member operator delete
2376 // with a size_t where possible (which it always is in this case).
2377 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2378 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2379 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2380 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2381 &BestDeallocFns);
2382 if (Selected)
2383 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2384 else {
2385 // If we failed to select an operator, all remaining functions are viable
2386 // but ambiguous.
2387 for (auto Fn : BestDeallocFns)
2388 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002389 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002390 }
2391
2392 // C++ [expr.new]p20:
2393 // [...] If the lookup finds a single matching deallocation
2394 // function, that function will be called; otherwise, no
2395 // deallocation function will be called.
2396 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002397 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002398
Richard Smithb2f0f052016-10-10 18:54:32 +00002399 // C++1z [expr.new]p23:
2400 // If the lookup finds a usual deallocation function (3.7.4.2)
2401 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002402 // as a placement deallocation function, would have been
2403 // selected as a match for the allocation function, the program
2404 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002405 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002406 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002407 UsualDeallocFnInfo Info(*this,
2408 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002409 // Core issue, per mail to core reflector, 2016-10-09:
2410 // If this is a member operator delete, and there is a corresponding
2411 // non-sized member operator delete, this isn't /really/ a sized
2412 // deallocation function, it just happens to have a size_t parameter.
2413 bool IsSizedDelete = Info.HasSizeT;
2414 if (IsSizedDelete && !FoundGlobalDelete) {
2415 auto NonSizedDelete =
2416 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2417 /*WantAlign*/Info.HasAlignValT);
2418 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2419 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2420 IsSizedDelete = false;
2421 }
2422
2423 if (IsSizedDelete) {
2424 SourceRange R = PlaceArgs.empty()
2425 ? SourceRange()
2426 : SourceRange(PlaceArgs.front()->getLocStart(),
2427 PlaceArgs.back()->getLocEnd());
2428 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2429 if (!OperatorDelete->isImplicit())
2430 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2431 << DeleteName;
2432 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002433 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002434
2435 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2436 Matches[0].first);
2437 } else if (!Matches.empty()) {
2438 // We found multiple suitable operators. Per [expr.new]p20, that means we
2439 // call no 'operator delete' function, but we should at least warn the user.
2440 // FIXME: Suppress this warning if the construction cannot throw.
2441 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2442 << DeleteName << AllocElemType;
2443
2444 for (auto &Match : Matches)
2445 Diag(Match.second->getLocation(),
2446 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002447 }
2448
Sebastian Redlfaf68082008-12-03 20:26:15 +00002449 return false;
2450}
2451
2452/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2453/// delete. These are:
2454/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002455/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002456/// void* operator new(std::size_t) throw(std::bad_alloc);
2457/// void* operator new[](std::size_t) throw(std::bad_alloc);
2458/// void operator delete(void *) throw();
2459/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002460/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002461/// void* operator new(std::size_t);
2462/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002463/// void operator delete(void *) noexcept;
2464/// void operator delete[](void *) noexcept;
2465/// // C++1y:
2466/// void* operator new(std::size_t);
2467/// void* operator new[](std::size_t);
2468/// void operator delete(void *) noexcept;
2469/// void operator delete[](void *) noexcept;
2470/// void operator delete(void *, std::size_t) noexcept;
2471/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002472/// @endcode
2473/// Note that the placement and nothrow forms of new are *not* implicitly
2474/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002475void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002476 if (GlobalNewDeleteDeclared)
2477 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002478
Douglas Gregor87f54062009-09-15 22:30:29 +00002479 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002480 // [...] The following allocation and deallocation functions (18.4) are
2481 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002482 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002483 //
Sebastian Redl37588092011-03-14 18:08:30 +00002484 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002485 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002486 // void* operator new[](std::size_t) throw(std::bad_alloc);
2487 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002488 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002489 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002490 // void* operator new(std::size_t);
2491 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002492 // void operator delete(void*) noexcept;
2493 // void operator delete[](void*) noexcept;
2494 // C++1y:
2495 // void* operator new(std::size_t);
2496 // void* operator new[](std::size_t);
2497 // void operator delete(void*) noexcept;
2498 // void operator delete[](void*) noexcept;
2499 // void operator delete(void*, std::size_t) noexcept;
2500 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002501 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002502 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002503 // new, operator new[], operator delete, operator delete[].
2504 //
2505 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2506 // "std" or "bad_alloc" as necessary to form the exception specification.
2507 // However, we do not make these implicit declarations visible to name
2508 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002509 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002510 // The "std::bad_alloc" class has not yet been declared, so build it
2511 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002512 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2513 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002514 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002515 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002516 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002517 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002518 }
Richard Smith59139022016-09-30 22:41:36 +00002519 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002520 // The "std::align_val_t" enum class has not yet been declared, so build it
2521 // implicitly.
2522 auto *AlignValT = EnumDecl::Create(
2523 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2524 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2525 AlignValT->setIntegerType(Context.getSizeType());
2526 AlignValT->setPromotionType(Context.getSizeType());
2527 AlignValT->setImplicit(true);
2528 StdAlignValT = AlignValT;
2529 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002530
Sebastian Redlfaf68082008-12-03 20:26:15 +00002531 GlobalNewDeleteDeclared = true;
2532
2533 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2534 QualType SizeT = Context.getSizeType();
2535
Richard Smith96269c52016-09-29 22:49:46 +00002536 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2537 QualType Return, QualType Param) {
2538 llvm::SmallVector<QualType, 3> Params;
2539 Params.push_back(Param);
2540
2541 // Create up to four variants of the function (sized/aligned).
2542 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2543 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002544 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002545
2546 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2547 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2548 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002549 if (Sized)
2550 Params.push_back(SizeT);
2551
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002552 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002553 if (Aligned)
2554 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2555
2556 DeclareGlobalAllocationFunction(
2557 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2558
2559 if (Aligned)
2560 Params.pop_back();
2561 }
2562 }
2563 };
2564
2565 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2566 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2567 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2568 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002569}
2570
2571/// DeclareGlobalAllocationFunction - Declares a single implicit global
2572/// allocation function if it doesn't already exist.
2573void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002574 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002575 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002576 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2577
2578 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002579 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2580 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2581 Alloc != AllocEnd; ++Alloc) {
2582 // Only look at non-template functions, as it is the predefined,
2583 // non-templated allocation function we are trying to declare here.
2584 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002585 if (Func->getNumParams() == Params.size()) {
2586 llvm::SmallVector<QualType, 3> FuncParams;
2587 for (auto *P : Func->parameters())
2588 FuncParams.push_back(
2589 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2590 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002591 // Make the function visible to name lookup, even if we found it in
2592 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002593 // allocation function, or is suppressing that function.
2594 Func->setHidden(false);
Chandler Carruth93538422010-02-03 11:02:14 +00002595 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002596 }
Chandler Carruth93538422010-02-03 11:02:14 +00002597 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002598 }
2599 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002600
Richard Smithc015bc22014-02-07 22:39:53 +00002601 FunctionProtoType::ExtProtoInfo EPI;
2602
Richard Smithf8b417c2014-02-08 00:42:45 +00002603 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002604 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002605 = (Name.getCXXOverloadedOperator() == OO_New ||
2606 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002607 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002608 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002609 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002610 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002611 EPI.ExceptionSpec.Type = EST_Dynamic;
2612 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002613 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002614 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002615 EPI.ExceptionSpec =
2616 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002617 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002618
Artem Belevich07db5cf2016-10-21 20:34:05 +00002619 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2620 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2621 FunctionDecl *Alloc = FunctionDecl::Create(
2622 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2623 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2624 Alloc->setImplicit();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002625
Artem Belevich07db5cf2016-10-21 20:34:05 +00002626 // Implicit sized deallocation functions always have default visibility.
2627 Alloc->addAttr(
2628 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002629
Artem Belevich07db5cf2016-10-21 20:34:05 +00002630 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2631 for (QualType T : Params) {
2632 ParamDecls.push_back(ParmVarDecl::Create(
2633 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2634 /*TInfo=*/nullptr, SC_None, nullptr));
2635 ParamDecls.back()->setImplicit();
2636 }
2637 Alloc->setParams(ParamDecls);
2638 if (ExtraAttr)
2639 Alloc->addAttr(ExtraAttr);
2640 Context.getTranslationUnitDecl()->addDecl(Alloc);
2641 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2642 };
2643
2644 if (!LangOpts.CUDA)
2645 CreateAllocationFunctionDecl(nullptr);
2646 else {
2647 // Host and device get their own declaration so each can be
2648 // defined or re-declared independently.
2649 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2650 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002651 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002652}
2653
Richard Smith1cdec012013-09-29 04:40:38 +00002654FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2655 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002656 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002657 DeclarationName Name) {
2658 DeclareGlobalNewDelete();
2659
2660 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2661 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2662
Richard Smithb2f0f052016-10-10 18:54:32 +00002663 // FIXME: It's possible for this to result in ambiguity, through a
2664 // user-declared variadic operator delete or the enable_if attribute. We
2665 // should probably not consider those cases to be usual deallocation
2666 // functions. But for now we just make an arbitrary choice in that case.
2667 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2668 Overaligned);
2669 assert(Result.FD && "operator delete missing from global scope?");
2670 return Result.FD;
2671}
Richard Smith1cdec012013-09-29 04:40:38 +00002672
Richard Smithb2f0f052016-10-10 18:54:32 +00002673FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2674 CXXRecordDecl *RD) {
2675 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002676
Richard Smithb2f0f052016-10-10 18:54:32 +00002677 FunctionDecl *OperatorDelete = nullptr;
2678 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2679 return nullptr;
2680 if (OperatorDelete)
2681 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002682
Richard Smithb2f0f052016-10-10 18:54:32 +00002683 // If there's no class-specific operator delete, look up the global
2684 // non-array delete.
2685 return FindUsualDeallocationFunction(
2686 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2687 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002688}
2689
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002690bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2691 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002692 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002693 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002694 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002695 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002696
John McCall27b18f82009-11-17 02:14:36 +00002697 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002698 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002699
Chandler Carruthb6f99172010-06-28 00:30:51 +00002700 Found.suppressDiagnostics();
2701
Richard Smithb2f0f052016-10-10 18:54:32 +00002702 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002703
Richard Smithb2f0f052016-10-10 18:54:32 +00002704 // C++17 [expr.delete]p10:
2705 // If the deallocation functions have class scope, the one without a
2706 // parameter of type std::size_t is selected.
2707 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2708 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2709 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002710
Richard Smithb2f0f052016-10-10 18:54:32 +00002711 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002712 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002713 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002714
Richard Smithb2f0f052016-10-10 18:54:32 +00002715 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002716 if (Operator->isDeleted()) {
2717 if (Diagnose) {
2718 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002719 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002720 }
2721 return true;
2722 }
2723
Richard Smith921bd202012-02-26 09:11:52 +00002724 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002725 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002726 return true;
2727
John McCall66a87592010-08-04 00:31:26 +00002728 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002729 }
John McCall66a87592010-08-04 00:31:26 +00002730
Richard Smithb2f0f052016-10-10 18:54:32 +00002731 // We found multiple suitable operators; complain about the ambiguity.
2732 // FIXME: The standard doesn't say to do this; it appears that the intent
2733 // is that this should never happen.
2734 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002735 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002736 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2737 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002738 for (auto &Match : Matches)
2739 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002740 }
John McCall66a87592010-08-04 00:31:26 +00002741 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002742 }
2743
2744 // We did find operator delete/operator delete[] declarations, but
2745 // none of them were suitable.
2746 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002747 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002748 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2749 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002750
Richard Smithb2f0f052016-10-10 18:54:32 +00002751 for (NamedDecl *D : Found)
2752 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002753 diag::note_member_declared_here) << Name;
2754 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002755 return true;
2756 }
2757
Craig Topperc3ec1492014-05-26 06:22:03 +00002758 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002759 return false;
2760}
2761
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002762namespace {
2763/// \brief Checks whether delete-expression, and new-expression used for
2764/// initializing deletee have the same array form.
2765class MismatchingNewDeleteDetector {
2766public:
2767 enum MismatchResult {
2768 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2769 NoMismatch,
2770 /// Indicates that variable is initialized with mismatching form of \a new.
2771 VarInitMismatches,
2772 /// Indicates that member is initialized with mismatching form of \a new.
2773 MemberInitMismatches,
2774 /// Indicates that 1 or more constructors' definitions could not been
2775 /// analyzed, and they will be checked again at the end of translation unit.
2776 AnalyzeLater
2777 };
2778
2779 /// \param EndOfTU True, if this is the final analysis at the end of
2780 /// translation unit. False, if this is the initial analysis at the point
2781 /// delete-expression was encountered.
2782 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002783 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002784 HasUndefinedConstructors(false) {}
2785
2786 /// \brief Checks whether pointee of a delete-expression is initialized with
2787 /// matching form of new-expression.
2788 ///
2789 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2790 /// point where delete-expression is encountered, then a warning will be
2791 /// issued immediately. If return value is \c AnalyzeLater at the point where
2792 /// delete-expression is seen, then member will be analyzed at the end of
2793 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2794 /// couldn't be analyzed. If at least one constructor initializes the member
2795 /// with matching type of new, the return value is \c NoMismatch.
2796 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2797 /// \brief Analyzes a class member.
2798 /// \param Field Class member to analyze.
2799 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2800 /// for deleting the \p Field.
2801 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002802 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002803 /// List of mismatching new-expressions used for initialization of the pointee
2804 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2805 /// Indicates whether delete-expression was in array form.
2806 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002807
2808private:
2809 const bool EndOfTU;
2810 /// \brief Indicates that there is at least one constructor without body.
2811 bool HasUndefinedConstructors;
2812 /// \brief Returns \c CXXNewExpr from given initialization expression.
2813 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002814 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002815 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2816 /// \brief Returns whether member is initialized with mismatching form of
2817 /// \c new either by the member initializer or in-class initialization.
2818 ///
2819 /// If bodies of all constructors are not visible at the end of translation
2820 /// unit or at least one constructor initializes member with the matching
2821 /// form of \c new, mismatch cannot be proven, and this function will return
2822 /// \c NoMismatch.
2823 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2824 /// \brief Returns whether variable is initialized with mismatching form of
2825 /// \c new.
2826 ///
2827 /// If variable is initialized with matching form of \c new or variable is not
2828 /// initialized with a \c new expression, this function will return true.
2829 /// If variable is initialized with mismatching form of \c new, returns false.
2830 /// \param D Variable to analyze.
2831 bool hasMatchingVarInit(const DeclRefExpr *D);
2832 /// \brief Checks whether the constructor initializes pointee with mismatching
2833 /// form of \c new.
2834 ///
2835 /// Returns true, if member is initialized with matching form of \c new in
2836 /// member initializer list. Returns false, if member is initialized with the
2837 /// matching form of \c new in this constructor's initializer or given
2838 /// constructor isn't defined at the point where delete-expression is seen, or
2839 /// member isn't initialized by the constructor.
2840 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2841 /// \brief Checks whether member is initialized with matching form of
2842 /// \c new in member initializer list.
2843 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2844 /// Checks whether member is initialized with mismatching form of \c new by
2845 /// in-class initializer.
2846 MismatchResult analyzeInClassInitializer();
2847};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002848}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002849
2850MismatchingNewDeleteDetector::MismatchResult
2851MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2852 NewExprs.clear();
2853 assert(DE && "Expected delete-expression");
2854 IsArrayForm = DE->isArrayForm();
2855 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2856 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2857 return analyzeMemberExpr(ME);
2858 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2859 if (!hasMatchingVarInit(D))
2860 return VarInitMismatches;
2861 }
2862 return NoMismatch;
2863}
2864
2865const CXXNewExpr *
2866MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2867 assert(E != nullptr && "Expected a valid initializer expression");
2868 E = E->IgnoreParenImpCasts();
2869 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2870 if (ILE->getNumInits() == 1)
2871 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2872 }
2873
2874 return dyn_cast_or_null<const CXXNewExpr>(E);
2875}
2876
2877bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2878 const CXXCtorInitializer *CI) {
2879 const CXXNewExpr *NE = nullptr;
2880 if (Field == CI->getMember() &&
2881 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2882 if (NE->isArray() == IsArrayForm)
2883 return true;
2884 else
2885 NewExprs.push_back(NE);
2886 }
2887 return false;
2888}
2889
2890bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2891 const CXXConstructorDecl *CD) {
2892 if (CD->isImplicit())
2893 return false;
2894 const FunctionDecl *Definition = CD;
2895 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2896 HasUndefinedConstructors = true;
2897 return EndOfTU;
2898 }
2899 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2900 if (hasMatchingNewInCtorInit(CI))
2901 return true;
2902 }
2903 return false;
2904}
2905
2906MismatchingNewDeleteDetector::MismatchResult
2907MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2908 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00002909 const Expr *InitExpr = Field->getInClassInitializer();
2910 if (!InitExpr)
2911 return EndOfTU ? NoMismatch : AnalyzeLater;
2912 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002913 if (NE->isArray() != IsArrayForm) {
2914 NewExprs.push_back(NE);
2915 return MemberInitMismatches;
2916 }
2917 }
2918 return NoMismatch;
2919}
2920
2921MismatchingNewDeleteDetector::MismatchResult
2922MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2923 bool DeleteWasArrayForm) {
2924 assert(Field != nullptr && "Analysis requires a valid class member.");
2925 this->Field = Field;
2926 IsArrayForm = DeleteWasArrayForm;
2927 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2928 for (const auto *CD : RD->ctors()) {
2929 if (hasMatchingNewInCtor(CD))
2930 return NoMismatch;
2931 }
2932 if (HasUndefinedConstructors)
2933 return EndOfTU ? NoMismatch : AnalyzeLater;
2934 if (!NewExprs.empty())
2935 return MemberInitMismatches;
2936 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
2937 : NoMismatch;
2938}
2939
2940MismatchingNewDeleteDetector::MismatchResult
2941MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
2942 assert(ME != nullptr && "Expected a member expression");
2943 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2944 return analyzeField(F, IsArrayForm);
2945 return NoMismatch;
2946}
2947
2948bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
2949 const CXXNewExpr *NE = nullptr;
2950 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
2951 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
2952 NE->isArray() != IsArrayForm) {
2953 NewExprs.push_back(NE);
2954 }
2955 }
2956 return NewExprs.empty();
2957}
2958
2959static void
2960DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
2961 const MismatchingNewDeleteDetector &Detector) {
2962 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
2963 FixItHint H;
2964 if (!Detector.IsArrayForm)
2965 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
2966 else {
2967 SourceLocation RSquare = Lexer::findLocationAfterToken(
2968 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
2969 SemaRef.getLangOpts(), true);
2970 if (RSquare.isValid())
2971 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
2972 }
2973 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
2974 << Detector.IsArrayForm << H;
2975
2976 for (const auto *NE : Detector.NewExprs)
2977 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
2978 << Detector.IsArrayForm;
2979}
2980
2981void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
2982 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
2983 return;
2984 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
2985 switch (Detector.analyzeDeleteExpr(DE)) {
2986 case MismatchingNewDeleteDetector::VarInitMismatches:
2987 case MismatchingNewDeleteDetector::MemberInitMismatches: {
2988 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
2989 break;
2990 }
2991 case MismatchingNewDeleteDetector::AnalyzeLater: {
2992 DeleteExprs[Detector.Field].push_back(
2993 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
2994 break;
2995 }
2996 case MismatchingNewDeleteDetector::NoMismatch:
2997 break;
2998 }
2999}
3000
3001void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3002 bool DeleteWasArrayForm) {
3003 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3004 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3005 case MismatchingNewDeleteDetector::VarInitMismatches:
3006 llvm_unreachable("This analysis should have been done for class members.");
3007 case MismatchingNewDeleteDetector::AnalyzeLater:
3008 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3009 "translation unit.");
3010 case MismatchingNewDeleteDetector::MemberInitMismatches:
3011 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3012 break;
3013 case MismatchingNewDeleteDetector::NoMismatch:
3014 break;
3015 }
3016}
3017
Sebastian Redlbd150f42008-11-21 19:14:01 +00003018/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3019/// @code ::delete ptr; @endcode
3020/// or
3021/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003022ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003023Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003024 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003025 // C++ [expr.delete]p1:
3026 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003027 // non-explicit conversion function to a pointer type. The result has type
3028 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003029 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003030 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3031
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003032 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003033 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003034 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003035 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003036
John Wiegley01296292011-04-08 18:41:53 +00003037 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003038 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003039 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003040 if (Ex.isInvalid())
3041 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003042
John Wiegley01296292011-04-08 18:41:53 +00003043 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003044
Richard Smithccc11812013-05-21 19:05:48 +00003045 class DeleteConverter : public ContextualImplicitConverter {
3046 public:
3047 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003048
Craig Toppere14c0f82014-03-12 04:55:44 +00003049 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003050 // FIXME: If we have an operator T* and an operator void*, we must pick
3051 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003052 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003053 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003054 return true;
3055 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003056 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003057
Richard Smithccc11812013-05-21 19:05:48 +00003058 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003059 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003060 return S.Diag(Loc, diag::err_delete_operand) << T;
3061 }
3062
3063 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003064 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003065 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3066 }
3067
3068 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003069 QualType T,
3070 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003071 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3072 }
3073
3074 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003075 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003076 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3077 << ConvTy;
3078 }
3079
3080 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003081 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003082 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3083 }
3084
3085 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003086 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003087 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3088 << ConvTy;
3089 }
3090
3091 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003092 QualType T,
3093 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003094 llvm_unreachable("conversion functions are permitted");
3095 }
3096 } Converter;
3097
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003098 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003099 if (Ex.isInvalid())
3100 return ExprError();
3101 Type = Ex.get()->getType();
3102 if (!Converter.match(Type))
3103 // FIXME: PerformContextualImplicitConversion should return ExprError
3104 // itself in this case.
3105 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003106
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003107 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003108 QualType PointeeElem = Context.getBaseElementType(Pointee);
3109
3110 if (unsigned AddressSpace = Pointee.getAddressSpace())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003111 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003112 diag::err_address_space_qualified_delete)
3113 << Pointee.getUnqualifiedType() << AddressSpace;
3114
Craig Topperc3ec1492014-05-26 06:22:03 +00003115 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003116 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003117 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003118 // effectively bans deletion of "void*". However, most compilers support
3119 // this, so we treat it as a warning unless we're in a SFINAE context.
3120 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003121 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003122 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003123 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003124 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003125 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003126 // FIXME: This can result in errors if the definition was imported from a
3127 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003128 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003129 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003130 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3131 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3132 }
3133 }
3134
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003135 if (Pointee->isArrayType() && !ArrayForm) {
3136 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003137 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003138 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003139 ArrayForm = true;
3140 }
3141
Anders Carlssona471db02009-08-16 20:29:29 +00003142 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3143 ArrayForm ? OO_Array_Delete : OO_Delete);
3144
Eli Friedmanae4280f2011-07-26 22:25:31 +00003145 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003146 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003147 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3148 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003149 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003150
John McCall284c48f2011-01-27 09:37:56 +00003151 // If we're allocating an array of records, check whether the
3152 // usual operator delete[] has a size_t parameter.
3153 if (ArrayForm) {
3154 // If the user specifically asked to use the global allocator,
3155 // we'll need to do the lookup into the class.
3156 if (UseGlobal)
3157 UsualArrayDeleteWantsSize =
3158 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3159
3160 // Otherwise, the usual operator delete[] should be the
3161 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003162 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003163 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003164 UsualDeallocFnInfo(*this,
3165 DeclAccessPair::make(OperatorDelete, AS_public))
3166 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003167 }
3168
Richard Smitheec915d62012-02-18 04:13:32 +00003169 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003170 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003171 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003172 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003173 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3174 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003175 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003176
Nico Weber5a9259c2016-01-15 21:45:31 +00003177 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3178 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3179 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3180 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003182
Richard Smithb2f0f052016-10-10 18:54:32 +00003183 if (!OperatorDelete) {
3184 bool IsComplete = isCompleteType(StartLoc, Pointee);
3185 bool CanProvideSize =
3186 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3187 Pointee.isDestructedType());
3188 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3189
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003190 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003191 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3192 Overaligned, DeleteName);
3193 }
Mike Stump11289f42009-09-09 15:08:12 +00003194
Eli Friedmanfa0df832012-02-02 03:46:19 +00003195 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003196
Douglas Gregorfa778132011-02-01 15:50:11 +00003197 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003198 if (PointeeRD) {
3199 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00003200 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00003201 PDiag(diag::err_access_dtor) << PointeeElem);
3202 }
3203 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003204 }
3205
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003206 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003207 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3208 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003209 AnalyzeDeleteExprMismatch(Result);
3210 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003211}
3212
Nico Weber5a9259c2016-01-15 21:45:31 +00003213void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3214 bool IsDelete, bool CallCanBeVirtual,
3215 bool WarnOnNonAbstractTypes,
3216 SourceLocation DtorLoc) {
3217 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
3218 return;
3219
3220 // C++ [expr.delete]p3:
3221 // In the first alternative (delete object), if the static type of the
3222 // object to be deleted is different from its dynamic type, the static
3223 // type shall be a base class of the dynamic type of the object to be
3224 // deleted and the static type shall have a virtual destructor or the
3225 // behavior is undefined.
3226 //
3227 const CXXRecordDecl *PointeeRD = dtor->getParent();
3228 // Note: a final class cannot be derived from, no issue there
3229 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3230 return;
3231
3232 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3233 if (PointeeRD->isAbstract()) {
3234 // If the class is abstract, we warn by default, because we're
3235 // sure the code has undefined behavior.
3236 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3237 << ClassType;
3238 } else if (WarnOnNonAbstractTypes) {
3239 // Otherwise, if this is not an array delete, it's a bit suspect,
3240 // but not necessarily wrong.
3241 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3242 << ClassType;
3243 }
3244 if (!IsDelete) {
3245 std::string TypeStr;
3246 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3247 Diag(DtorLoc, diag::note_delete_non_virtual)
3248 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3249 }
3250}
3251
Richard Smith03a4aa32016-06-23 19:02:52 +00003252Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3253 SourceLocation StmtLoc,
3254 ConditionKind CK) {
3255 ExprResult E =
3256 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3257 if (E.isInvalid())
3258 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003259 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3260 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003261}
3262
Douglas Gregor633caca2009-11-23 23:44:04 +00003263/// \brief Check the use of the given variable as a C++ condition in an if,
3264/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003265ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003266 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003267 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003268 if (ConditionVar->isInvalidDecl())
3269 return ExprError();
3270
Douglas Gregor633caca2009-11-23 23:44:04 +00003271 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003272
Douglas Gregor633caca2009-11-23 23:44:04 +00003273 // C++ [stmt.select]p2:
3274 // The declarator shall not specify a function or an array.
3275 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003276 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003277 diag::err_invalid_use_of_function_type)
3278 << ConditionVar->getSourceRange());
3279 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003280 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003281 diag::err_invalid_use_of_array_type)
3282 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003283
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003284 ExprResult Condition = DeclRefExpr::Create(
3285 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3286 /*enclosing*/ false, ConditionVar->getLocation(),
3287 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003288
Eli Friedmanfa0df832012-02-02 03:46:19 +00003289 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003290
Richard Smith03a4aa32016-06-23 19:02:52 +00003291 switch (CK) {
3292 case ConditionKind::Boolean:
3293 return CheckBooleanCondition(StmtLoc, Condition.get());
3294
Richard Smithb130fe72016-06-23 19:16:49 +00003295 case ConditionKind::ConstexprIf:
3296 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3297
Richard Smith03a4aa32016-06-23 19:02:52 +00003298 case ConditionKind::Switch:
3299 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003300 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003301
Richard Smith03a4aa32016-06-23 19:02:52 +00003302 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003303}
3304
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003305/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003306ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003307 // C++ 6.4p4:
3308 // The value of a condition that is an initialized declaration in a statement
3309 // other than a switch statement is the value of the declared variable
3310 // implicitly converted to type bool. If that conversion is ill-formed, the
3311 // program is ill-formed.
3312 // The value of a condition that is an expression is the value of the
3313 // expression, implicitly converted to bool.
3314 //
Richard Smithb130fe72016-06-23 19:16:49 +00003315 // FIXME: Return this value to the caller so they don't need to recompute it.
3316 llvm::APSInt Value(/*BitWidth*/1);
3317 return (IsConstexpr && !CondExpr->isValueDependent())
3318 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3319 CCEK_ConstexprIf)
3320 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003321}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003322
3323/// Helper function to determine whether this is the (deprecated) C++
3324/// conversion from a string literal to a pointer to non-const char or
3325/// non-const wchar_t (for narrow and wide string literals,
3326/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003327bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003328Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3329 // Look inside the implicit cast, if it exists.
3330 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3331 From = Cast->getSubExpr();
3332
3333 // A string literal (2.13.4) that is not a wide string literal can
3334 // be converted to an rvalue of type "pointer to char"; a wide
3335 // string literal can be converted to an rvalue of type "pointer
3336 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003337 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003338 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003339 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003340 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003341 // This conversion is considered only when there is an
3342 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003343 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3344 switch (StrLit->getKind()) {
3345 case StringLiteral::UTF8:
3346 case StringLiteral::UTF16:
3347 case StringLiteral::UTF32:
3348 // We don't allow UTF literals to be implicitly converted
3349 break;
3350 case StringLiteral::Ascii:
3351 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3352 ToPointeeType->getKind() == BuiltinType::Char_S);
3353 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003354 return Context.typesAreCompatible(Context.getWideCharType(),
3355 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003356 }
3357 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003358 }
3359
3360 return false;
3361}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003362
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003363static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003364 SourceLocation CastLoc,
3365 QualType Ty,
3366 CastKind Kind,
3367 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003368 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003369 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003370 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003371 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003372 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003373 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003374 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003375 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003376
Richard Smith72d74052013-07-20 19:41:36 +00003377 if (S.RequireNonAbstractType(CastLoc, Ty,
3378 diag::err_allocation_of_abstract_type))
3379 return ExprError();
3380
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003381 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003382 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003383
Richard Smith5179eb72016-06-28 19:03:57 +00003384 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3385 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003386 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003387 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003388
Richard Smithf8adcdc2014-07-17 05:12:35 +00003389 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003390 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003391 ConstructorArgs, HadMultipleCandidates,
3392 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3393 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003394 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003395 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003396
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003397 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003399
John McCalle3027922010-08-25 11:45:40 +00003400 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003401 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402
Richard Smithd3f2d322015-02-24 21:16:19 +00003403 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003404 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003405 return ExprError();
3406
Douglas Gregora4253922010-04-16 22:17:36 +00003407 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003408 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3409 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003410 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003411 if (Result.isInvalid())
3412 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003413 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003414 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3415 CK_UserDefinedConversion, Result.get(),
3416 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003417
Douglas Gregor668443e2011-01-20 00:18:04 +00003418 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003419 }
3420 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003421}
Douglas Gregora4253922010-04-16 22:17:36 +00003422
Douglas Gregor5fb53972009-01-14 15:45:31 +00003423/// PerformImplicitConversion - Perform an implicit conversion of the
3424/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003425/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003426/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003427/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003428ExprResult
3429Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003430 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003431 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003432 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003433 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003434 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003435 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3436 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003437 if (Res.isInvalid())
3438 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003439 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003440 break;
John Wiegley01296292011-04-08 18:41:53 +00003441 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003442
Anders Carlsson110b07b2009-09-15 06:28:28 +00003443 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003444
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003445 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003446 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003447 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003448 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003449 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003450 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003451
Anders Carlsson110b07b2009-09-15 06:28:28 +00003452 // If the user-defined conversion is specified by a conversion function,
3453 // the initial standard conversion sequence converts the source type to
3454 // the implicit object parameter of the conversion function.
3455 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003456 } else {
3457 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003458 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003459 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003460 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003461 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003462 // initial standard conversion sequence converts the source type to
3463 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003464 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3465 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003466 }
Richard Smith72d74052013-07-20 19:41:36 +00003467 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003468 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003469 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003470 PerformImplicitConversion(From, BeforeToType,
3471 ICS.UserDefined.Before, AA_Converting,
3472 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003473 if (Res.isInvalid())
3474 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003475 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003476 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003477
3478 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003479 = BuildCXXCastArgument(*this,
3480 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003481 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003482 CastKind, cast<CXXMethodDecl>(FD),
3483 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003484 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003485 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003486
3487 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003488 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003489
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003490 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003491
Richard Smith507840d2011-11-29 22:48:16 +00003492 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3493 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003494 }
John McCall0d1da222010-01-12 00:44:57 +00003495
3496 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003497 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003498 PDiag(diag::err_typecheck_ambiguous_condition)
3499 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003500 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501
Douglas Gregor39c16d42008-10-24 04:54:22 +00003502 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003503 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003504
3505 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003506 bool Diagnosed =
3507 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3508 From->getType(), From, Action);
3509 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003510 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003511 }
3512
3513 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003514 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003515}
3516
Richard Smith507840d2011-11-29 22:48:16 +00003517/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003518/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003519/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003520/// expression. Flavor is the context in which we're performing this
3521/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003522ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003523Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003524 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003525 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003526 CheckedConversionKind CCK) {
3527 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003528
Mike Stump87c57ac2009-05-16 07:39:55 +00003529 // Overall FIXME: we are recomputing too many types here and doing far too
3530 // much extra work. What this means is that we need to keep track of more
3531 // information that is computed when we try the implicit conversion initially,
3532 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003533 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003534
Douglas Gregor2fe98832008-11-03 19:09:14 +00003535 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003536 // FIXME: When can ToType be a reference type?
3537 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003538 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003539 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003540 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003541 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003542 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003543 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003544 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003545 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3546 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003547 ConstructorArgs, /*HadMultipleCandidates*/ false,
3548 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3549 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003550 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003551 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003552 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3553 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003554 From, /*HadMultipleCandidates*/ false,
3555 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3556 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003557 }
3558
Douglas Gregor980fb162010-04-29 18:24:40 +00003559 // Resolve overloaded function references.
3560 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3561 DeclAccessPair Found;
3562 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3563 true, Found);
3564 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003565 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003566
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003567 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003568 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003569
Douglas Gregor980fb162010-04-29 18:24:40 +00003570 From = FixOverloadedFunctionReference(From, Found, Fn);
3571 FromType = From->getType();
3572 }
3573
Richard Smitha23ab512013-05-23 00:30:41 +00003574 // If we're converting to an atomic type, first convert to the corresponding
3575 // non-atomic type.
3576 QualType ToAtomicType;
3577 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3578 ToAtomicType = ToType;
3579 ToType = ToAtomic->getValueType();
3580 }
3581
George Burgess IV8d141e02015-12-14 22:00:49 +00003582 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003583 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003584 switch (SCS.First) {
3585 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003586 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3587 FromType = FromAtomic->getValueType().getUnqualifiedType();
3588 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3589 From, /*BasePath=*/nullptr, VK_RValue);
3590 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003591 break;
3592
Eli Friedman946b7b52012-01-24 22:51:26 +00003593 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003594 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003595 ExprResult FromRes = DefaultLvalueConversion(From);
3596 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003597 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003598 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003599 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003600 }
John McCall34376a62010-12-04 03:47:34 +00003601
Douglas Gregor39c16d42008-10-24 04:54:22 +00003602 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003603 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003604 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003605 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003606 break;
3607
3608 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003609 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003610 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003611 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003612 break;
3613
3614 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003615 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003616 }
3617
Richard Smith507840d2011-11-29 22:48:16 +00003618 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003619 switch (SCS.Second) {
3620 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003621 // C++ [except.spec]p5:
3622 // [For] assignment to and initialization of pointers to functions,
3623 // pointers to member functions, and references to functions: the
3624 // target entity shall allow at least the exceptions allowed by the
3625 // source value in the assignment or initialization.
3626 switch (Action) {
3627 case AA_Assigning:
3628 case AA_Initializing:
3629 // Note, function argument passing and returning are initialization.
3630 case AA_Passing:
3631 case AA_Returning:
3632 case AA_Sending:
3633 case AA_Passing_CFAudited:
3634 if (CheckExceptionSpecCompatibility(From, ToType))
3635 return ExprError();
3636 break;
3637
3638 case AA_Casting:
3639 case AA_Converting:
3640 // Casts and implicit conversions are not initialization, so are not
3641 // checked for exception specification mismatches.
3642 break;
3643 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003644 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003645 break;
3646
3647 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003648 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003649 if (ToType->isBooleanType()) {
3650 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3651 SCS.Second == ICK_Integral_Promotion &&
3652 "only enums with fixed underlying type can promote to bool");
3653 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003654 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003655 } else {
3656 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003657 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003658 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003659 break;
3660
3661 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003662 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003663 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003664 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003665 break;
3666
3667 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003668 case ICK_Complex_Conversion: {
3669 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3670 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3671 CastKind CK;
3672 if (FromEl->isRealFloatingType()) {
3673 if (ToEl->isRealFloatingType())
3674 CK = CK_FloatingComplexCast;
3675 else
3676 CK = CK_FloatingComplexToIntegralComplex;
3677 } else if (ToEl->isRealFloatingType()) {
3678 CK = CK_IntegralComplexToFloatingComplex;
3679 } else {
3680 CK = CK_IntegralComplexCast;
3681 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003682 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003683 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003684 break;
John McCall8cb679e2010-11-15 09:13:47 +00003685 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003686
Douglas Gregor39c16d42008-10-24 04:54:22 +00003687 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003688 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00003689 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003690 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003691 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00003692 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003693 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003694 break;
3695
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003696 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003697 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003698 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003699 break;
3700
John McCall31168b02011-06-15 23:02:42 +00003701 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003702 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003703 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003704 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00003705 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003706 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003707 diag::ext_typecheck_convert_incompatible_pointer)
3708 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003709 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003710 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003711 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003712 diag::ext_typecheck_convert_incompatible_pointer)
3713 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003714 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00003715
Douglas Gregor33823722011-06-11 01:09:30 +00003716 if (From->getType()->isObjCObjectPointerType() &&
3717 ToType->isObjCObjectPointerType())
3718 EmitRelatedResultTypeNote(From);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003719 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00003720 else if (getLangOpts().ObjCAutoRefCount &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00003721 !CheckObjCARCUnavailableWeakConversion(ToType,
Fariborz Jahanianf2913402011-07-08 17:41:42 +00003722 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00003723 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003724 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003725 diag::err_arc_weak_unavailable_assign);
3726 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003727 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00003728 diag::err_arc_convesion_of_weak_unavailable)
3729 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00003730 << From->getSourceRange();
3731 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003732
John McCall8cb679e2010-11-15 09:13:47 +00003733 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003734 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003735 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003736 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00003737
3738 // Make sure we extend blocks if necessary.
3739 // FIXME: doing this here is really ugly.
3740 if (Kind == CK_BlockPointerToObjCPointerCast) {
3741 ExprResult E = From;
3742 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003743 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00003744 }
Fariborz Jahanian374089e2013-07-31 17:12:26 +00003745 if (getLangOpts().ObjCAutoRefCount)
3746 CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00003747 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003748 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003749 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003750 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003751
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003752 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00003753 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003754 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003755 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003756 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00003757 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003758 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00003759
3760 // We may not have been able to figure out what this member pointer resolved
3761 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00003762 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003763 (void)isCompleteType(From->getExprLoc(), From->getType());
3764 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00003765 }
David Majnemerd96b9972014-08-08 00:10:39 +00003766
Richard Smith507840d2011-11-29 22:48:16 +00003767 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003768 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003769 break;
3770 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003771
Abramo Bagnara7ccce982011-04-07 09:26:19 +00003772 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003773 // Perform half-to-boolean conversion via float.
3774 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003775 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003776 FromType = Context.FloatTy;
3777 }
3778
Richard Smith507840d2011-11-29 22:48:16 +00003779 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003780 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003781 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003782 break;
3783
Douglas Gregor88d292c2010-05-13 16:44:06 +00003784 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00003785 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003786 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003787 ToType.getNonReferenceType(),
3788 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003789 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003790 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00003791 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003792 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00003793
Richard Smith507840d2011-11-29 22:48:16 +00003794 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3795 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003796 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003797 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00003798 }
3799
Douglas Gregor46188682010-05-18 22:42:18 +00003800 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00003801 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003802 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003803 break;
3804
George Burgess IVdf1ed002016-01-13 01:52:39 +00003805 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00003806 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00003807 Expr *Elem = prepareVectorSplat(ToType, From).get();
3808 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3809 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003810 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00003811 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003812
Douglas Gregor46188682010-05-18 22:42:18 +00003813 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00003814 // Case 1. x -> _Complex y
3815 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3816 QualType ElType = ToComplex->getElementType();
3817 bool isFloatingComplex = ElType->isRealFloatingType();
3818
3819 // x -> y
3820 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3821 // do nothing
3822 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003823 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003824 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00003825 } else {
3826 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003827 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003828 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00003829 }
3830 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00003831 From = ImpCastExprToType(From, ToType,
3832 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003833 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00003834
3835 // Case 2. _Complex x -> y
3836 } else {
3837 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3838 assert(FromComplex);
3839
3840 QualType ElType = FromComplex->getElementType();
3841 bool isFloatingComplex = ElType->isRealFloatingType();
3842
3843 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00003844 From = ImpCastExprToType(From, ElType,
3845 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00003846 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003847 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003848
3849 // x -> y
3850 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3851 // do nothing
3852 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003853 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003854 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003855 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003856 } else {
3857 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003858 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003859 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003860 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003861 }
3862 }
Douglas Gregor46188682010-05-18 22:42:18 +00003863 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00003864
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00003865 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003866 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003867 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00003868 break;
3869 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00003870
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003871 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003872 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003873 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00003874 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3875 if (FromRes.isInvalid())
3876 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003877 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003878 assert ((ConvTy == Sema::Compatible) &&
3879 "Improper transparent union conversion");
3880 (void)ConvTy;
3881 break;
3882 }
3883
Guy Benyei259f9f42013-02-07 16:05:33 +00003884 case ICK_Zero_Event_Conversion:
3885 From = ImpCastExprToType(From, ToType,
3886 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003887 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00003888 break;
3889
Douglas Gregor46188682010-05-18 22:42:18 +00003890 case ICK_Lvalue_To_Rvalue:
3891 case ICK_Array_To_Pointer:
3892 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003893 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00003894 case ICK_Qualification:
3895 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00003896 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00003897 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003898 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003899 }
3900
3901 switch (SCS.Third) {
3902 case ICK_Identity:
3903 // Nothing to do.
3904 break;
3905
Richard Smitheb7ef2e2016-10-20 21:53:09 +00003906 case ICK_Function_Conversion:
3907 // If both sides are functions (or pointers/references to them), there could
3908 // be incompatible exception declarations.
3909 if (CheckExceptionSpecCompatibility(From, ToType))
3910 return ExprError();
3911
3912 From = ImpCastExprToType(From, ToType, CK_NoOp,
3913 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3914 break;
3915
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003916 case ICK_Qualification: {
3917 // The qualification keeps the category of the inner expression, unless the
3918 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00003919 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003920 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00003921 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003922 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00003923
Douglas Gregore981bb02011-03-14 16:13:32 +00003924 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003925 !getLangOpts().WritableStrings) {
3926 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3927 ? diag::ext_deprecated_string_literal_conversion
3928 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00003929 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003930 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00003931
Douglas Gregor39c16d42008-10-24 04:54:22 +00003932 break;
Richard Smitha23ab512013-05-23 00:30:41 +00003933 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003934
Douglas Gregor39c16d42008-10-24 04:54:22 +00003935 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003936 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003937 }
3938
Douglas Gregor298f43d2012-04-12 20:42:30 +00003939 // If this conversion sequence involved a scalar -> atomic conversion, perform
3940 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00003941 if (!ToAtomicType.isNull()) {
3942 assert(Context.hasSameType(
3943 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3944 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003945 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00003946 }
3947
George Burgess IV8d141e02015-12-14 22:00:49 +00003948 // If this conversion sequence succeeded and involved implicitly converting a
3949 // _Nullable type to a _Nonnull one, complain.
3950 if (CCK == CCK_ImplicitConversion)
3951 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
3952 From->getLocStart());
3953
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003954 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003955}
3956
Chandler Carruth8e172c62011-05-01 06:51:22 +00003957/// \brief Check the completeness of a type in a unary type trait.
3958///
3959/// If the particular type trait requires a complete type, tries to complete
3960/// it. If completing the type fails, a diagnostic is emitted and false
3961/// returned. If completing the type succeeds or no completion was required,
3962/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00003963static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00003964 SourceLocation Loc,
3965 QualType ArgTy) {
3966 // C++0x [meta.unary.prop]p3:
3967 // For all of the class templates X declared in this Clause, instantiating
3968 // that template with a template argument that is a class template
3969 // specialization may result in the implicit instantiation of the template
3970 // argument if and only if the semantics of X require that the argument
3971 // must be a complete type.
3972 // We apply this rule to all the type trait expressions used to implement
3973 // these class templates. We also try to follow any GCC documented behavior
3974 // in these expressions to ensure portability of standard libraries.
3975 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00003976 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00003977 // is_complete_type somewhat obviously cannot require a complete type.
3978 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003979 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003980
3981 // These traits are modeled on the type predicates in C++0x
3982 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3983 // requiring a complete type, as whether or not they return true cannot be
3984 // impacted by the completeness of the type.
3985 case UTT_IsVoid:
3986 case UTT_IsIntegral:
3987 case UTT_IsFloatingPoint:
3988 case UTT_IsArray:
3989 case UTT_IsPointer:
3990 case UTT_IsLvalueReference:
3991 case UTT_IsRvalueReference:
3992 case UTT_IsMemberFunctionPointer:
3993 case UTT_IsMemberObjectPointer:
3994 case UTT_IsEnum:
3995 case UTT_IsUnion:
3996 case UTT_IsClass:
3997 case UTT_IsFunction:
3998 case UTT_IsReference:
3999 case UTT_IsArithmetic:
4000 case UTT_IsFundamental:
4001 case UTT_IsObject:
4002 case UTT_IsScalar:
4003 case UTT_IsCompound:
4004 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004005 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004006
4007 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4008 // which requires some of its traits to have the complete type. However,
4009 // the completeness of the type cannot impact these traits' semantics, and
4010 // so they don't require it. This matches the comments on these traits in
4011 // Table 49.
4012 case UTT_IsConst:
4013 case UTT_IsVolatile:
4014 case UTT_IsSigned:
4015 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004016
4017 // This type trait always returns false, checking the type is moot.
4018 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004019 return true;
4020
David Majnemer213bea32015-11-16 06:58:51 +00004021 // C++14 [meta.unary.prop]:
4022 // If T is a non-union class type, T shall be a complete type.
4023 case UTT_IsEmpty:
4024 case UTT_IsPolymorphic:
4025 case UTT_IsAbstract:
4026 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4027 if (!RD->isUnion())
4028 return !S.RequireCompleteType(
4029 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4030 return true;
4031
4032 // C++14 [meta.unary.prop]:
4033 // If T is a class type, T shall be a complete type.
4034 case UTT_IsFinal:
4035 case UTT_IsSealed:
4036 if (ArgTy->getAsCXXRecordDecl())
4037 return !S.RequireCompleteType(
4038 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4039 return true;
4040
4041 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
4042 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004043 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004044 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004045 case UTT_IsStandardLayout:
4046 case UTT_IsPOD:
4047 case UTT_IsLiteral:
David Majnemer213bea32015-11-16 06:58:51 +00004048
Alp Toker73287bf2014-01-20 00:24:09 +00004049 case UTT_IsDestructible:
4050 case UTT_IsNothrowDestructible:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004051 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004052
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004053 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00004054 // [meta.unary.prop] despite not being named the same. They are specified
4055 // by both GCC and the Embarcadero C++ compiler, and require the complete
4056 // type due to the overarching C++0x type predicates being implemented
4057 // requiring the complete type.
4058 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004059 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004060 case UTT_HasNothrowConstructor:
4061 case UTT_HasNothrowCopy:
4062 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004063 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004064 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004065 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004066 case UTT_HasTrivialCopy:
4067 case UTT_HasTrivialDestructor:
4068 case UTT_HasVirtualDestructor:
4069 // Arrays of unknown bound are expressly allowed.
4070 QualType ElTy = ArgTy;
4071 if (ArgTy->isIncompleteArrayType())
4072 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
4073
4074 // The void type is expressly allowed.
4075 if (ElTy->isVoidType())
4076 return true;
4077
4078 return !S.RequireCompleteType(
4079 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004080 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004081}
4082
Joao Matosc9523d42013-03-27 01:34:16 +00004083static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4084 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004085 bool (CXXRecordDecl::*HasTrivial)() const,
4086 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004087 bool (CXXMethodDecl::*IsDesiredOp)() const)
4088{
4089 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4090 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4091 return true;
4092
4093 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4094 DeclarationNameInfo NameInfo(Name, KeyLoc);
4095 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4096 if (Self.LookupQualifiedName(Res, RD)) {
4097 bool FoundOperator = false;
4098 Res.suppressDiagnostics();
4099 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4100 Op != OpEnd; ++Op) {
4101 if (isa<FunctionTemplateDecl>(*Op))
4102 continue;
4103
4104 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4105 if((Operator->*IsDesiredOp)()) {
4106 FoundOperator = true;
4107 const FunctionProtoType *CPT =
4108 Operator->getType()->getAs<FunctionProtoType>();
4109 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Alp Toker73287bf2014-01-20 00:24:09 +00004110 if (!CPT || !CPT->isNothrow(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004111 return false;
4112 }
4113 }
4114 return FoundOperator;
4115 }
4116 return false;
4117}
4118
Alp Toker95e7ff22014-01-01 05:57:51 +00004119static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004120 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004121 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004122
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004123 ASTContext &C = Self.Context;
4124 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004125 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004126 // Type trait expressions corresponding to the primary type category
4127 // predicates in C++0x [meta.unary.cat].
4128 case UTT_IsVoid:
4129 return T->isVoidType();
4130 case UTT_IsIntegral:
4131 return T->isIntegralType(C);
4132 case UTT_IsFloatingPoint:
4133 return T->isFloatingType();
4134 case UTT_IsArray:
4135 return T->isArrayType();
4136 case UTT_IsPointer:
4137 return T->isPointerType();
4138 case UTT_IsLvalueReference:
4139 return T->isLValueReferenceType();
4140 case UTT_IsRvalueReference:
4141 return T->isRValueReferenceType();
4142 case UTT_IsMemberFunctionPointer:
4143 return T->isMemberFunctionPointerType();
4144 case UTT_IsMemberObjectPointer:
4145 return T->isMemberDataPointerType();
4146 case UTT_IsEnum:
4147 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004148 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004149 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004150 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004151 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004152 case UTT_IsFunction:
4153 return T->isFunctionType();
4154
4155 // Type trait expressions which correspond to the convenient composition
4156 // predicates in C++0x [meta.unary.comp].
4157 case UTT_IsReference:
4158 return T->isReferenceType();
4159 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004160 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004161 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004162 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004163 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004164 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004165 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004166 // Note: semantic analysis depends on Objective-C lifetime types to be
4167 // considered scalar types. However, such types do not actually behave
4168 // like scalar types at run time (since they may require retain/release
4169 // operations), so we report them as non-scalar.
4170 if (T->isObjCLifetimeType()) {
4171 switch (T.getObjCLifetime()) {
4172 case Qualifiers::OCL_None:
4173 case Qualifiers::OCL_ExplicitNone:
4174 return true;
4175
4176 case Qualifiers::OCL_Strong:
4177 case Qualifiers::OCL_Weak:
4178 case Qualifiers::OCL_Autoreleasing:
4179 return false;
4180 }
4181 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004182
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004183 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004184 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004185 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004186 case UTT_IsMemberPointer:
4187 return T->isMemberPointerType();
4188
4189 // Type trait expressions which correspond to the type property predicates
4190 // in C++0x [meta.unary.prop].
4191 case UTT_IsConst:
4192 return T.isConstQualified();
4193 case UTT_IsVolatile:
4194 return T.isVolatileQualified();
4195 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004196 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004197 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004198 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004199 case UTT_IsStandardLayout:
4200 return T->isStandardLayoutType();
4201 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004202 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004203 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004204 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004205 case UTT_IsEmpty:
4206 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4207 return !RD->isUnion() && RD->isEmpty();
4208 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004209 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004210 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004211 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004212 return false;
4213 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004214 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004215 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004216 return false;
David Majnemer213bea32015-11-16 06:58:51 +00004217 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4218 // even then only when it is used with the 'interface struct ...' syntax
4219 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004220 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004221 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004222 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004223 case UTT_IsSealed:
4224 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004225 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004226 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004227 case UTT_IsSigned:
4228 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004229 case UTT_IsUnsigned:
4230 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004231
4232 // Type trait expressions which query classes regarding their construction,
4233 // destruction, and copying. Rather than being based directly on the
4234 // related type predicates in the standard, they are specified by both
4235 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4236 // specifications.
4237 //
4238 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4239 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004240 //
4241 // Note that these builtins do not behave as documented in g++: if a class
4242 // has both a trivial and a non-trivial special member of a particular kind,
4243 // they return false! For now, we emulate this behavior.
4244 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4245 // does not correctly compute triviality in the presence of multiple special
4246 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004247 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004248 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4249 // If __is_pod (type) is true then the trait is true, else if type is
4250 // a cv class or union type (or array thereof) with a trivial default
4251 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004252 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004253 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004254 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4255 return RD->hasTrivialDefaultConstructor() &&
4256 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004257 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004258 case UTT_HasTrivialMoveConstructor:
4259 // This trait is implemented by MSVC 2012 and needed to parse the
4260 // standard library headers. Specifically this is used as the logic
4261 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004262 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004263 return true;
4264 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4265 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4266 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004267 case UTT_HasTrivialCopy:
4268 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4269 // If __is_pod (type) is true or type is a reference type then
4270 // the trait is true, else if type is a cv class or union type
4271 // with a trivial copy constructor ([class.copy]) then the trait
4272 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004273 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004274 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004275 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4276 return RD->hasTrivialCopyConstructor() &&
4277 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004278 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00004279 case UTT_HasTrivialMoveAssign:
4280 // This trait is implemented by MSVC 2012 and needed to parse the
4281 // standard library headers. Specifically it is used as the logic
4282 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004283 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004284 return true;
4285 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4286 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4287 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004288 case UTT_HasTrivialAssign:
4289 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4290 // If type is const qualified or is a reference type then the
4291 // trait is false. Otherwise if __is_pod (type) is true then the
4292 // trait is true, else if type is a cv class or union type with
4293 // a trivial copy assignment ([class.copy]) then the trait is
4294 // true, else it is false.
4295 // Note: the const and reference restrictions are interesting,
4296 // given that const and reference members don't prevent a class
4297 // from having a trivial copy assignment operator (but do cause
4298 // errors if the copy assignment operator is actually used, q.v.
4299 // [class.copy]p12).
4300
Richard Smith92f241f2012-12-08 02:53:02 +00004301 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004302 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004303 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004304 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004305 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4306 return RD->hasTrivialCopyAssignment() &&
4307 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004308 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004309 case UTT_IsDestructible:
4310 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004311 // C++14 [meta.unary.prop]:
4312 // For reference types, is_destructible<T>::value is true.
4313 if (T->isReferenceType())
4314 return true;
4315
4316 // Objective-C++ ARC: autorelease types don't require destruction.
4317 if (T->isObjCLifetimeType() &&
4318 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4319 return true;
4320
4321 // C++14 [meta.unary.prop]:
4322 // For incomplete types and function types, is_destructible<T>::value is
4323 // false.
4324 if (T->isIncompleteType() || T->isFunctionType())
4325 return false;
4326
4327 // C++14 [meta.unary.prop]:
4328 // For object types and given U equal to remove_all_extents_t<T>, if the
4329 // expression std::declval<U&>().~U() is well-formed when treated as an
4330 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4331 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4332 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4333 if (!Destructor)
4334 return false;
4335 // C++14 [dcl.fct.def.delete]p2:
4336 // A program that refers to a deleted function implicitly or
4337 // explicitly, other than to declare it, is ill-formed.
4338 if (Destructor->isDeleted())
4339 return false;
4340 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4341 return false;
4342 if (UTT == UTT_IsNothrowDestructible) {
4343 const FunctionProtoType *CPT =
4344 Destructor->getType()->getAs<FunctionProtoType>();
4345 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4346 if (!CPT || !CPT->isNothrow(C))
4347 return false;
4348 }
4349 }
4350 return true;
4351
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004352 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004353 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004354 // If __is_pod (type) is true or type is a reference type
4355 // then the trait is true, else if type is a cv class or union
4356 // type (or array thereof) with a trivial destructor
4357 // ([class.dtor]) then the trait is true, else it is
4358 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004359 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004360 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004361
John McCall31168b02011-06-15 23:02:42 +00004362 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004363 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004364 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4365 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004366
Richard Smith92f241f2012-12-08 02:53:02 +00004367 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4368 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004369 return false;
4370 // TODO: Propagate nothrowness for implicitly declared special members.
4371 case UTT_HasNothrowAssign:
4372 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4373 // If type is const qualified or is a reference type then the
4374 // trait is false. Otherwise if __has_trivial_assign (type)
4375 // is true then the trait is true, else if type is a cv class
4376 // or union type with copy assignment operators that are known
4377 // not to throw an exception then the trait is true, else it is
4378 // false.
4379 if (C.getBaseElementType(T).isConstQualified())
4380 return false;
4381 if (T->isReferenceType())
4382 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004383 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004384 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004385
Joao Matosc9523d42013-03-27 01:34:16 +00004386 if (const RecordType *RT = T->getAs<RecordType>())
4387 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4388 &CXXRecordDecl::hasTrivialCopyAssignment,
4389 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4390 &CXXMethodDecl::isCopyAssignmentOperator);
4391 return false;
4392 case UTT_HasNothrowMoveAssign:
4393 // This trait is implemented by MSVC 2012 and needed to parse the
4394 // standard library headers. Specifically this is used as the logic
4395 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004396 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004397 return true;
4398
4399 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4400 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4401 &CXXRecordDecl::hasTrivialMoveAssignment,
4402 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4403 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004404 return false;
4405 case UTT_HasNothrowCopy:
4406 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4407 // If __has_trivial_copy (type) is true then the trait is true, else
4408 // if type is a cv class or union type with copy constructors that are
4409 // known not to throw an exception then the trait is true, else it is
4410 // false.
John McCall31168b02011-06-15 23:02:42 +00004411 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004412 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004413 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4414 if (RD->hasTrivialCopyConstructor() &&
4415 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004416 return true;
4417
4418 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004419 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004420 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004421 // A template constructor is never a copy constructor.
4422 // FIXME: However, it may actually be selected at the actual overload
4423 // resolution point.
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004424 if (isa<FunctionTemplateDecl>(ND))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004425 continue;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004426 const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004427 if (Constructor->isCopyConstructor(FoundTQs)) {
4428 FoundConstructor = true;
4429 const FunctionProtoType *CPT
4430 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004431 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4432 if (!CPT)
4433 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004434 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004435 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004436 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004437 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004438 }
4439 }
4440
Richard Smith938f40b2011-06-11 17:19:42 +00004441 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004442 }
4443 return false;
4444 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004445 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004446 // If __has_trivial_constructor (type) is true then the trait is
4447 // true, else if type is a cv class or union type (or array
4448 // thereof) with a default constructor that is known not to
4449 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004450 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004451 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004452 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4453 if (RD->hasTrivialDefaultConstructor() &&
4454 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004455 return true;
4456
Alp Tokerb4bca412014-01-20 00:23:47 +00004457 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004458 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004459 // FIXME: In C++0x, a constructor template can be a default constructor.
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004460 if (isa<FunctionTemplateDecl>(ND))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004461 continue;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004462 const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND);
Sebastian Redlc15c3262010-09-13 22:02:47 +00004463 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004464 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004465 const FunctionProtoType *CPT
4466 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004467 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4468 if (!CPT)
4469 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004470 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004471 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004472 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004473 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004474 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004475 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004476 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004477 }
4478 return false;
4479 case UTT_HasVirtualDestructor:
4480 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4481 // If type is a class type with a virtual destructor ([class.dtor])
4482 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004483 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004484 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004485 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004486 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004487
4488 // These type trait expressions are modeled on the specifications for the
4489 // Embarcadero C++0x type trait functions:
4490 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4491 case UTT_IsCompleteType:
4492 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4493 // Returns True if and only if T is a complete type at the point of the
4494 // function call.
4495 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004496 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004497}
Sebastian Redl5822f082009-02-07 20:10:22 +00004498
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004499/// \brief Determine whether T has a non-trivial Objective-C lifetime in
4500/// ARC mode.
4501static bool hasNontrivialObjCLifetime(QualType T) {
4502 switch (T.getObjCLifetime()) {
4503 case Qualifiers::OCL_ExplicitNone:
4504 return false;
4505
4506 case Qualifiers::OCL_Strong:
4507 case Qualifiers::OCL_Weak:
4508 case Qualifiers::OCL_Autoreleasing:
4509 return true;
4510
4511 case Qualifiers::OCL_None:
4512 return T->isObjCLifetimeType();
4513 }
4514
4515 llvm_unreachable("Unknown ObjC lifetime qualifier");
4516}
4517
Alp Tokercbb90342013-12-13 20:49:58 +00004518static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4519 QualType RhsT, SourceLocation KeyLoc);
4520
Douglas Gregor29c42f22012-02-24 07:38:34 +00004521static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4522 ArrayRef<TypeSourceInfo *> Args,
4523 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004524 if (Kind <= UTT_Last)
4525 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4526
Alp Tokercbb90342013-12-13 20:49:58 +00004527 if (Kind <= BTT_Last)
4528 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4529 Args[1]->getType(), RParenLoc);
4530
Douglas Gregor29c42f22012-02-24 07:38:34 +00004531 switch (Kind) {
Alp Toker73287bf2014-01-20 00:24:09 +00004532 case clang::TT_IsConstructible:
4533 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004534 case clang::TT_IsTriviallyConstructible: {
4535 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004536 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004537 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004538 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004539 // definition for is_constructible, as defined below, is known to call
4540 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004541 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004542 // The predicate condition for a template specialization
4543 // is_constructible<T, Args...> shall be satisfied if and only if the
4544 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004545 // variable t:
4546 //
4547 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004548 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004549
4550 // Precondition: T and all types in the parameter pack Args shall be
4551 // complete types, (possibly cv-qualified) void, or arrays of
4552 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004553 for (const auto *TSI : Args) {
4554 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004555 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004556 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004557
Simon Pilgrim75c26882016-09-30 14:25:09 +00004558 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004559 diag::err_incomplete_type_used_in_type_trait_expr))
4560 return false;
4561 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004562
David Majnemer9658ecc2015-11-13 05:32:43 +00004563 // Make sure the first argument is not incomplete nor a function type.
4564 QualType T = Args[0]->getType();
4565 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004566 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004567
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004568 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004569 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004570 if (RD && RD->isAbstract())
4571 return false;
4572
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004573 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4574 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004575 ArgExprs.reserve(Args.size() - 1);
4576 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004577 QualType ArgTy = Args[I]->getType();
4578 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4579 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004580 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004581 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4582 ArgTy.getNonLValueExprType(S.Context),
4583 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004584 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004585 for (Expr &E : OpaqueArgExprs)
4586 ArgExprs.push_back(&E);
4587
Simon Pilgrim75c26882016-09-30 14:25:09 +00004588 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004589 // trap at translation unit scope.
4590 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
4591 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4592 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4593 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4594 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4595 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004596 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004597 if (Init.Failed())
4598 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004599
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004600 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004601 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4602 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004603
Alp Toker73287bf2014-01-20 00:24:09 +00004604 if (Kind == clang::TT_IsConstructible)
4605 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004606
Alp Toker73287bf2014-01-20 00:24:09 +00004607 if (Kind == clang::TT_IsNothrowConstructible)
4608 return S.canThrow(Result.get()) == CT_Cannot;
4609
4610 if (Kind == clang::TT_IsTriviallyConstructible) {
4611 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4612 // lifetime, this is a non-trivial construction.
4613 if (S.getLangOpts().ObjCAutoRefCount &&
David Majnemer9658ecc2015-11-13 05:32:43 +00004614 hasNontrivialObjCLifetime(T.getNonReferenceType()))
Alp Toker73287bf2014-01-20 00:24:09 +00004615 return false;
4616
4617 // The initialization succeeded; now make sure there are no non-trivial
4618 // calls.
4619 return !Result.get()->hasNonTrivialCall(S.Context);
4620 }
4621
4622 llvm_unreachable("unhandled type trait");
4623 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004624 }
Alp Tokercbb90342013-12-13 20:49:58 +00004625 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004626 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004627
Douglas Gregor29c42f22012-02-24 07:38:34 +00004628 return false;
4629}
4630
Simon Pilgrim75c26882016-09-30 14:25:09 +00004631ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4632 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004633 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004634 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004635
Alp Toker95e7ff22014-01-01 05:57:51 +00004636 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4637 *this, Kind, KWLoc, Args[0]->getType()))
4638 return ExprError();
4639
Douglas Gregor29c42f22012-02-24 07:38:34 +00004640 bool Dependent = false;
4641 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4642 if (Args[I]->getType()->isDependentType()) {
4643 Dependent = true;
4644 break;
4645 }
4646 }
Alp Tokercbb90342013-12-13 20:49:58 +00004647
4648 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004649 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004650 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4651
4652 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4653 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004654}
4655
Alp Toker88f64e62013-12-13 21:19:30 +00004656ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4657 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004658 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004659 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004660 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00004661
Douglas Gregor29c42f22012-02-24 07:38:34 +00004662 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4663 TypeSourceInfo *TInfo;
4664 QualType T = GetTypeFromParser(Args[I], &TInfo);
4665 if (!TInfo)
4666 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00004667
4668 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004669 }
Alp Tokercbb90342013-12-13 20:49:58 +00004670
Douglas Gregor29c42f22012-02-24 07:38:34 +00004671 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4672}
4673
Alp Tokercbb90342013-12-13 20:49:58 +00004674static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4675 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004676 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4677 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004678
4679 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004680 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004681 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004682 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004683 // Base and Derived are not unions and name the same class type without
4684 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004685
John McCall388ef532011-01-28 22:02:36 +00004686 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4687 if (!lhsRecord) return false;
4688
4689 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4690 if (!rhsRecord) return false;
4691
4692 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4693 == (lhsRecord == rhsRecord));
4694
4695 if (lhsRecord == rhsRecord)
4696 return !lhsRecord->getDecl()->isUnion();
4697
4698 // C++0x [meta.rel]p2:
4699 // If Base and Derived are class types and are different types
4700 // (ignoring possible cv-qualifiers) then Derived shall be a
4701 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004702 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00004703 diag::err_incomplete_type_used_in_type_trait_expr))
4704 return false;
4705
4706 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4707 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4708 }
John Wiegley65497cc2011-04-27 23:09:49 +00004709 case BTT_IsSame:
4710 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00004711 case BTT_TypeCompatible:
4712 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4713 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00004714 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00004715 case BTT_IsConvertibleTo: {
4716 // C++0x [meta.rel]p4:
4717 // Given the following function prototype:
4718 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004719 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00004720 // typename add_rvalue_reference<T>::type create();
4721 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004722 // the predicate condition for a template specialization
4723 // is_convertible<From, To> shall be satisfied if and only if
4724 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00004725 // well-formed, including any implicit conversions to the return
4726 // type of the function:
4727 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004728 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00004729 // return create<From>();
4730 // }
4731 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004732 // Access checking is performed as if in a context unrelated to To and
4733 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00004734 // of the return-statement (including conversions to the return type)
4735 // is considered.
4736 //
4737 // We model the initialization as a copy-initialization of a temporary
4738 // of the appropriate type, which for this expression is identical to the
4739 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004740
4741 // Functions aren't allowed to return function or array types.
4742 if (RhsT->isFunctionType() || RhsT->isArrayType())
4743 return false;
4744
4745 // A return statement in a void function must have void type.
4746 if (RhsT->isVoidType())
4747 return LhsT->isVoidType();
4748
4749 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00004750 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004751 return false;
4752
4753 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00004754 if (LhsT->isObjectType() || LhsT->isFunctionType())
4755 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004756
4757 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00004758 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00004759 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00004760 Expr::getValueKindForType(LhsT));
4761 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004762 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00004763 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004764
4765 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00004766 // trap at translation unit scope.
4767 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00004768 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4769 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004770 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004771 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00004772 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00004773
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004774 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00004775 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4776 }
Alp Toker73287bf2014-01-20 00:24:09 +00004777
David Majnemerb3d96882016-05-23 17:21:55 +00004778 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00004779 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00004780 case BTT_IsTriviallyAssignable: {
4781 // C++11 [meta.unary.prop]p3:
4782 // is_trivially_assignable is defined as:
4783 // is_assignable<T, U>::value is true and the assignment, as defined by
4784 // is_assignable, is known to call no operation that is not trivial
4785 //
4786 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004787 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00004788 // treated as an unevaluated operand (Clause 5).
4789 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004790 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00004791 // void, or arrays of unknown bound.
4792 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004793 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004794 diag::err_incomplete_type_used_in_type_trait_expr))
4795 return false;
4796 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00004797 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00004798 diag::err_incomplete_type_used_in_type_trait_expr))
4799 return false;
4800
4801 // cv void is never assignable.
4802 if (LhsT->isVoidType() || RhsT->isVoidType())
4803 return false;
4804
Simon Pilgrim75c26882016-09-30 14:25:09 +00004805 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00004806 // declval<U>().
4807 if (LhsT->isObjectType() || LhsT->isFunctionType())
4808 LhsT = Self.Context.getRValueReferenceType(LhsT);
4809 if (RhsT->isObjectType() || RhsT->isFunctionType())
4810 RhsT = Self.Context.getRValueReferenceType(RhsT);
4811 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4812 Expr::getValueKindForType(LhsT));
4813 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4814 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00004815
4816 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00004817 // trap at translation unit scope.
4818 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
4819 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4820 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004821 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4822 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004823 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4824 return false;
4825
David Majnemerb3d96882016-05-23 17:21:55 +00004826 if (BTT == BTT_IsAssignable)
4827 return true;
4828
Alp Toker73287bf2014-01-20 00:24:09 +00004829 if (BTT == BTT_IsNothrowAssignable)
4830 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004831
Alp Toker73287bf2014-01-20 00:24:09 +00004832 if (BTT == BTT_IsTriviallyAssignable) {
4833 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4834 // lifetime, this is a non-trivial assignment.
4835 if (Self.getLangOpts().ObjCAutoRefCount &&
4836 hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
4837 return false;
4838
4839 return !Result.get()->hasNonTrivialCall(Self.Context);
4840 }
4841
4842 llvm_unreachable("unhandled type trait");
4843 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00004844 }
Alp Tokercbb90342013-12-13 20:49:58 +00004845 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004846 }
4847 llvm_unreachable("Unknown type trait or not implemented");
4848}
4849
John Wiegley6242b6a2011-04-28 00:16:57 +00004850ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4851 SourceLocation KWLoc,
4852 ParsedType Ty,
4853 Expr* DimExpr,
4854 SourceLocation RParen) {
4855 TypeSourceInfo *TSInfo;
4856 QualType T = GetTypeFromParser(Ty, &TSInfo);
4857 if (!TSInfo)
4858 TSInfo = Context.getTrivialTypeSourceInfo(T);
4859
4860 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4861}
4862
4863static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4864 QualType T, Expr *DimExpr,
4865 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004866 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00004867
4868 switch(ATT) {
4869 case ATT_ArrayRank:
4870 if (T->isArrayType()) {
4871 unsigned Dim = 0;
4872 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4873 ++Dim;
4874 T = AT->getElementType();
4875 }
4876 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00004877 }
John Wiegleyd3522222011-04-28 02:06:46 +00004878 return 0;
4879
John Wiegley6242b6a2011-04-28 00:16:57 +00004880 case ATT_ArrayExtent: {
4881 llvm::APSInt Value;
4882 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00004883 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00004884 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00004885 false).isInvalid())
4886 return 0;
4887 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00004888 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4889 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00004890 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00004891 }
Richard Smithf4c51d92012-02-04 09:53:13 +00004892 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00004893
4894 if (T->isArrayType()) {
4895 unsigned D = 0;
4896 bool Matched = false;
4897 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4898 if (Dim == D) {
4899 Matched = true;
4900 break;
4901 }
4902 ++D;
4903 T = AT->getElementType();
4904 }
4905
John Wiegleyd3522222011-04-28 02:06:46 +00004906 if (Matched && T->isArrayType()) {
4907 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4908 return CAT->getSize().getLimitedValue();
4909 }
John Wiegley6242b6a2011-04-28 00:16:57 +00004910 }
John Wiegleyd3522222011-04-28 02:06:46 +00004911 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00004912 }
4913 }
4914 llvm_unreachable("Unknown type trait or not implemented");
4915}
4916
4917ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4918 SourceLocation KWLoc,
4919 TypeSourceInfo *TSInfo,
4920 Expr* DimExpr,
4921 SourceLocation RParen) {
4922 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00004923
Chandler Carruthc5276e52011-05-01 08:48:21 +00004924 // FIXME: This should likely be tracked as an APInt to remove any host
4925 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004926 uint64_t Value = 0;
4927 if (!T->isDependentType())
4928 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4929
Chandler Carruthc5276e52011-05-01 08:48:21 +00004930 // While the specification for these traits from the Embarcadero C++
4931 // compiler's documentation says the return type is 'unsigned int', Clang
4932 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4933 // compiler, there is no difference. On several other platforms this is an
4934 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004935 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4936 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00004937}
4938
John Wiegleyf9f65842011-04-25 06:54:41 +00004939ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004940 SourceLocation KWLoc,
4941 Expr *Queried,
4942 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004943 // If error parsing the expression, ignore.
4944 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004945 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00004946
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004947 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004948
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004949 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00004950}
4951
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004952static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4953 switch (ET) {
4954 case ET_IsLValueExpr: return E->isLValue();
4955 case ET_IsRValueExpr: return E->isRValue();
4956 }
4957 llvm_unreachable("Expression trait not covered by switch");
4958}
4959
John Wiegleyf9f65842011-04-25 06:54:41 +00004960ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004961 SourceLocation KWLoc,
4962 Expr *Queried,
4963 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004964 if (Queried->isTypeDependent()) {
4965 // Delay type-checking for type-dependent expressions.
4966 } else if (Queried->getType()->isPlaceholderType()) {
4967 ExprResult PE = CheckPlaceholderExpr(Queried);
4968 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004969 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004970 }
4971
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004972 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00004973
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004974 return new (Context)
4975 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00004976}
4977
Richard Trieu82402a02011-09-15 21:56:47 +00004978QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004979 ExprValueKind &VK,
4980 SourceLocation Loc,
4981 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004982 assert(!LHS.get()->getType()->isPlaceholderType() &&
4983 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00004984 "placeholders should have been weeded out by now");
4985
4986 // The LHS undergoes lvalue conversions if this is ->*.
4987 if (isIndirect) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004988 LHS = DefaultLvalueConversion(LHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00004989 if (LHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004990 }
4991
4992 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004993 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00004994 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004995
Sebastian Redl5822f082009-02-07 20:10:22 +00004996 const char *OpSpelling = isIndirect ? "->*" : ".*";
4997 // C++ 5.5p2
4998 // The binary operator .* [p3: ->*] binds its second operand, which shall
4999 // be of type "pointer to member of T" (where T is a completely-defined
5000 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005001 QualType RHSType = RHS.get()->getType();
5002 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005003 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005004 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005005 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005006 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005007 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005008
Sebastian Redl5822f082009-02-07 20:10:22 +00005009 QualType Class(MemPtr->getClass(), 0);
5010
Douglas Gregord07ba342010-10-13 20:41:14 +00005011 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5012 // member pointer points must be completely-defined. However, there is no
5013 // reason for this semantic distinction, and the rule is not enforced by
5014 // other compilers. Therefore, we do not check this property, as it is
5015 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005016
Sebastian Redl5822f082009-02-07 20:10:22 +00005017 // C++ 5.5p2
5018 // [...] to its first operand, which shall be of class T or of a class of
5019 // which T is an unambiguous and accessible base class. [p3: a pointer to
5020 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005021 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005022 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005023 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5024 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005025 else {
5026 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005027 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005028 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005029 return QualType();
5030 }
5031 }
5032
Richard Trieu82402a02011-09-15 21:56:47 +00005033 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005034 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005035 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5036 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005037 return QualType();
5038 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005039
Richard Smith0f59cb32015-12-18 21:45:41 +00005040 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005041 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005042 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005043 return QualType();
5044 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005045
5046 CXXCastPath BasePath;
5047 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5048 SourceRange(LHS.get()->getLocStart(),
5049 RHS.get()->getLocEnd()),
5050 &BasePath))
5051 return QualType();
5052
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005053 // Cast LHS to type of use.
5054 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005055 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005056 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005057 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005058 }
5059
Richard Trieu82402a02011-09-15 21:56:47 +00005060 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005061 // Diagnose use of pointer-to-member type which when used as
5062 // the functional cast in a pointer-to-member expression.
5063 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5064 return QualType();
5065 }
John McCall7decc9e2010-11-18 06:31:45 +00005066
Sebastian Redl5822f082009-02-07 20:10:22 +00005067 // C++ 5.5p2
5068 // The result is an object or a function of the type specified by the
5069 // second operand.
5070 // The cv qualifiers are the union of those in the pointer and the left side,
5071 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005072 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005073 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005074
Douglas Gregor1d042092011-01-26 16:40:18 +00005075 // C++0x [expr.mptr.oper]p6:
5076 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005077 // ill-formed if the second operand is a pointer to member function with
5078 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5079 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005080 // is a pointer to member function with ref-qualifier &&.
5081 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5082 switch (Proto->getRefQualifier()) {
5083 case RQ_None:
5084 // Do nothing
5085 break;
5086
5087 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005088 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005089 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005090 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005091 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005092
Douglas Gregor1d042092011-01-26 16:40:18 +00005093 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005094 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005095 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005096 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005097 break;
5098 }
5099 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005100
John McCall7decc9e2010-11-18 06:31:45 +00005101 // C++ [expr.mptr.oper]p6:
5102 // The result of a .* expression whose second operand is a pointer
5103 // to a data member is of the same value category as its
5104 // first operand. The result of a .* expression whose second
5105 // operand is a pointer to a member function is a prvalue. The
5106 // result of an ->* expression is an lvalue if its second operand
5107 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005108 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005109 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005110 return Context.BoundMemberTy;
5111 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005112 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005113 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005114 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005115 }
John McCall7decc9e2010-11-18 06:31:45 +00005116
Sebastian Redl5822f082009-02-07 20:10:22 +00005117 return Result;
5118}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005119
Richard Smith2414bca2016-04-25 19:30:37 +00005120/// \brief Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005121///
5122/// This is part of the parameter validation for the ? operator. If either
5123/// value operand is a class type, the two operands are attempted to be
5124/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005125/// It returns true if the program is ill-formed and has already been diagnosed
5126/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005127static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5128 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005129 bool &HaveConversion,
5130 QualType &ToType) {
5131 HaveConversion = false;
5132 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005133
5134 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005135 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005136 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005137 // The process for determining whether an operand expression E1 of type T1
5138 // can be converted to match an operand expression E2 of type T2 is defined
5139 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005140 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5141 // implicitly converted to type "lvalue reference to T2", subject to the
5142 // constraint that in the conversion the reference must bind directly to
5143 // an lvalue.
5144 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5145 // implicitly conveted to the type "rvalue reference to R2", subject to
5146 // the constraint that the reference must bind directly.
5147 if (To->isLValue() || To->isXValue()) {
5148 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5149 : Self.Context.getRValueReferenceType(ToType);
5150
Douglas Gregor838fcc32010-03-26 20:14:36 +00005151 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005152
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005153 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005154 if (InitSeq.isDirectReferenceBinding()) {
5155 ToType = T;
5156 HaveConversion = true;
5157 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005158 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005159
Douglas Gregor838fcc32010-03-26 20:14:36 +00005160 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005161 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005162 }
John McCall65eb8792010-02-25 01:37:24 +00005163
Sebastian Redl1a99f442009-04-16 17:51:27 +00005164 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5165 // -- if E1 and E2 have class type, and the underlying class types are
5166 // the same or one is a base class of the other:
5167 QualType FTy = From->getType();
5168 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005169 const RecordType *FRec = FTy->getAs<RecordType>();
5170 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005171 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005172 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5173 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5174 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005175 // E1 can be converted to match E2 if the class of T2 is the
5176 // same type as, or a base class of, the class of T1, and
5177 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005178 if (FRec == TRec || FDerivedFromT) {
5179 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005180 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005181 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005182 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005183 HaveConversion = true;
5184 return false;
5185 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005186
Douglas Gregor838fcc32010-03-26 20:14:36 +00005187 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005188 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005189 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005191
Douglas Gregor838fcc32010-03-26 20:14:36 +00005192 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005193 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005194
Douglas Gregor838fcc32010-03-26 20:14:36 +00005195 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5196 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005197 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005198 // an rvalue).
5199 //
5200 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5201 // to the array-to-pointer or function-to-pointer conversions.
5202 if (!TTy->getAs<TagType>())
5203 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005204
Douglas Gregor838fcc32010-03-26 20:14:36 +00005205 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005206 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005207 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005208 ToType = TTy;
5209 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005210 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005211
Sebastian Redl1a99f442009-04-16 17:51:27 +00005212 return false;
5213}
5214
5215/// \brief Try to find a common type for two according to C++0x 5.16p5.
5216///
5217/// This is part of the parameter validation for the ? operator. If either
5218/// value operand is a class type, overload resolution is used to find a
5219/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005220static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005221 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005222 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005223 OverloadCandidateSet CandidateSet(QuestionLoc,
5224 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005225 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005226 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005227
5228 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005229 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005230 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005231 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00005232 ExprResult LHSRes =
5233 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
5234 Best->Conversions[0], Sema::AA_Converting);
5235 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005236 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005237 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005238
5239 ExprResult RHSRes =
5240 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
5241 Best->Conversions[1], Sema::AA_Converting);
5242 if (RHSRes.isInvalid())
5243 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005244 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005245 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005246 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005247 return false;
John Wiegley01296292011-04-08 18:41:53 +00005248 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005249
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005250 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005251
5252 // Emit a better diagnostic if one of the expressions is a null pointer
5253 // constant and the other is a pointer type. In this case, the user most
5254 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005255 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005256 return true;
5257
5258 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005259 << LHS.get()->getType() << RHS.get()->getType()
5260 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005261 return true;
5262
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005263 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005264 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005265 << LHS.get()->getType() << RHS.get()->getType()
5266 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005267 // FIXME: Print the possible common types by printing the return types of
5268 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005269 break;
5270
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005271 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005272 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005273 }
5274 return true;
5275}
5276
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005277/// \brief Perform an "extended" implicit conversion as returned by
5278/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005279static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005280 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005281 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005282 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005283 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005284 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005285 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005286 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005287 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005288
John Wiegley01296292011-04-08 18:41:53 +00005289 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005290 return false;
5291}
5292
Sebastian Redl1a99f442009-04-16 17:51:27 +00005293/// \brief Check the operands of ?: under C++ semantics.
5294///
5295/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5296/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005297QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5298 ExprResult &RHS, ExprValueKind &VK,
5299 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005300 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005301 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5302 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005303
Richard Smith45edb702012-08-07 22:06:48 +00005304 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005305 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00005306 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005307 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005308 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005309 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005310 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005311 }
5312
John McCall7decc9e2010-11-18 06:31:45 +00005313 // Assume r-value.
5314 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005315 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005316
Sebastian Redl1a99f442009-04-16 17:51:27 +00005317 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005318 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005319 return Context.DependentTy;
5320
Richard Smith45edb702012-08-07 22:06:48 +00005321 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005322 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005323 QualType LTy = LHS.get()->getType();
5324 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005325 bool LVoid = LTy->isVoidType();
5326 bool RVoid = RTy->isVoidType();
5327 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005328 // ... one of the following shall hold:
5329 // -- The second or the third operand (but not both) is a (possibly
5330 // parenthesized) throw-expression; the result is of the type
5331 // and value category of the other.
5332 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5333 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5334 if (LThrow != RThrow) {
5335 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5336 VK = NonThrow->getValueKind();
5337 // DR (no number yet): the result is a bit-field if the
5338 // non-throw-expression operand is a bit-field.
5339 OK = NonThrow->getObjectKind();
5340 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005341 }
5342
Sebastian Redl1a99f442009-04-16 17:51:27 +00005343 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005344 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005345 if (LVoid && RVoid)
5346 return Context.VoidTy;
5347
5348 // Neither holds, error.
5349 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5350 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005351 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005352 return QualType();
5353 }
5354
5355 // Neither is void.
5356
Richard Smithf2b084f2012-08-08 06:13:49 +00005357 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005358 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005359 // either has (cv) class type [...] an attempt is made to convert each of
5360 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005361 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005362 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005363 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005364 QualType L2RType, R2LType;
5365 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005366 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005367 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005368 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005369 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005370
Sebastian Redl1a99f442009-04-16 17:51:27 +00005371 // If both can be converted, [...] the program is ill-formed.
5372 if (HaveL2R && HaveR2L) {
5373 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005374 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005375 return QualType();
5376 }
5377
5378 // If exactly one conversion is possible, that conversion is applied to
5379 // the chosen operand and the converted operands are used in place of the
5380 // original operands for the remainder of this section.
5381 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005382 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005383 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005384 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005385 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005386 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005387 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005388 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005389 }
5390 }
5391
Richard Smithf2b084f2012-08-08 06:13:49 +00005392 // C++11 [expr.cond]p3
5393 // if both are glvalues of the same value category and the same type except
5394 // for cv-qualification, an attempt is made to convert each of those
5395 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005396 // FIXME:
5397 // Resolving a defect in P0012R1: we extend this to cover all cases where
5398 // one of the operands is reference-compatible with the other, in order
5399 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005400 ExprValueKind LVK = LHS.get()->getValueKind();
5401 ExprValueKind RVK = RHS.get()->getValueKind();
5402 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005403 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005404 // DerivedToBase was already handled by the class-specific case above.
5405 // FIXME: Should we allow ObjC conversions here?
5406 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5407 if (CompareReferenceRelationship(
5408 QuestionLoc, LTy, RTy, DerivedToBase,
5409 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5410 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005411 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005412 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005413 } else if (CompareReferenceRelationship(
5414 QuestionLoc, RTy, LTy, DerivedToBase,
5415 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5416 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion) {
5417 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5418 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005419 }
5420 }
5421
5422 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005423 // If the second and third operands are glvalues of the same value
5424 // category and have the same type, the result is of that type and
5425 // value category and it is a bit-field if the second or the third
5426 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005427 // We only extend this to bitfields, not to the crazy other kinds of
5428 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005429 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005430 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005431 LHS.get()->isOrdinaryOrBitFieldObject() &&
5432 RHS.get()->isOrdinaryOrBitFieldObject()) {
5433 VK = LHS.get()->getValueKind();
5434 if (LHS.get()->getObjectKind() == OK_BitField ||
5435 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005436 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005437
5438 // If we have function pointer types, unify them anyway to unify their
5439 // exception specifications, if any.
5440 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5441 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005442 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005443 /*ConvertArgs*/false);
5444 LTy = Context.getQualifiedType(LTy, Qs);
5445
5446 assert(!LTy.isNull() && "failed to find composite pointer type for "
5447 "canonically equivalent function ptr types");
5448 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5449 }
5450
John McCall7decc9e2010-11-18 06:31:45 +00005451 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005452 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005453
Richard Smithf2b084f2012-08-08 06:13:49 +00005454 // C++11 [expr.cond]p5
5455 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005456 // do not have the same type, and either has (cv) class type, ...
5457 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5458 // ... overload resolution is used to determine the conversions (if any)
5459 // to be applied to the operands. If the overload resolution fails, the
5460 // program is ill-formed.
5461 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5462 return QualType();
5463 }
5464
Richard Smithf2b084f2012-08-08 06:13:49 +00005465 // C++11 [expr.cond]p6
5466 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005467 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005468 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5469 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005470 if (LHS.isInvalid() || RHS.isInvalid())
5471 return QualType();
5472 LTy = LHS.get()->getType();
5473 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005474
5475 // After those conversions, one of the following shall hold:
5476 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005477 // is of that type. If the operands have class type, the result
5478 // is a prvalue temporary of the result type, which is
5479 // copy-initialized from either the second operand or the third
5480 // operand depending on the value of the first operand.
5481 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5482 if (LTy->isRecordType()) {
5483 // The operands have class type. Make a temporary copy.
David Blaikie6154ef92012-09-10 22:05:41 +00005484 if (RequireNonAbstractType(QuestionLoc, LTy,
5485 diag::err_allocation_of_abstract_type))
5486 return QualType();
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005487 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005488
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005489 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5490 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005491 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005492 if (LHSCopy.isInvalid())
5493 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005494
5495 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5496 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005497 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005498 if (RHSCopy.isInvalid())
5499 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005500
John Wiegley01296292011-04-08 18:41:53 +00005501 LHS = LHSCopy;
5502 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005503 }
5504
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005505 // If we have function pointer types, unify them anyway to unify their
5506 // exception specifications, if any.
5507 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5508 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5509 assert(!LTy.isNull() && "failed to find composite pointer type for "
5510 "canonically equivalent function ptr types");
5511 }
5512
Sebastian Redl1a99f442009-04-16 17:51:27 +00005513 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005514 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005515
Douglas Gregor46188682010-05-18 22:42:18 +00005516 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005517 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005518 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5519 /*AllowBothBool*/true,
5520 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005521
Sebastian Redl1a99f442009-04-16 17:51:27 +00005522 // -- The second and third operands have arithmetic or enumeration type;
5523 // the usual arithmetic conversions are performed to bring them to a
5524 // common type, and the result is of that type.
5525 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005526 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005527 if (LHS.isInvalid() || RHS.isInvalid())
5528 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005529 if (ResTy.isNull()) {
5530 Diag(QuestionLoc,
5531 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5532 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5533 return QualType();
5534 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005535
5536 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5537 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5538
5539 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005540 }
5541
5542 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005543 // type and the other is a null pointer constant, or both are null
5544 // pointer constants, at least one of which is non-integral; pointer
5545 // conversions and qualification conversions are performed to bring them
5546 // to their composite pointer type. The result is of the composite
5547 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005548 // -- The second and third operands have pointer to member type, or one has
5549 // pointer to member type and the other is a null pointer constant;
5550 // pointer to member conversions and qualification conversions are
5551 // performed to bring them to a common type, whose cv-qualification
5552 // shall match the cv-qualification of either the second or the third
5553 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005554 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5555 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005556 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005557
Douglas Gregor697a3912010-04-01 22:47:07 +00005558 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005559 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5560 if (!Composite.isNull())
5561 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005562
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005563 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005564 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005565 return QualType();
5566
Sebastian Redl1a99f442009-04-16 17:51:27 +00005567 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005568 << LHS.get()->getType() << RHS.get()->getType()
5569 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005570 return QualType();
5571}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005572
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005573static FunctionProtoType::ExceptionSpecInfo
5574mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5575 FunctionProtoType::ExceptionSpecInfo ESI2,
5576 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5577 ExceptionSpecificationType EST1 = ESI1.Type;
5578 ExceptionSpecificationType EST2 = ESI2.Type;
5579
5580 // If either of them can throw anything, that is the result.
5581 if (EST1 == EST_None) return ESI1;
5582 if (EST2 == EST_None) return ESI2;
5583 if (EST1 == EST_MSAny) return ESI1;
5584 if (EST2 == EST_MSAny) return ESI2;
5585
5586 // If either of them is non-throwing, the result is the other.
5587 if (EST1 == EST_DynamicNone) return ESI2;
5588 if (EST2 == EST_DynamicNone) return ESI1;
5589 if (EST1 == EST_BasicNoexcept) return ESI2;
5590 if (EST2 == EST_BasicNoexcept) return ESI1;
5591
5592 // If either of them is a non-value-dependent computed noexcept, that
5593 // determines the result.
5594 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5595 !ESI2.NoexceptExpr->isValueDependent())
5596 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5597 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5598 !ESI1.NoexceptExpr->isValueDependent())
5599 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5600 // If we're left with value-dependent computed noexcept expressions, we're
5601 // stuck. Before C++17, we can just drop the exception specification entirely,
5602 // since it's not actually part of the canonical type. And this should never
5603 // happen in C++17, because it would mean we were computing the composite
5604 // pointer type of dependent types, which should never happen.
5605 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
5606 assert(!S.getLangOpts().CPlusPlus1z &&
5607 "computing composite pointer type of dependent types");
5608 return FunctionProtoType::ExceptionSpecInfo();
5609 }
5610
5611 // Switch over the possibilities so that people adding new values know to
5612 // update this function.
5613 switch (EST1) {
5614 case EST_None:
5615 case EST_DynamicNone:
5616 case EST_MSAny:
5617 case EST_BasicNoexcept:
5618 case EST_ComputedNoexcept:
5619 llvm_unreachable("handled above");
5620
5621 case EST_Dynamic: {
5622 // This is the fun case: both exception specifications are dynamic. Form
5623 // the union of the two lists.
5624 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5625 llvm::SmallPtrSet<QualType, 8> Found;
5626 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5627 for (QualType E : Exceptions)
5628 if (Found.insert(S.Context.getCanonicalType(E)).second)
5629 ExceptionTypeStorage.push_back(E);
5630
5631 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5632 Result.Exceptions = ExceptionTypeStorage;
5633 return Result;
5634 }
5635
5636 case EST_Unevaluated:
5637 case EST_Uninstantiated:
5638 case EST_Unparsed:
5639 llvm_unreachable("shouldn't see unresolved exception specifications here");
5640 }
5641
5642 llvm_unreachable("invalid ExceptionSpecificationType");
5643}
5644
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005645/// \brief Find a merged pointer type and convert the two expressions to it.
5646///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005647/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005648/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005649/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005650/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005651///
Douglas Gregor19175ff2010-04-16 23:20:25 +00005652/// \param Loc The location of the operator requiring these two expressions to
5653/// be converted to the composite pointer type.
5654///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005655/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005656QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00005657 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005658 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005659 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005660
5661 // C++1z [expr]p14:
5662 // The composite pointer type of two operands p1 and p2 having types T1
5663 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005664 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005665
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005666 // where at least one is a pointer or pointer to member type or
5667 // std::nullptr_t is:
5668 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5669 T1->isNullPtrType();
5670 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5671 T2->isNullPtrType();
5672 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00005673 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005674
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005675 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5676 // This can't actually happen, following the standard, but we also use this
5677 // to implement the end of [expr.conv], which hits this case.
5678 //
5679 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5680 if (T1IsPointerLike &&
5681 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005682 if (ConvertArgs)
5683 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5684 ? CK_NullToMemberPointer
5685 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005686 return T1;
5687 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005688 if (T2IsPointerLike &&
5689 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005690 if (ConvertArgs)
5691 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5692 ? CK_NullToMemberPointer
5693 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005694 return T2;
5695 }
Mike Stump11289f42009-09-09 15:08:12 +00005696
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005697 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005698 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005699 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005700 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
5701 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005702
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005703 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5704 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5705 // the union of cv1 and cv2;
5706 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5707 // "pointer to function", where the function types are otherwise the same,
5708 // "pointer to function";
5709 // FIXME: This rule is defective: it should also permit removing noexcept
5710 // from a pointer to member function. As a Clang extension, we also
5711 // permit removing 'noreturn', so we generalize this rule to;
5712 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5713 // "pointer to member function" and the pointee types can be unified
5714 // by a function pointer conversion, that conversion is applied
5715 // before checking the following rules.
5716 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5717 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5718 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5719 // respectively;
5720 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5721 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5722 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5723 // T1 or the cv-combined type of T1 and T2, respectively;
5724 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5725 // T2;
5726 //
5727 // If looked at in the right way, these bullets all do the same thing.
5728 // What we do here is, we build the two possible cv-combined types, and try
5729 // the conversions in both directions. If only one works, or if the two
5730 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00005731 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005732 //
5733 // Note that this will fail to find a composite pointer type for "pointer
5734 // to void" and "pointer to function". We can't actually perform the final
5735 // conversion in this case, even though a composite pointer type formally
5736 // exists.
5737 SmallVector<unsigned, 4> QualifierUnion;
5738 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005739 QualType Composite1 = T1;
5740 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005742 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005743 const PointerType *Ptr1, *Ptr2;
5744 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5745 (Ptr2 = Composite2->getAs<PointerType>())) {
5746 Composite1 = Ptr1->getPointeeType();
5747 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005748
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005749 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005750 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005751 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005752 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005753
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005754 QualifierUnion.push_back(
5755 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00005756 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005757 continue;
5758 }
Mike Stump11289f42009-09-09 15:08:12 +00005759
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005760 const MemberPointerType *MemPtr1, *MemPtr2;
5761 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5762 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5763 Composite1 = MemPtr1->getPointeeType();
5764 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005765
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005766 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005767 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00005768 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005769 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005770
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005771 QualifierUnion.push_back(
5772 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5773 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5774 MemPtr2->getClass()));
5775 continue;
5776 }
Mike Stump11289f42009-09-09 15:08:12 +00005777
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005778 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00005779
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005780 // Cannot unwrap any more types.
5781 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005782 }
Mike Stump11289f42009-09-09 15:08:12 +00005783
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005784 // Apply the function pointer conversion to unify the types. We've already
5785 // unwrapped down to the function types, and we want to merge rather than
5786 // just convert, so do this ourselves rather than calling
5787 // IsFunctionConversion.
5788 //
5789 // FIXME: In order to match the standard wording as closely as possible, we
5790 // currently only do this under a single level of pointers. Ideally, we would
5791 // allow this in general, and set NeedConstBefore to the relevant depth on
5792 // the side(s) where we changed anything.
5793 if (QualifierUnion.size() == 1) {
5794 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5795 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5796 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5797 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5798
5799 // The result is noreturn if both operands are.
5800 bool Noreturn =
5801 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5802 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5803 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5804
5805 // The result is nothrow if both operands are.
5806 SmallVector<QualType, 8> ExceptionTypeStorage;
5807 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
5808 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
5809 ExceptionTypeStorage);
5810
5811 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
5812 FPT1->getParamTypes(), EPI1);
5813 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
5814 FPT2->getParamTypes(), EPI2);
5815 }
5816 }
5817 }
5818
Richard Smith5e9746f2016-10-21 22:00:42 +00005819 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005820 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005821 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005822 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00005823 for (unsigned I = 0; I != NeedConstBefore; ++I)
5824 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005825 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005826 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005827
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005828 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005829 auto MOC = MemberOfClass.rbegin();
5830 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
5831 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
5832 auto Classes = *MOC++;
5833 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005834 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005835 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005836 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00005837 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005838 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005839 } else {
5840 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005841 Composite1 =
5842 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5843 Composite2 =
5844 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005845 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005846 }
5847
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005848 struct Conversion {
5849 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005850 Expr *&E1, *&E2;
5851 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00005852 InitializedEntity Entity;
5853 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005854 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00005855 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00005856
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005857 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
5858 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00005859 : S(S), E1(E1), E2(E2), Composite(Composite),
5860 Entity(InitializedEntity::InitializeTemporary(Composite)),
5861 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
5862 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
5863 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005864
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005865 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005866 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
5867 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005868 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005869 E1 = E1Result.getAs<Expr>();
5870
5871 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
5872 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005873 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005874 E2 = E2Result.getAs<Expr>();
5875
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005876 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005877 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005878 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00005879
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005880 // Try to convert to each composite pointer type.
5881 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005882 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
5883 if (ConvertArgs && C1.perform())
5884 return QualType();
5885 return C1.Composite;
5886 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005887 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005888
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005889 if (C1.Viable == C2.Viable) {
5890 // Either Composite1 and Composite2 are viable and are different, or
5891 // neither is viable.
5892 // FIXME: How both be viable and different?
5893 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005894 }
5895
Richard Smith6ffdb1f2016-10-20 01:20:00 +00005896 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005897 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
5898 return QualType();
5899
5900 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005901}
Anders Carlsson85a307d2009-05-17 18:41:29 +00005902
John McCalldadc5752010-08-24 06:29:42 +00005903ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00005904 if (!E)
5905 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005906
John McCall31168b02011-06-15 23:02:42 +00005907 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
5908
5909 // If the result is a glvalue, we shouldn't bind it.
5910 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005911 return E;
Mike Stump11289f42009-09-09 15:08:12 +00005912
John McCall31168b02011-06-15 23:02:42 +00005913 // In ARC, calls that return a retainable type can return retained,
5914 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005915 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00005916 E->getType()->isObjCRetainableType()) {
5917
5918 bool ReturnsRetained;
5919
5920 // For actual calls, we compute this by examining the type of the
5921 // called value.
5922 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5923 Expr *Callee = Call->getCallee()->IgnoreParens();
5924 QualType T = Callee->getType();
5925
5926 if (T == Context.BoundMemberTy) {
5927 // Handle pointer-to-members.
5928 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5929 T = BinOp->getRHS()->getType();
5930 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5931 T = Mem->getMemberDecl()->getType();
5932 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005933
John McCall31168b02011-06-15 23:02:42 +00005934 if (const PointerType *Ptr = T->getAs<PointerType>())
5935 T = Ptr->getPointeeType();
5936 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
5937 T = Ptr->getPointeeType();
5938 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
5939 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00005940
John McCall31168b02011-06-15 23:02:42 +00005941 const FunctionType *FTy = T->getAs<FunctionType>();
5942 assert(FTy && "call to value not of function type?");
5943 ReturnsRetained = FTy->getExtInfo().getProducesResult();
5944
5945 // ActOnStmtExpr arranges things so that StmtExprs of retainable
5946 // type always produce a +1 object.
5947 } else if (isa<StmtExpr>(E)) {
5948 ReturnsRetained = true;
5949
Ted Kremeneke65b0862012-03-06 20:05:56 +00005950 // We hit this case with the lambda conversion-to-block optimization;
5951 // we don't want any extra casts here.
5952 } else if (isa<CastExpr>(E) &&
5953 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005954 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005955
John McCall31168b02011-06-15 23:02:42 +00005956 // For message sends and property references, we try to find an
5957 // actual method. FIXME: we should infer retention by selector in
5958 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00005959 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00005960 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005961 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
5962 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00005963 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
5964 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00005965 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
5966 D = ArrayLit->getArrayWithObjectsMethod();
5967 } else if (ObjCDictionaryLiteral *DictLit
5968 = dyn_cast<ObjCDictionaryLiteral>(E)) {
5969 D = DictLit->getDictWithObjectsMethod();
5970 }
John McCall31168b02011-06-15 23:02:42 +00005971
5972 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00005973
5974 // Don't do reclaims on performSelector calls; despite their
5975 // return type, the invoked method doesn't necessarily actually
5976 // return an object.
5977 if (!ReturnsRetained &&
5978 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005979 return E;
John McCall31168b02011-06-15 23:02:42 +00005980 }
5981
John McCall16de4d22011-11-14 19:53:16 +00005982 // Don't reclaim an object of Class type.
5983 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005984 return E;
John McCall16de4d22011-11-14 19:53:16 +00005985
Tim Shen4a05bb82016-06-21 20:29:17 +00005986 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00005987
John McCall2d637d22011-09-10 06:18:15 +00005988 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
5989 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005990 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
5991 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00005992 }
5993
David Blaikiebbafb8a2012-03-11 07:00:24 +00005994 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005995 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00005996
Peter Collingbournec331a1e2012-01-26 03:33:51 +00005997 // Search for the base element type (cf. ASTContext::getBaseElementType) with
5998 // a fast path for the common case that the type is directly a RecordType.
5999 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006000 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006001 while (!RT) {
6002 switch (T->getTypeClass()) {
6003 case Type::Record:
6004 RT = cast<RecordType>(T);
6005 break;
6006 case Type::ConstantArray:
6007 case Type::IncompleteArray:
6008 case Type::VariableArray:
6009 case Type::DependentSizedArray:
6010 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6011 break;
6012 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006013 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006014 }
6015 }
Mike Stump11289f42009-09-09 15:08:12 +00006016
Richard Smithfd555f62012-02-22 02:04:18 +00006017 // That should be enough to guarantee that this type is complete, if we're
6018 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006019 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006020 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006021 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006022
6023 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006024 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006025
John McCall31168b02011-06-15 23:02:42 +00006026 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006027 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006028 CheckDestructorAccess(E->getExprLoc(), Destructor,
6029 PDiag(diag::err_access_dtor_temp)
6030 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006031 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6032 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006033
Richard Smithfd555f62012-02-22 02:04:18 +00006034 // If destructor is trivial, we can avoid the extra copy.
6035 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006036 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006037
John McCall28fc7092011-11-10 05:35:25 +00006038 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006039 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006040 }
Richard Smitheec915d62012-02-18 04:13:32 +00006041
6042 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006043 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6044
6045 if (IsDecltype)
6046 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6047
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006048 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006049}
6050
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006051ExprResult
John McCall5d413782010-12-06 08:20:24 +00006052Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006053 if (SubExpr.isInvalid())
6054 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006055
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006056 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006057}
6058
John McCall28fc7092011-11-10 05:35:25 +00006059Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006060 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006061
Eli Friedman3bda6b12012-02-02 23:15:15 +00006062 CleanupVarDeclMarking();
6063
John McCall28fc7092011-11-10 05:35:25 +00006064 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6065 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006066 assert(Cleanup.exprNeedsCleanups() ||
6067 ExprCleanupObjects.size() == FirstCleanup);
6068 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006069 return SubExpr;
6070
Craig Topper5fc8fc22014-08-27 06:28:36 +00006071 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6072 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006073
Tim Shen4a05bb82016-06-21 20:29:17 +00006074 auto *E = ExprWithCleanups::Create(
6075 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006076 DiscardCleanupsInEvaluationContext();
6077
6078 return E;
6079}
6080
John McCall5d413782010-12-06 08:20:24 +00006081Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006082 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006083
Eli Friedman3bda6b12012-02-02 23:15:15 +00006084 CleanupVarDeclMarking();
6085
Tim Shen4a05bb82016-06-21 20:29:17 +00006086 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006087 return SubStmt;
6088
6089 // FIXME: In order to attach the temporaries, wrap the statement into
6090 // a StmtExpr; currently this is only used for asm statements.
6091 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6092 // a new AsmStmtWithTemporaries.
Nico Webera2a0eb92012-12-29 20:03:39 +00006093 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006094 SourceLocation(),
6095 SourceLocation());
6096 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6097 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006098 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006099}
6100
Richard Smithfd555f62012-02-22 02:04:18 +00006101/// Process the expression contained within a decltype. For such expressions,
6102/// certain semantic checks on temporaries are delayed until this point, and
6103/// are omitted for the 'topmost' call in the decltype expression. If the
6104/// topmost call bound a temporary, strip that temporary off the expression.
6105ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006106 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006107
6108 // C++11 [expr.call]p11:
6109 // If a function call is a prvalue of object type,
6110 // -- if the function call is either
6111 // -- the operand of a decltype-specifier, or
6112 // -- the right operand of a comma operator that is the operand of a
6113 // decltype-specifier,
6114 // a temporary object is not introduced for the prvalue.
6115
6116 // Recursively rebuild ParenExprs and comma expressions to strip out the
6117 // outermost CXXBindTemporaryExpr, if any.
6118 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6119 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6120 if (SubExpr.isInvalid())
6121 return ExprError();
6122 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006123 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006124 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006125 }
6126 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6127 if (BO->getOpcode() == BO_Comma) {
6128 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6129 if (RHS.isInvalid())
6130 return ExprError();
6131 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006132 return E;
6133 return new (Context) BinaryOperator(
6134 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6135 BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
Richard Smithfd555f62012-02-22 02:04:18 +00006136 }
6137 }
6138
6139 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006140 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6141 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006142 if (TopCall)
6143 E = TopCall;
6144 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006145 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006146
6147 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006148 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00006149
Richard Smithf86b0ae2012-07-28 19:54:11 +00006150 // In MS mode, don't perform any extra checking of call return types within a
6151 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006152 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006153 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006154
Richard Smithfd555f62012-02-22 02:04:18 +00006155 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006156 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6157 I != N; ++I) {
6158 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006159 if (Call == TopCall)
6160 continue;
6161
David Majnemerced8bdf2015-02-25 17:36:15 +00006162 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006163 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006164 Call, Call->getDirectCallee()))
6165 return ExprError();
6166 }
6167
6168 // Now all relevant types are complete, check the destructors are accessible
6169 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006170 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6171 I != N; ++I) {
6172 CXXBindTemporaryExpr *Bind =
6173 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006174 if (Bind == TopBind)
6175 continue;
6176
6177 CXXTemporary *Temp = Bind->getTemporary();
6178
6179 CXXRecordDecl *RD =
6180 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6181 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6182 Temp->setDestructor(Destructor);
6183
Richard Smith7d847b12012-05-11 22:20:10 +00006184 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6185 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006186 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006187 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006188 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6189 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006190
6191 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006192 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006193 }
6194
6195 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006196 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006197}
6198
Richard Smith79c927b2013-11-06 19:31:51 +00006199/// Note a set of 'operator->' functions that were used for a member access.
6200static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006201 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006202 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6203 // FIXME: Make this configurable?
6204 unsigned Limit = 9;
6205 if (OperatorArrows.size() > Limit) {
6206 // Produce Limit-1 normal notes and one 'skipping' note.
6207 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6208 SkipCount = OperatorArrows.size() - (Limit - 1);
6209 }
6210
6211 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6212 if (I == SkipStart) {
6213 S.Diag(OperatorArrows[I]->getLocation(),
6214 diag::note_operator_arrows_suppressed)
6215 << SkipCount;
6216 I += SkipCount;
6217 } else {
6218 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6219 << OperatorArrows[I]->getCallResultType();
6220 ++I;
6221 }
6222 }
6223}
6224
Nico Weber964d3322015-02-16 22:35:45 +00006225ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6226 SourceLocation OpLoc,
6227 tok::TokenKind OpKind,
6228 ParsedType &ObjectType,
6229 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006230 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006231 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006232 if (Result.isInvalid()) return ExprError();
6233 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006234
John McCall526ab472011-10-25 17:37:35 +00006235 Result = CheckPlaceholderExpr(Base);
6236 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006237 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006238
John McCallb268a282010-08-23 23:25:46 +00006239 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006240 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006241 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006242 // If we have a pointer to a dependent type and are using the -> operator,
6243 // the object type is the type that the pointer points to. We might still
6244 // have enough information about that type to do something useful.
6245 if (OpKind == tok::arrow)
6246 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6247 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006248
John McCallba7bf592010-08-24 05:47:05 +00006249 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006250 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006251 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006252 }
Mike Stump11289f42009-09-09 15:08:12 +00006253
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006254 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006255 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006256 // returned, with the original second operand.
6257 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006258 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006259 bool NoArrowOperatorFound = false;
6260 bool FirstIteration = true;
6261 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006262 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006263 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006264 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006265 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006266
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006267 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006268 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6269 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006270 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006271 noteOperatorArrows(*this, OperatorArrows);
6272 Diag(OpLoc, diag::note_operator_arrow_depth)
6273 << getLangOpts().ArrowDepth;
6274 return ExprError();
6275 }
6276
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006277 Result = BuildOverloadedArrowExpr(
6278 S, Base, OpLoc,
6279 // When in a template specialization and on the first loop iteration,
6280 // potentially give the default diagnostic (with the fixit in a
6281 // separate note) instead of having the error reported back to here
6282 // and giving a diagnostic with a fixit attached to the error itself.
6283 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006284 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006285 : &NoArrowOperatorFound);
6286 if (Result.isInvalid()) {
6287 if (NoArrowOperatorFound) {
6288 if (FirstIteration) {
6289 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006290 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006291 << FixItHint::CreateReplacement(OpLoc, ".");
6292 OpKind = tok::period;
6293 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006294 }
6295 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6296 << BaseType << Base->getSourceRange();
6297 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006298 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006299 Diag(CD->getLocStart(),
6300 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006301 }
6302 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006303 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006304 }
John McCallb268a282010-08-23 23:25:46 +00006305 Base = Result.get();
6306 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006307 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006308 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006309 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006310 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006311 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6312 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006313 return ExprError();
6314 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006315 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006316 }
Mike Stump11289f42009-09-09 15:08:12 +00006317
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006318 if (OpKind == tok::arrow &&
6319 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006320 BaseType = BaseType->getPointeeType();
6321 }
Mike Stump11289f42009-09-09 15:08:12 +00006322
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006323 // Objective-C properties allow "." access on Objective-C pointer types,
6324 // so adjust the base type to the object type itself.
6325 if (BaseType->isObjCObjectPointerType())
6326 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006327
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006328 // C++ [basic.lookup.classref]p2:
6329 // [...] If the type of the object expression is of pointer to scalar
6330 // type, the unqualified-id is looked up in the context of the complete
6331 // postfix-expression.
6332 //
6333 // This also indicates that we could be parsing a pseudo-destructor-name.
6334 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006335 // expressions or normal member (ivar or property) access expressions, and
6336 // it's legal for the type to be incomplete if this is a pseudo-destructor
6337 // call. We'll do more incomplete-type checks later in the lookup process,
6338 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006339 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006340 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006341 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006342 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006343 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006344 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006345 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006346 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006347 }
Mike Stump11289f42009-09-09 15:08:12 +00006348
Douglas Gregor3024f072012-04-16 07:05:22 +00006349 // The object type must be complete (or dependent), or
6350 // C++11 [expr.prim.general]p3:
6351 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006352 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006353 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006354 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006355 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006356 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006357 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006358
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006359 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006360 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006361 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006362 // type C (or of pointer to a class type C), the unqualified-id is looked
6363 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006364 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006365 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006366}
6367
Simon Pilgrim75c26882016-09-30 14:25:09 +00006368static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006369 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006370 if (Base->hasPlaceholderType()) {
6371 ExprResult result = S.CheckPlaceholderExpr(Base);
6372 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006373 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006374 }
6375 ObjectType = Base->getType();
6376
David Blaikie1d578782011-12-16 16:03:09 +00006377 // C++ [expr.pseudo]p2:
6378 // The left-hand side of the dot operator shall be of scalar type. The
6379 // left-hand side of the arrow operator shall be of pointer to scalar type.
6380 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006381 // Note that this is rather different from the normal handling for the
6382 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006383 if (OpKind == tok::arrow) {
6384 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6385 ObjectType = Ptr->getPointeeType();
6386 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006387 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006388 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6389 << ObjectType << true
6390 << FixItHint::CreateReplacement(OpLoc, ".");
6391 if (S.isSFINAEContext())
6392 return true;
6393
6394 OpKind = tok::period;
6395 }
6396 }
6397
6398 return false;
6399}
6400
John McCalldadc5752010-08-24 06:29:42 +00006401ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006402 SourceLocation OpLoc,
6403 tok::TokenKind OpKind,
6404 const CXXScopeSpec &SS,
6405 TypeSourceInfo *ScopeTypeInfo,
6406 SourceLocation CCLoc,
6407 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006408 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006409 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006410
Eli Friedman0ce4de42012-01-25 04:35:06 +00006411 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006412 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6413 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006414
Douglas Gregorc5c57342012-09-10 14:57:06 +00006415 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6416 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006417 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006418 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006419 else {
Nico Weber58829272012-01-23 05:50:57 +00006420 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6421 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006422 return ExprError();
6423 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006424 }
6425
6426 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006427 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006428 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006429 if (DestructedTypeInfo) {
6430 QualType DestructedType = DestructedTypeInfo->getType();
6431 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006432 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006433 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6434 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6435 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6436 << ObjectType << DestructedType << Base->getSourceRange()
6437 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006438
John McCall31168b02011-06-15 23:02:42 +00006439 // Recover by setting the destructed type to the object type.
6440 DestructedType = ObjectType;
6441 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregor678f90d2010-02-25 01:56:36 +00006442 DestructedTypeStart);
John McCall31168b02011-06-15 23:02:42 +00006443 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
Simon Pilgrim75c26882016-09-30 14:25:09 +00006444 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006445 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006446
John McCall31168b02011-06-15 23:02:42 +00006447 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6448 // Okay: just pretend that the user provided the correctly-qualified
6449 // type.
6450 } else {
6451 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6452 << ObjectType << DestructedType << Base->getSourceRange()
6453 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6454 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006455
John McCall31168b02011-06-15 23:02:42 +00006456 // Recover by setting the destructed type to the object type.
6457 DestructedType = ObjectType;
6458 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6459 DestructedTypeStart);
6460 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6461 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006462 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006464
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006465 // C++ [expr.pseudo]p2:
6466 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6467 // form
6468 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006469 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006470 //
6471 // shall designate the same scalar type.
6472 if (ScopeTypeInfo) {
6473 QualType ScopeType = ScopeTypeInfo->getType();
6474 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006475 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006476
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006477 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006478 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006479 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006480 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006481
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006482 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006483 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006484 }
6485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006486
John McCallb268a282010-08-23 23:25:46 +00006487 Expr *Result
6488 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6489 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006490 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006491 ScopeTypeInfo,
6492 CCLoc,
6493 TildeLoc,
6494 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006495
David Majnemerced8bdf2015-02-25 17:36:15 +00006496 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006497}
6498
John McCalldadc5752010-08-24 06:29:42 +00006499ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006500 SourceLocation OpLoc,
6501 tok::TokenKind OpKind,
6502 CXXScopeSpec &SS,
6503 UnqualifiedId &FirstTypeName,
6504 SourceLocation CCLoc,
6505 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006506 UnqualifiedId &SecondTypeName) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006507 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6508 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6509 "Invalid first type name in pseudo-destructor");
6510 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6511 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6512 "Invalid second type name in pseudo-destructor");
6513
Eli Friedman0ce4de42012-01-25 04:35:06 +00006514 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006515 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6516 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006517
6518 // Compute the object type that we should use for name lookup purposes. Only
6519 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006520 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006521 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006522 if (ObjectType->isRecordType())
6523 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006524 else if (ObjectType->isDependentType())
6525 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006526 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006527
6528 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006529 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006530 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006531 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006532 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006533 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006534 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006535 SecondTypeName.StartLocation,
Fariborz Jahanian87967422011-02-08 18:05:59 +00006536 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006537 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006538 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6539 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006540 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006541 // couldn't find anything useful in scope. Just store the identifier and
6542 // it's location, and we'll perform (qualified) name lookup again at
6543 // template instantiation time.
6544 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6545 SecondTypeName.StartLocation);
6546 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006547 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006548 diag::err_pseudo_dtor_destructor_non_type)
6549 << SecondTypeName.Identifier << ObjectType;
6550 if (isSFINAEContext())
6551 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006552
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006553 // Recover by assuming we had the right type all along.
6554 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006555 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006556 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006557 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006558 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006559 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006560 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006561 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006562 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006563 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006564 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006565 TemplateId->TemplateNameLoc,
6566 TemplateId->LAngleLoc,
6567 TemplateArgsPtr,
6568 TemplateId->RAngleLoc);
6569 if (T.isInvalid() || !T.get()) {
6570 // Recover by assuming we had the right type all along.
6571 DestructedType = ObjectType;
6572 } else
6573 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006574 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006575
6576 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006577 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006578 if (!DestructedType.isNull()) {
6579 if (!DestructedTypeInfo)
6580 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006581 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006582 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006584
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006585 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006586 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006587 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006588 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006589 FirstTypeName.Identifier) {
6590 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006591 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006592 FirstTypeName.StartLocation,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006593 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006594 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006595 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006596 diag::err_pseudo_dtor_destructor_non_type)
6597 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006598
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006599 if (isSFINAEContext())
6600 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006601
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006602 // Just drop this type. It's unnecessary anyway.
6603 ScopeType = QualType();
6604 } else
6605 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006606 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006607 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006608 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006609 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006610 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006611 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006612 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006613 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006614 TemplateId->TemplateNameLoc,
6615 TemplateId->LAngleLoc,
6616 TemplateArgsPtr,
6617 TemplateId->RAngleLoc);
6618 if (T.isInvalid() || !T.get()) {
6619 // Recover by dropping this type.
6620 ScopeType = QualType();
6621 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006622 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006623 }
6624 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006625
Douglas Gregor90ad9222010-02-24 23:02:30 +00006626 if (!ScopeType.isNull() && !ScopeTypeInfo)
6627 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6628 FirstTypeName.StartLocation);
6629
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006630
John McCallb268a282010-08-23 23:25:46 +00006631 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00006632 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006633 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00006634}
6635
David Blaikie1d578782011-12-16 16:03:09 +00006636ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6637 SourceLocation OpLoc,
6638 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006639 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006640 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00006641 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006642 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6643 return ExprError();
6644
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006645 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6646 false);
David Blaikie1d578782011-12-16 16:03:09 +00006647
6648 TypeLocBuilder TLB;
6649 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6650 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6651 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6652 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6653
6654 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006655 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006656 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00006657}
6658
John Wiegley01296292011-04-08 18:41:53 +00006659ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00006660 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006661 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00006662 if (Method->getParent()->isLambda() &&
6663 Method->getConversionType()->isBlockPointerType()) {
6664 // This is a lambda coversion to block pointer; check if the argument
6665 // is a LambdaExpr.
6666 Expr *SubE = E;
6667 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6668 if (CE && CE->getCastKind() == CK_NoOp)
6669 SubE = CE->getSubExpr();
6670 SubE = SubE->IgnoreParens();
6671 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6672 SubE = BE->getSubExpr();
6673 if (isa<LambdaExpr>(SubE)) {
6674 // For the conversion to block pointer on a lambda expression, we
6675 // construct a special BlockLiteral instead; this doesn't really make
6676 // a difference in ARC, but outside of ARC the resulting block literal
6677 // follows the normal lifetime rules for block literals instead of being
6678 // autoreleased.
6679 DiagnosticErrorTrap Trap(Diags);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006680 PushExpressionEvaluationContext(PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00006681 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6682 E->getExprLoc(),
6683 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00006684 PopExpressionEvaluationContext();
6685
Eli Friedman98b01ed2012-03-01 04:01:32 +00006686 if (Exp.isInvalid())
6687 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6688 return Exp;
6689 }
6690 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00006691
Craig Topperc3ec1492014-05-26 06:22:03 +00006692 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006693 FoundDecl, Method);
6694 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00006695 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00006696
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00006697 MemberExpr *ME = new (Context) MemberExpr(
6698 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6699 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006700 if (HadMultipleCandidates)
6701 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00006702 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006703
Alp Toker314cc812014-01-25 16:55:45 +00006704 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00006705 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6706 ResultType = ResultType.getNonLValueExprType(Context);
6707
Douglas Gregor27381f32009-11-23 12:27:39 +00006708 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006709 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00006710 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006711 return CE;
6712}
6713
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006714ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6715 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00006716 // If the operand is an unresolved lookup expression, the expression is ill-
6717 // formed per [over.over]p1, because overloaded function names cannot be used
6718 // without arguments except in explicit contexts.
6719 ExprResult R = CheckPlaceholderExpr(Operand);
6720 if (R.isInvalid())
6721 return R;
6722
6723 // The operand may have been modified when checking the placeholder type.
6724 Operand = R.get();
6725
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006726 if (ActiveTemplateInstantiations.empty() &&
6727 Operand->HasSideEffects(Context, false)) {
6728 // The expression operand for noexcept is in an unevaluated expression
6729 // context, so side effects could result in unintended consequences.
6730 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6731 }
6732
Richard Smithf623c962012-04-17 00:58:00 +00006733 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006734 return new (Context)
6735 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006736}
6737
6738ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6739 Expr *Operand, SourceLocation RParen) {
6740 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00006741}
6742
Eli Friedmanf798f652012-05-24 22:04:19 +00006743static bool IsSpecialDiscardedValue(Expr *E) {
6744 // In C++11, discarded-value expressions of a certain form are special,
6745 // according to [expr]p10:
6746 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6747 // expression is an lvalue of volatile-qualified type and it has
6748 // one of the following forms:
6749 E = E->IgnoreParens();
6750
Eli Friedmanc49c2262012-05-24 22:36:31 +00006751 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006752 if (isa<DeclRefExpr>(E))
6753 return true;
6754
Eli Friedmanc49c2262012-05-24 22:36:31 +00006755 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006756 if (isa<ArraySubscriptExpr>(E))
6757 return true;
6758
Eli Friedmanc49c2262012-05-24 22:36:31 +00006759 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006760 if (isa<MemberExpr>(E))
6761 return true;
6762
Eli Friedmanc49c2262012-05-24 22:36:31 +00006763 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006764 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6765 if (UO->getOpcode() == UO_Deref)
6766 return true;
6767
6768 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00006769 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006770 if (BO->isPtrMemOp())
6771 return true;
6772
Eli Friedmanc49c2262012-05-24 22:36:31 +00006773 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00006774 if (BO->getOpcode() == BO_Comma)
6775 return IsSpecialDiscardedValue(BO->getRHS());
6776 }
6777
Eli Friedmanc49c2262012-05-24 22:36:31 +00006778 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00006779 // operands are one of the above, or
6780 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6781 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6782 IsSpecialDiscardedValue(CO->getFalseExpr());
6783 // The related edge case of "*x ?: *x".
6784 if (BinaryConditionalOperator *BCO =
6785 dyn_cast<BinaryConditionalOperator>(E)) {
6786 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6787 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6788 IsSpecialDiscardedValue(BCO->getFalseExpr());
6789 }
6790
6791 // Objective-C++ extensions to the rule.
6792 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6793 return true;
6794
6795 return false;
6796}
6797
John McCall34376a62010-12-04 03:47:34 +00006798/// Perform the conversions required for an expression used in a
6799/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00006800ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00006801 if (E->hasPlaceholderType()) {
6802 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006803 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006804 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00006805 }
6806
John McCallfee942d2010-12-02 02:07:15 +00006807 // C99 6.3.2.1:
6808 // [Except in specific positions,] an lvalue that does not have
6809 // array type is converted to the value stored in the
6810 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00006811 if (E->isRValue()) {
6812 // In C, function designators (i.e. expressions of function type)
6813 // are r-values, but we still want to do function-to-pointer decay
6814 // on them. This is both technically correct and convenient for
6815 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006816 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00006817 return DefaultFunctionArrayConversion(E);
6818
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006819 return E;
John McCalld68b2d02011-06-27 21:24:11 +00006820 }
John McCallfee942d2010-12-02 02:07:15 +00006821
Eli Friedmanf798f652012-05-24 22:04:19 +00006822 if (getLangOpts().CPlusPlus) {
6823 // The C++11 standard defines the notion of a discarded-value expression;
6824 // normally, we don't need to do anything to handle it, but if it is a
6825 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6826 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006827 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00006828 E->getType().isVolatileQualified() &&
6829 IsSpecialDiscardedValue(E)) {
6830 ExprResult Res = DefaultLvalueConversion(E);
6831 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006832 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006833 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006834 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006835 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00006836 }
John McCall34376a62010-12-04 03:47:34 +00006837
6838 // GCC seems to also exclude expressions of incomplete enum type.
6839 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6840 if (!T->getDecl()->isComplete()) {
6841 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006842 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006843 return E;
John McCall34376a62010-12-04 03:47:34 +00006844 }
6845 }
6846
John Wiegley01296292011-04-08 18:41:53 +00006847 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6848 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006849 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006850 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00006851
John McCallca61b652010-12-04 12:29:11 +00006852 if (!E->getType()->isVoidType())
6853 RequireCompleteType(E->getExprLoc(), E->getType(),
6854 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006855 return E;
John McCall34376a62010-12-04 03:47:34 +00006856}
6857
Faisal Valia17d19f2013-11-07 05:17:06 +00006858// If we can unambiguously determine whether Var can never be used
6859// in a constant expression, return true.
6860// - if the variable and its initializer are non-dependent, then
6861// we can unambiguously check if the variable is a constant expression.
6862// - if the initializer is not value dependent - we can determine whether
6863// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00006864// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00006865// never be a constant expression.
6866// - FXIME: if the initializer is dependent, we can still do some analysis and
6867// identify certain cases unambiguously as non-const by using a Visitor:
6868// - such as those that involve odr-use of a ParmVarDecl, involve a new
6869// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00006870static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00006871 ASTContext &Context) {
6872 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006873 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006874
6875 // If there is no initializer - this can not be a constant expression.
6876 if (!Var->getAnyInitializer(DefVD)) return true;
6877 assert(DefVD);
6878 if (DefVD->isWeak()) return false;
6879 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00006880
Faisal Valia17d19f2013-11-07 05:17:06 +00006881 Expr *Init = cast<Expr>(Eval->Value);
6882
6883 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00006884 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
6885 // of value-dependent expressions, and use it here to determine whether the
6886 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00006887 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00006888 }
6889
Simon Pilgrim75c26882016-09-30 14:25:09 +00006890 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00006891}
6892
Simon Pilgrim75c26882016-09-30 14:25:09 +00006893/// \brief Check if the current lambda has any potential captures
6894/// that must be captured by any of its enclosing lambdas that are ready to
6895/// capture. If there is a lambda that can capture a nested
6896/// potential-capture, go ahead and do so. Also, check to see if any
6897/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00006898/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00006899
Faisal Valiab3d6462013-12-07 20:22:44 +00006900static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
6901 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
6902
Simon Pilgrim75c26882016-09-30 14:25:09 +00006903 assert(!S.isUnevaluatedContext());
6904 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00006905#ifndef NDEBUG
6906 DeclContext *DC = S.CurContext;
6907 while (DC && isa<CapturedDecl>(DC))
6908 DC = DC->getParent();
6909 assert(
6910 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00006911 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00006912#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00006913
6914 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
6915
6916 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
6917 S.FunctionScopes.data(), S.FunctionScopes.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00006918
Faisal Valiab3d6462013-12-07 20:22:44 +00006919 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00006920 // lambda (within a generic outer lambda), must be captured by an
6921 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00006922 const unsigned NumPotentialCaptures =
6923 CurrentLSI->getNumPotentialVariableCaptures();
6924 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006925 Expr *VarExpr = nullptr;
6926 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006927 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00006928 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00006929 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00006930 // need to check enclosing lambda's for speculative captures.
6931 // For e.g.:
6932 // Even though 'x' is not odr-used, it should be captured.
6933 // int test() {
6934 // const int x = 10;
6935 // auto L = [=](auto a) {
6936 // (void) +x + a;
6937 // };
6938 // }
6939 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00006940 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00006941 continue;
6942
6943 // If we have a capture-capable lambda for the variable, go ahead and
6944 // capture the variable in that lambda (and all its enclosing lambdas).
6945 if (const Optional<unsigned> Index =
6946 getStackIndexOfNearestEnclosingCaptureCapableLambda(
6947 FunctionScopesArrayRef, Var, S)) {
6948 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6949 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
6950 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00006951 }
6952 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00006953 VariableCanNeverBeAConstantExpression(Var, S.Context);
6954 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
6955 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00006956 // can not be used in a constant expression - which means
6957 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00006958 // capture violation early, if the variable is un-captureable.
6959 // This is purely for diagnosing errors early. Otherwise, this
6960 // error would get diagnosed when the lambda becomes capture ready.
6961 QualType CaptureType, DeclRefType;
6962 SourceLocation ExprLoc = VarExpr->getExprLoc();
6963 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006964 /*EllipsisLoc*/ SourceLocation(),
6965 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00006966 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00006967 // We will never be able to capture this variable, and we need
6968 // to be able to in any and all instantiations, so diagnose it.
6969 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00006970 /*EllipsisLoc*/ SourceLocation(),
6971 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00006972 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00006973 }
6974 }
6975 }
6976
Faisal Valiab3d6462013-12-07 20:22:44 +00006977 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00006978 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00006979 // If we have a capture-capable lambda for 'this', go ahead and capture
6980 // 'this' in that lambda (and all its enclosing lambdas).
6981 if (const Optional<unsigned> Index =
6982 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Craig Topperc3ec1492014-05-26 06:22:03 +00006983 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00006984 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6985 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
6986 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
6987 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00006988 }
6989 }
Faisal Valiab3d6462013-12-07 20:22:44 +00006990
6991 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00006992 CurrentLSI->clearPotentialCaptures();
6993}
6994
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006995static ExprResult attemptRecovery(Sema &SemaRef,
6996 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00006997 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006998 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
6999 Consumer.getLookupResult().getLookupKind());
7000 const CXXScopeSpec *SS = Consumer.getSS();
7001 CXXScopeSpec NewSS;
7002
7003 // Use an approprate CXXScopeSpec for building the expr.
7004 if (auto *NNS = TC.getCorrectionSpecifier())
7005 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7006 else if (SS && !TC.WillReplaceSpecifier())
7007 NewSS = *SS;
7008
Richard Smithde6d6c42015-12-29 19:43:10 +00007009 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007010 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007011 R.addDecl(ND);
7012 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007013 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007014 CXXRecordDecl *Record = nullptr;
7015 if (auto *NNS = TC.getCorrectionSpecifier())
7016 Record = NNS->getAsType()->getAsCXXRecordDecl();
7017 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007018 Record =
7019 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7020 if (Record)
7021 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007022
7023 // Detect and handle the case where the decl might be an implicit
7024 // member.
7025 bool MightBeImplicitMember;
7026 if (!Consumer.isAddressOfOperand())
7027 MightBeImplicitMember = true;
7028 else if (!NewSS.isEmpty())
7029 MightBeImplicitMember = false;
7030 else if (R.isOverloadedResult())
7031 MightBeImplicitMember = false;
7032 else if (R.isUnresolvableResult())
7033 MightBeImplicitMember = true;
7034 else
7035 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7036 isa<IndirectFieldDecl>(ND) ||
7037 isa<MSPropertyDecl>(ND);
7038
7039 if (MightBeImplicitMember)
7040 return SemaRef.BuildPossibleImplicitMemberExpr(
7041 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007042 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007043 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7044 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7045 Ivar->getIdentifier());
7046 }
7047 }
7048
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007049 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7050 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007051}
7052
Kaelyn Takata6c759512014-10-27 18:07:37 +00007053namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007054class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7055 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7056
7057public:
7058 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7059 : TypoExprs(TypoExprs) {}
7060 bool VisitTypoExpr(TypoExpr *TE) {
7061 TypoExprs.insert(TE);
7062 return true;
7063 }
7064};
7065
Kaelyn Takata6c759512014-10-27 18:07:37 +00007066class TransformTypos : public TreeTransform<TransformTypos> {
7067 typedef TreeTransform<TransformTypos> BaseTransform;
7068
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007069 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7070 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007071 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007072 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007073 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007074 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007075
7076 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7077 /// If the TypoExprs were successfully corrected, then the diagnostics should
7078 /// suggest the corrections. Otherwise the diagnostics will not suggest
7079 /// anything (having been passed an empty TypoCorrection).
7080 void EmitAllDiagnostics() {
7081 for (auto E : TypoExprs) {
7082 TypoExpr *TE = cast<TypoExpr>(E);
7083 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007084 if (State.DiagHandler) {
7085 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7086 ExprResult Replacement = TransformCache[TE];
7087
7088 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7089 // TypoCorrection, replacing the existing decls. This ensures the right
7090 // NamedDecl is used in diagnostics e.g. in the case where overload
7091 // resolution was used to select one from several possible decls that
7092 // had been stored in the TypoCorrection.
7093 if (auto *ND = getDeclFromExpr(
7094 Replacement.isInvalid() ? nullptr : Replacement.get()))
7095 TC.setCorrectionDecl(ND);
7096
7097 State.DiagHandler(TC);
7098 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007099 SemaRef.clearDelayedTypo(TE);
7100 }
7101 }
7102
7103 /// \brief If corrections for the first TypoExpr have been exhausted for a
7104 /// given combination of the other TypoExprs, retry those corrections against
7105 /// the next combination of substitutions for the other TypoExprs by advancing
7106 /// to the next potential correction of the second TypoExpr. For the second
7107 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7108 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7109 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7110 /// TransformCache). Returns true if there is still any untried combinations
7111 /// of corrections.
7112 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7113 for (auto TE : TypoExprs) {
7114 auto &State = SemaRef.getTypoExprState(TE);
7115 TransformCache.erase(TE);
7116 if (!State.Consumer->finished())
7117 return true;
7118 State.Consumer->resetCorrectionStream();
7119 }
7120 return false;
7121 }
7122
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007123 NamedDecl *getDeclFromExpr(Expr *E) {
7124 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7125 E = OverloadResolution[OE];
7126
7127 if (!E)
7128 return nullptr;
7129 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007130 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007131 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007132 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007133 // FIXME: Add any other expr types that could be be seen by the delayed typo
7134 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007135 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007136 return nullptr;
7137 }
7138
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007139 ExprResult TryTransform(Expr *E) {
7140 Sema::SFINAETrap Trap(SemaRef);
7141 ExprResult Res = TransformExpr(E);
7142 if (Trap.hasErrorOccurred() || Res.isInvalid())
7143 return ExprError();
7144
7145 return ExprFilter(Res.get());
7146 }
7147
Kaelyn Takata6c759512014-10-27 18:07:37 +00007148public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007149 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7150 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007151
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007152 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7153 MultiExprArg Args,
7154 SourceLocation RParenLoc,
7155 Expr *ExecConfig = nullptr) {
7156 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7157 RParenLoc, ExecConfig);
7158 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007159 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007160 Expr *ResultCall = Result.get();
7161 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7162 ResultCall = BE->getSubExpr();
7163 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7164 OverloadResolution[OE] = CE->getCallee();
7165 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007166 }
7167 return Result;
7168 }
7169
Kaelyn Takata6c759512014-10-27 18:07:37 +00007170 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7171
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007172 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7173
Saleem Abdulrasool407f36b2016-02-07 02:30:55 +00007174 ExprResult TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
7175 return Owned(E);
7176 }
7177
Saleem Abdulrasool02e19a12016-02-07 02:30:59 +00007178 ExprResult TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
7179 return Owned(E);
7180 }
7181
Kaelyn Takata6c759512014-10-27 18:07:37 +00007182 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007183 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007184 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007185 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007186
Kaelyn Takata6c759512014-10-27 18:07:37 +00007187 // Exit if either the transform was valid or if there were no TypoExprs
7188 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007189 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007190 !CheckAndAdvanceTypoExprCorrectionStreams())
7191 break;
7192 }
7193
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007194 // Ensure none of the TypoExprs have multiple typo correction candidates
7195 // with the same edit length that pass all the checks and filters.
7196 // TODO: Properly handle various permutations of possible corrections when
7197 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007198 // Also, disable typo correction while attempting the transform when
7199 // handling potentially ambiguous typo corrections as any new TypoExprs will
7200 // have been introduced by the application of one of the correction
7201 // candidates and add little to no value if corrected.
7202 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007203 while (!AmbiguousTypoExprs.empty()) {
7204 auto TE = AmbiguousTypoExprs.back();
7205 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007206 auto &State = SemaRef.getTypoExprState(TE);
7207 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007208 TransformCache.erase(TE);
7209 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007210 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007211 TransformCache.erase(TE);
7212 Res = ExprError();
7213 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007214 }
7215 AmbiguousTypoExprs.remove(TE);
7216 State.Consumer->restoreSavedPosition();
7217 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007218 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007219 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007220
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007221 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007222 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007223 FindTypoExprs(TypoExprs).TraverseStmt(E);
7224
Kaelyn Takata6c759512014-10-27 18:07:37 +00007225 EmitAllDiagnostics();
7226
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007227 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007228 }
7229
7230 ExprResult TransformTypoExpr(TypoExpr *E) {
7231 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7232 // cached transformation result if there is one and the TypoExpr isn't the
7233 // first one that was encountered.
7234 auto &CacheEntry = TransformCache[E];
7235 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7236 return CacheEntry;
7237 }
7238
7239 auto &State = SemaRef.getTypoExprState(E);
7240 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7241
7242 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7243 // typo correction and return it.
7244 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007245 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007246 continue;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007247 ExprResult NE = State.RecoveryHandler ?
7248 State.RecoveryHandler(SemaRef, E, TC) :
7249 attemptRecovery(SemaRef, *State.Consumer, TC);
7250 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007251 // Check whether there may be a second viable correction with the same
7252 // edit distance; if so, remember this TypoExpr may have an ambiguous
7253 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007254 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007255 if ((Next = State.Consumer->peekNextCorrection()) &&
7256 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7257 AmbiguousTypoExprs.insert(E);
7258 } else {
7259 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007260 }
7261 assert(!NE.isUnset() &&
7262 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007263 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007264 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007265 }
7266 return CacheEntry = ExprError();
7267 }
7268};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007269}
Faisal Valia17d19f2013-11-07 05:17:06 +00007270
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007271ExprResult
7272Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7273 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007274 // If the current evaluation context indicates there are uncorrected typos
7275 // and the current expression isn't guaranteed to not have typos, try to
7276 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007277 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007278 (E->isTypeDependent() || E->isValueDependent() ||
7279 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007280 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7281 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7282 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007283 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007284 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00007285 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00007286 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007287 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007288 ExprEvalContexts.back().NumTypos -= TyposResolved;
7289 return Result;
7290 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007291 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007292 }
7293 return E;
7294}
7295
Richard Smith945f8d32013-01-14 22:39:08 +00007296ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007297 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007298 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007299 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007300 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007301
7302 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007303 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007304
7305 // If we are an init-expression in a lambdas init-capture, we should not
7306 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007307 // containing full-expression is done).
7308 // template<class ... Ts> void test(Ts ... t) {
7309 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7310 // return a;
7311 // }() ...);
7312 // }
7313 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7314 // when we parse the lambda introducer, and teach capturing (but not
7315 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7316 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7317 // lambda where we've entered the introducer but not the body, or represent a
7318 // lambda where we've entered the body, depending on where the
7319 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007320 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007321 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007322 return ExprError();
7323
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007324 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007325 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007326 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007327 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007328 if (FullExpr.isInvalid())
7329 return ExprError();
7330 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007331
Richard Smith945f8d32013-01-14 22:39:08 +00007332 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007333 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007334 if (FullExpr.isInvalid())
7335 return ExprError();
7336
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007337 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007338 if (FullExpr.isInvalid())
7339 return ExprError();
7340 }
John Wiegley01296292011-04-08 18:41:53 +00007341
Kaelyn Takata49d84322014-11-11 23:26:56 +00007342 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7343 if (FullExpr.isInvalid())
7344 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007345
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007346 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007347
Simon Pilgrim75c26882016-09-30 14:25:09 +00007348 // At the end of this full expression (which could be a deeply nested
7349 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007350 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007351 // Consider the following code:
7352 // void f(int, int);
7353 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007354 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007355 // const int x = 10, y = 20;
7356 // auto L = [=](auto a) {
7357 // auto M = [=](auto b) {
7358 // f(x, b); <-- requires x to be captured by L and M
7359 // f(y, a); <-- requires y to be captured by L, but not all Ms
7360 // };
7361 // };
7362 // }
7363
Simon Pilgrim75c26882016-09-30 14:25:09 +00007364 // FIXME: Also consider what happens for something like this that involves
7365 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007366 // void f() {
7367 // const int n = 0;
7368 // auto L = [&](auto a) {
7369 // +n + ({ 0; a; });
7370 // };
7371 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007372 //
7373 // Here, we see +n, and then the full-expression 0; ends, so we don't
7374 // capture n (and instead remove it from our list of potential captures),
7375 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007376 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007377
Alexey Bataev31939e32016-11-11 12:36:20 +00007378 LambdaScopeInfo *const CurrentLSI =
7379 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007380 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007381 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007382 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007383 // By ensuring we are in the context of a lambda's call operator
7384 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007385 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007386 // PR, a proper fix would entail :
7387 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007388 // - Add to Sema an integer holding the smallest (outermost) scope
7389 // index that we are *lexically* within, and save/restore/set to
7390 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007391 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007392 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007393 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007394 DeclContext *DC = CurContext;
7395 while (DC && isa<CapturedDecl>(DC))
7396 DC = DC->getParent();
7397 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007398 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007399 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007400 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7401 *this);
John McCall5d413782010-12-06 08:20:24 +00007402 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007403}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007404
7405StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7406 if (!FullStmt) return StmtError();
7407
John McCall5d413782010-12-06 08:20:24 +00007408 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007409}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007410
Simon Pilgrim75c26882016-09-30 14:25:09 +00007411Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007412Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7413 CXXScopeSpec &SS,
7414 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007415 DeclarationName TargetName = TargetNameInfo.getName();
7416 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007417 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007418
Douglas Gregor43edb322011-10-24 22:31:10 +00007419 // If the name itself is dependent, then the result is dependent.
7420 if (TargetName.isDependentName())
7421 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007422
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007423 // Do the redeclaration lookup in the current scope.
7424 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7425 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007426 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007427 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007428
Douglas Gregor43edb322011-10-24 22:31:10 +00007429 switch (R.getResultKind()) {
7430 case LookupResult::Found:
7431 case LookupResult::FoundOverloaded:
7432 case LookupResult::FoundUnresolvedValue:
7433 case LookupResult::Ambiguous:
7434 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007435
Douglas Gregor43edb322011-10-24 22:31:10 +00007436 case LookupResult::NotFound:
7437 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007438
Douglas Gregor43edb322011-10-24 22:31:10 +00007439 case LookupResult::NotFoundInCurrentInstantiation:
7440 return IER_Dependent;
7441 }
David Blaikie8a40f702012-01-17 06:56:22 +00007442
7443 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007444}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007445
Simon Pilgrim75c26882016-09-30 14:25:09 +00007446Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007447Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7448 bool IsIfExists, CXXScopeSpec &SS,
7449 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007450 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007451
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007452 // Check for unexpanded parameter packs.
7453 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
7454 collectUnexpandedParameterPacks(SS, Unexpanded);
7455 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
7456 if (!Unexpanded.empty()) {
7457 DiagnoseUnexpandedParameterPacks(KeywordLoc,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007458 IsIfExists? UPPC_IfExists
7459 : UPPC_IfNotExists,
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007460 Unexpanded);
7461 return IER_Error;
7462 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007463
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007464 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7465}