Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/freebsd-src
Path: blob/main/contrib/llvm-project/clang/lib/Sema/SemaExprCXX.cpp
35233 views
1
//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
///
9
/// \file
10
/// Implements semantic analysis for C++ expressions.
11
///
12
//===----------------------------------------------------------------------===//
13
14
#include "TreeTransform.h"
15
#include "TypeLocBuilder.h"
16
#include "clang/AST/ASTContext.h"
17
#include "clang/AST/ASTLambda.h"
18
#include "clang/AST/CXXInheritance.h"
19
#include "clang/AST/CharUnits.h"
20
#include "clang/AST/DeclObjC.h"
21
#include "clang/AST/ExprCXX.h"
22
#include "clang/AST/ExprConcepts.h"
23
#include "clang/AST/ExprObjC.h"
24
#include "clang/AST/RecursiveASTVisitor.h"
25
#include "clang/AST/Type.h"
26
#include "clang/AST/TypeLoc.h"
27
#include "clang/Basic/AlignedAllocation.h"
28
#include "clang/Basic/DiagnosticSema.h"
29
#include "clang/Basic/PartialDiagnostic.h"
30
#include "clang/Basic/TargetInfo.h"
31
#include "clang/Basic/TokenKinds.h"
32
#include "clang/Basic/TypeTraits.h"
33
#include "clang/Lex/Preprocessor.h"
34
#include "clang/Sema/DeclSpec.h"
35
#include "clang/Sema/EnterExpressionEvaluationContext.h"
36
#include "clang/Sema/Initialization.h"
37
#include "clang/Sema/Lookup.h"
38
#include "clang/Sema/ParsedTemplate.h"
39
#include "clang/Sema/Scope.h"
40
#include "clang/Sema/ScopeInfo.h"
41
#include "clang/Sema/SemaCUDA.h"
42
#include "clang/Sema/SemaInternal.h"
43
#include "clang/Sema/SemaLambda.h"
44
#include "clang/Sema/SemaObjC.h"
45
#include "clang/Sema/SemaPPC.h"
46
#include "clang/Sema/Template.h"
47
#include "clang/Sema/TemplateDeduction.h"
48
#include "llvm/ADT/APInt.h"
49
#include "llvm/ADT/STLExtras.h"
50
#include "llvm/ADT/STLForwardCompat.h"
51
#include "llvm/ADT/StringExtras.h"
52
#include "llvm/Support/ErrorHandling.h"
53
#include "llvm/Support/TypeSize.h"
54
#include <optional>
55
using namespace clang;
56
using namespace sema;
57
58
ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
59
SourceLocation NameLoc,
60
const IdentifierInfo &Name) {
61
NestedNameSpecifier *NNS = SS.getScopeRep();
62
63
// Convert the nested-name-specifier into a type.
64
QualType Type;
65
switch (NNS->getKind()) {
66
case NestedNameSpecifier::TypeSpec:
67
case NestedNameSpecifier::TypeSpecWithTemplate:
68
Type = QualType(NNS->getAsType(), 0);
69
break;
70
71
case NestedNameSpecifier::Identifier:
72
// Strip off the last layer of the nested-name-specifier and build a
73
// typename type for it.
74
assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
75
Type = Context.getDependentNameType(
76
ElaboratedTypeKeyword::None, NNS->getPrefix(), NNS->getAsIdentifier());
77
break;
78
79
case NestedNameSpecifier::Global:
80
case NestedNameSpecifier::Super:
81
case NestedNameSpecifier::Namespace:
82
case NestedNameSpecifier::NamespaceAlias:
83
llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
84
}
85
86
// This reference to the type is located entirely at the location of the
87
// final identifier in the qualified-id.
88
return CreateParsedType(Type,
89
Context.getTrivialTypeSourceInfo(Type, NameLoc));
90
}
91
92
ParsedType Sema::getConstructorName(const IdentifierInfo &II,
93
SourceLocation NameLoc, Scope *S,
94
CXXScopeSpec &SS, bool EnteringContext) {
95
CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
96
assert(CurClass && &II == CurClass->getIdentifier() &&
97
"not a constructor name");
98
99
// When naming a constructor as a member of a dependent context (eg, in a
100
// friend declaration or an inherited constructor declaration), form an
101
// unresolved "typename" type.
102
if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
103
QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
104
SS.getScopeRep(), &II);
105
return ParsedType::make(T);
106
}
107
108
if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
109
return ParsedType();
110
111
// Find the injected-class-name declaration. Note that we make no attempt to
112
// diagnose cases where the injected-class-name is shadowed: the only
113
// declaration that can validly shadow the injected-class-name is a
114
// non-static data member, and if the class contains both a non-static data
115
// member and a constructor then it is ill-formed (we check that in
116
// CheckCompletedCXXClass).
117
CXXRecordDecl *InjectedClassName = nullptr;
118
for (NamedDecl *ND : CurClass->lookup(&II)) {
119
auto *RD = dyn_cast<CXXRecordDecl>(ND);
120
if (RD && RD->isInjectedClassName()) {
121
InjectedClassName = RD;
122
break;
123
}
124
}
125
if (!InjectedClassName) {
126
if (!CurClass->isInvalidDecl()) {
127
// FIXME: RequireCompleteDeclContext doesn't check dependent contexts
128
// properly. Work around it here for now.
129
Diag(SS.getLastQualifierNameLoc(),
130
diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
131
}
132
return ParsedType();
133
}
134
135
QualType T = Context.getTypeDeclType(InjectedClassName);
136
DiagnoseUseOfDecl(InjectedClassName, NameLoc);
137
MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
138
139
return ParsedType::make(T);
140
}
141
142
ParsedType Sema::getDestructorName(const IdentifierInfo &II,
143
SourceLocation NameLoc, Scope *S,
144
CXXScopeSpec &SS, ParsedType ObjectTypePtr,
145
bool EnteringContext) {
146
// Determine where to perform name lookup.
147
148
// FIXME: This area of the standard is very messy, and the current
149
// wording is rather unclear about which scopes we search for the
150
// destructor name; see core issues 399 and 555. Issue 399 in
151
// particular shows where the current description of destructor name
152
// lookup is completely out of line with existing practice, e.g.,
153
// this appears to be ill-formed:
154
//
155
// namespace N {
156
// template <typename T> struct S {
157
// ~S();
158
// };
159
// }
160
//
161
// void f(N::S<int>* s) {
162
// s->N::S<int>::~S();
163
// }
164
//
165
// See also PR6358 and PR6359.
166
//
167
// For now, we accept all the cases in which the name given could plausibly
168
// be interpreted as a correct destructor name, issuing off-by-default
169
// extension diagnostics on the cases that don't strictly conform to the
170
// C++20 rules. This basically means we always consider looking in the
171
// nested-name-specifier prefix, the complete nested-name-specifier, and
172
// the scope, and accept if we find the expected type in any of the three
173
// places.
174
175
if (SS.isInvalid())
176
return nullptr;
177
178
// Whether we've failed with a diagnostic already.
179
bool Failed = false;
180
181
llvm::SmallVector<NamedDecl*, 8> FoundDecls;
182
llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;
183
184
// If we have an object type, it's because we are in a
185
// pseudo-destructor-expression or a member access expression, and
186
// we know what type we're looking for.
187
QualType SearchType =
188
ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
189
190
auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
191
auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
192
auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
193
if (!Type)
194
return false;
195
196
if (SearchType.isNull() || SearchType->isDependentType())
197
return true;
198
199
QualType T = Context.getTypeDeclType(Type);
200
return Context.hasSameUnqualifiedType(T, SearchType);
201
};
202
203
unsigned NumAcceptableResults = 0;
204
for (NamedDecl *D : Found) {
205
if (IsAcceptableResult(D))
206
++NumAcceptableResults;
207
208
// Don't list a class twice in the lookup failure diagnostic if it's
209
// found by both its injected-class-name and by the name in the enclosing
210
// scope.
211
if (auto *RD = dyn_cast<CXXRecordDecl>(D))
212
if (RD->isInjectedClassName())
213
D = cast<NamedDecl>(RD->getParent());
214
215
if (FoundDeclSet.insert(D).second)
216
FoundDecls.push_back(D);
217
}
218
219
// As an extension, attempt to "fix" an ambiguity by erasing all non-type
220
// results, and all non-matching results if we have a search type. It's not
221
// clear what the right behavior is if destructor lookup hits an ambiguity,
222
// but other compilers do generally accept at least some kinds of
223
// ambiguity.
224
if (Found.isAmbiguous() && NumAcceptableResults == 1) {
225
Diag(NameLoc, diag::ext_dtor_name_ambiguous);
226
LookupResult::Filter F = Found.makeFilter();
227
while (F.hasNext()) {
228
NamedDecl *D = F.next();
229
if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
230
Diag(D->getLocation(), diag::note_destructor_type_here)
231
<< Context.getTypeDeclType(TD);
232
else
233
Diag(D->getLocation(), diag::note_destructor_nontype_here);
234
235
if (!IsAcceptableResult(D))
236
F.erase();
237
}
238
F.done();
239
}
240
241
if (Found.isAmbiguous())
242
Failed = true;
243
244
if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
245
if (IsAcceptableResult(Type)) {
246
QualType T = Context.getTypeDeclType(Type);
247
MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
248
return CreateParsedType(
249
Context.getElaboratedType(ElaboratedTypeKeyword::None, nullptr, T),
250
Context.getTrivialTypeSourceInfo(T, NameLoc));
251
}
252
}
253
254
return nullptr;
255
};
256
257
bool IsDependent = false;
258
259
auto LookupInObjectType = [&]() -> ParsedType {
260
if (Failed || SearchType.isNull())
261
return nullptr;
262
263
IsDependent |= SearchType->isDependentType();
264
265
LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
266
DeclContext *LookupCtx = computeDeclContext(SearchType);
267
if (!LookupCtx)
268
return nullptr;
269
LookupQualifiedName(Found, LookupCtx);
270
return CheckLookupResult(Found);
271
};
272
273
auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
274
if (Failed)
275
return nullptr;
276
277
IsDependent |= isDependentScopeSpecifier(LookupSS);
278
DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
279
if (!LookupCtx)
280
return nullptr;
281
282
LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
283
if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
284
Failed = true;
285
return nullptr;
286
}
287
LookupQualifiedName(Found, LookupCtx);
288
return CheckLookupResult(Found);
289
};
290
291
auto LookupInScope = [&]() -> ParsedType {
292
if (Failed || !S)
293
return nullptr;
294
295
LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
296
LookupName(Found, S);
297
return CheckLookupResult(Found);
298
};
299
300
// C++2a [basic.lookup.qual]p6:
301
// In a qualified-id of the form
302
//
303
// nested-name-specifier[opt] type-name :: ~ type-name
304
//
305
// the second type-name is looked up in the same scope as the first.
306
//
307
// We interpret this as meaning that if you do a dual-scope lookup for the
308
// first name, you also do a dual-scope lookup for the second name, per
309
// C++ [basic.lookup.classref]p4:
310
//
311
// If the id-expression in a class member access is a qualified-id of the
312
// form
313
//
314
// class-name-or-namespace-name :: ...
315
//
316
// the class-name-or-namespace-name following the . or -> is first looked
317
// up in the class of the object expression and the name, if found, is used.
318
// Otherwise, it is looked up in the context of the entire
319
// postfix-expression.
320
//
321
// This looks in the same scopes as for an unqualified destructor name:
322
//
323
// C++ [basic.lookup.classref]p3:
324
// If the unqualified-id is ~ type-name, the type-name is looked up
325
// in the context of the entire postfix-expression. If the type T
326
// of the object expression is of a class type C, the type-name is
327
// also looked up in the scope of class C. At least one of the
328
// lookups shall find a name that refers to cv T.
329
//
330
// FIXME: The intent is unclear here. Should type-name::~type-name look in
331
// the scope anyway if it finds a non-matching name declared in the class?
332
// If both lookups succeed and find a dependent result, which result should
333
// we retain? (Same question for p->~type-name().)
334
335
if (NestedNameSpecifier *Prefix =
336
SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
337
// This is
338
//
339
// nested-name-specifier type-name :: ~ type-name
340
//
341
// Look for the second type-name in the nested-name-specifier.
342
CXXScopeSpec PrefixSS;
343
PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
344
if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
345
return T;
346
} else {
347
// This is one of
348
//
349
// type-name :: ~ type-name
350
// ~ type-name
351
//
352
// Look in the scope and (if any) the object type.
353
if (ParsedType T = LookupInScope())
354
return T;
355
if (ParsedType T = LookupInObjectType())
356
return T;
357
}
358
359
if (Failed)
360
return nullptr;
361
362
if (IsDependent) {
363
// We didn't find our type, but that's OK: it's dependent anyway.
364
365
// FIXME: What if we have no nested-name-specifier?
366
QualType T =
367
CheckTypenameType(ElaboratedTypeKeyword::None, SourceLocation(),
368
SS.getWithLocInContext(Context), II, NameLoc);
369
return ParsedType::make(T);
370
}
371
372
// The remaining cases are all non-standard extensions imitating the behavior
373
// of various other compilers.
374
unsigned NumNonExtensionDecls = FoundDecls.size();
375
376
if (SS.isSet()) {
377
// For compatibility with older broken C++ rules and existing code,
378
//
379
// nested-name-specifier :: ~ type-name
380
//
381
// also looks for type-name within the nested-name-specifier.
382
if (ParsedType T = LookupInNestedNameSpec(SS)) {
383
Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
384
<< SS.getRange()
385
<< FixItHint::CreateInsertion(SS.getEndLoc(),
386
("::" + II.getName()).str());
387
return T;
388
}
389
390
// For compatibility with other compilers and older versions of Clang,
391
//
392
// nested-name-specifier type-name :: ~ type-name
393
//
394
// also looks for type-name in the scope. Unfortunately, we can't
395
// reasonably apply this fallback for dependent nested-name-specifiers.
396
if (SS.isValid() && SS.getScopeRep()->getPrefix()) {
397
if (ParsedType T = LookupInScope()) {
398
Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
399
<< FixItHint::CreateRemoval(SS.getRange());
400
Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
401
<< GetTypeFromParser(T);
402
return T;
403
}
404
}
405
}
406
407
// We didn't find anything matching; tell the user what we did find (if
408
// anything).
409
410
// Don't tell the user about declarations we shouldn't have found.
411
FoundDecls.resize(NumNonExtensionDecls);
412
413
// List types before non-types.
414
std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
415
[](NamedDecl *A, NamedDecl *B) {
416
return isa<TypeDecl>(A->getUnderlyingDecl()) >
417
isa<TypeDecl>(B->getUnderlyingDecl());
418
});
419
420
// Suggest a fixit to properly name the destroyed type.
421
auto MakeFixItHint = [&]{
422
const CXXRecordDecl *Destroyed = nullptr;
423
// FIXME: If we have a scope specifier, suggest its last component?
424
if (!SearchType.isNull())
425
Destroyed = SearchType->getAsCXXRecordDecl();
426
else if (S)
427
Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
428
if (Destroyed)
429
return FixItHint::CreateReplacement(SourceRange(NameLoc),
430
Destroyed->getNameAsString());
431
return FixItHint();
432
};
433
434
if (FoundDecls.empty()) {
435
// FIXME: Attempt typo-correction?
436
Diag(NameLoc, diag::err_undeclared_destructor_name)
437
<< &II << MakeFixItHint();
438
} else if (!SearchType.isNull() && FoundDecls.size() == 1) {
439
if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
440
assert(!SearchType.isNull() &&
441
"should only reject a type result if we have a search type");
442
QualType T = Context.getTypeDeclType(TD);
443
Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
444
<< T << SearchType << MakeFixItHint();
445
} else {
446
Diag(NameLoc, diag::err_destructor_expr_nontype)
447
<< &II << MakeFixItHint();
448
}
449
} else {
450
Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
451
: diag::err_destructor_expr_mismatch)
452
<< &II << SearchType << MakeFixItHint();
453
}
454
455
for (NamedDecl *FoundD : FoundDecls) {
456
if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
457
Diag(FoundD->getLocation(), diag::note_destructor_type_here)
458
<< Context.getTypeDeclType(TD);
459
else
460
Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
461
<< FoundD;
462
}
463
464
return nullptr;
465
}
466
467
ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
468
ParsedType ObjectType) {
469
if (DS.getTypeSpecType() == DeclSpec::TST_error)
470
return nullptr;
471
472
if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
473
Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
474
return nullptr;
475
}
476
477
assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
478
"unexpected type in getDestructorType");
479
QualType T = BuildDecltypeType(DS.getRepAsExpr());
480
481
// If we know the type of the object, check that the correct destructor
482
// type was named now; we can give better diagnostics this way.
483
QualType SearchType = GetTypeFromParser(ObjectType);
484
if (!SearchType.isNull() && !SearchType->isDependentType() &&
485
!Context.hasSameUnqualifiedType(T, SearchType)) {
486
Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
487
<< T << SearchType;
488
return nullptr;
489
}
490
491
return ParsedType::make(T);
492
}
493
494
bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
495
const UnqualifiedId &Name, bool IsUDSuffix) {
496
assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
497
if (!IsUDSuffix) {
498
// [over.literal] p8
499
//
500
// double operator""_Bq(long double); // OK: not a reserved identifier
501
// double operator"" _Bq(long double); // ill-formed, no diagnostic required
502
const IdentifierInfo *II = Name.Identifier;
503
ReservedIdentifierStatus Status = II->isReserved(PP.getLangOpts());
504
SourceLocation Loc = Name.getEndLoc();
505
if (!PP.getSourceManager().isInSystemHeader(Loc)) {
506
if (auto Hint = FixItHint::CreateReplacement(
507
Name.getSourceRange(),
508
(StringRef("operator\"\"") + II->getName()).str());
509
isReservedInAllContexts(Status)) {
510
Diag(Loc, diag::warn_reserved_extern_symbol)
511
<< II << static_cast<int>(Status) << Hint;
512
} else {
513
Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint;
514
}
515
}
516
}
517
518
if (!SS.isValid())
519
return false;
520
521
switch (SS.getScopeRep()->getKind()) {
522
case NestedNameSpecifier::Identifier:
523
case NestedNameSpecifier::TypeSpec:
524
case NestedNameSpecifier::TypeSpecWithTemplate:
525
// Per C++11 [over.literal]p2, literal operators can only be declared at
526
// namespace scope. Therefore, this unqualified-id cannot name anything.
527
// Reject it early, because we have no AST representation for this in the
528
// case where the scope is dependent.
529
Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
530
<< SS.getScopeRep();
531
return true;
532
533
case NestedNameSpecifier::Global:
534
case NestedNameSpecifier::Super:
535
case NestedNameSpecifier::Namespace:
536
case NestedNameSpecifier::NamespaceAlias:
537
return false;
538
}
539
540
llvm_unreachable("unknown nested name specifier kind");
541
}
542
543
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
544
SourceLocation TypeidLoc,
545
TypeSourceInfo *Operand,
546
SourceLocation RParenLoc) {
547
// C++ [expr.typeid]p4:
548
// The top-level cv-qualifiers of the lvalue expression or the type-id
549
// that is the operand of typeid are always ignored.
550
// If the type of the type-id is a class type or a reference to a class
551
// type, the class shall be completely-defined.
552
Qualifiers Quals;
553
QualType T
554
= Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
555
Quals);
556
if (T->getAs<RecordType>() &&
557
RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
558
return ExprError();
559
560
if (T->isVariablyModifiedType())
561
return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
562
563
if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
564
return ExprError();
565
566
return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
567
SourceRange(TypeidLoc, RParenLoc));
568
}
569
570
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
571
SourceLocation TypeidLoc,
572
Expr *E,
573
SourceLocation RParenLoc) {
574
bool WasEvaluated = false;
575
if (E && !E->isTypeDependent()) {
576
if (E->hasPlaceholderType()) {
577
ExprResult result = CheckPlaceholderExpr(E);
578
if (result.isInvalid()) return ExprError();
579
E = result.get();
580
}
581
582
QualType T = E->getType();
583
if (const RecordType *RecordT = T->getAs<RecordType>()) {
584
CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
585
// C++ [expr.typeid]p3:
586
// [...] If the type of the expression is a class type, the class
587
// shall be completely-defined.
588
if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
589
return ExprError();
590
591
// C++ [expr.typeid]p3:
592
// When typeid is applied to an expression other than an glvalue of a
593
// polymorphic class type [...] [the] expression is an unevaluated
594
// operand. [...]
595
if (RecordD->isPolymorphic() && E->isGLValue()) {
596
if (isUnevaluatedContext()) {
597
// The operand was processed in unevaluated context, switch the
598
// context and recheck the subexpression.
599
ExprResult Result = TransformToPotentiallyEvaluated(E);
600
if (Result.isInvalid())
601
return ExprError();
602
E = Result.get();
603
}
604
605
// We require a vtable to query the type at run time.
606
MarkVTableUsed(TypeidLoc, RecordD);
607
WasEvaluated = true;
608
}
609
}
610
611
ExprResult Result = CheckUnevaluatedOperand(E);
612
if (Result.isInvalid())
613
return ExprError();
614
E = Result.get();
615
616
// C++ [expr.typeid]p4:
617
// [...] If the type of the type-id is a reference to a possibly
618
// cv-qualified type, the result of the typeid expression refers to a
619
// std::type_info object representing the cv-unqualified referenced
620
// type.
621
Qualifiers Quals;
622
QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
623
if (!Context.hasSameType(T, UnqualT)) {
624
T = UnqualT;
625
E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
626
}
627
}
628
629
if (E->getType()->isVariablyModifiedType())
630
return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
631
<< E->getType());
632
else if (!inTemplateInstantiation() &&
633
E->HasSideEffects(Context, WasEvaluated)) {
634
// The expression operand for typeid is in an unevaluated expression
635
// context, so side effects could result in unintended consequences.
636
Diag(E->getExprLoc(), WasEvaluated
637
? diag::warn_side_effects_typeid
638
: diag::warn_side_effects_unevaluated_context);
639
}
640
641
return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
642
SourceRange(TypeidLoc, RParenLoc));
643
}
644
645
/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
646
ExprResult
647
Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
648
bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
649
// typeid is not supported in OpenCL.
650
if (getLangOpts().OpenCLCPlusPlus) {
651
return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
652
<< "typeid");
653
}
654
655
// Find the std::type_info type.
656
if (!getStdNamespace())
657
return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
658
659
if (!CXXTypeInfoDecl) {
660
IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
661
LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
662
LookupQualifiedName(R, getStdNamespace());
663
CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
664
// Microsoft's typeinfo doesn't have type_info in std but in the global
665
// namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
666
if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
667
LookupQualifiedName(R, Context.getTranslationUnitDecl());
668
CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
669
}
670
if (!CXXTypeInfoDecl)
671
return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
672
}
673
674
if (!getLangOpts().RTTI) {
675
return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
676
}
677
678
QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
679
680
if (isType) {
681
// The operand is a type; handle it as such.
682
TypeSourceInfo *TInfo = nullptr;
683
QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
684
&TInfo);
685
if (T.isNull())
686
return ExprError();
687
688
if (!TInfo)
689
TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
690
691
return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
692
}
693
694
// The operand is an expression.
695
ExprResult Result =
696
BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
697
698
if (!getLangOpts().RTTIData && !Result.isInvalid())
699
if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
700
if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
701
Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
702
<< (getDiagnostics().getDiagnosticOptions().getFormat() ==
703
DiagnosticOptions::MSVC);
704
return Result;
705
}
706
707
/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
708
/// a single GUID.
709
static void
710
getUuidAttrOfType(Sema &SemaRef, QualType QT,
711
llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
712
// Optionally remove one level of pointer, reference or array indirection.
713
const Type *Ty = QT.getTypePtr();
714
if (QT->isPointerType() || QT->isReferenceType())
715
Ty = QT->getPointeeType().getTypePtr();
716
else if (QT->isArrayType())
717
Ty = Ty->getBaseElementTypeUnsafe();
718
719
const auto *TD = Ty->getAsTagDecl();
720
if (!TD)
721
return;
722
723
if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
724
UuidAttrs.insert(Uuid);
725
return;
726
}
727
728
// __uuidof can grab UUIDs from template arguments.
729
if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
730
const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
731
for (const TemplateArgument &TA : TAL.asArray()) {
732
const UuidAttr *UuidForTA = nullptr;
733
if (TA.getKind() == TemplateArgument::Type)
734
getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
735
else if (TA.getKind() == TemplateArgument::Declaration)
736
getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
737
738
if (UuidForTA)
739
UuidAttrs.insert(UuidForTA);
740
}
741
}
742
}
743
744
ExprResult Sema::BuildCXXUuidof(QualType Type,
745
SourceLocation TypeidLoc,
746
TypeSourceInfo *Operand,
747
SourceLocation RParenLoc) {
748
MSGuidDecl *Guid = nullptr;
749
if (!Operand->getType()->isDependentType()) {
750
llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
751
getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
752
if (UuidAttrs.empty())
753
return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
754
if (UuidAttrs.size() > 1)
755
return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
756
Guid = UuidAttrs.back()->getGuidDecl();
757
}
758
759
return new (Context)
760
CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
761
}
762
763
ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc,
764
Expr *E, SourceLocation RParenLoc) {
765
MSGuidDecl *Guid = nullptr;
766
if (!E->getType()->isDependentType()) {
767
if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
768
// A null pointer results in {00000000-0000-0000-0000-000000000000}.
769
Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{});
770
} else {
771
llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
772
getUuidAttrOfType(*this, E->getType(), UuidAttrs);
773
if (UuidAttrs.empty())
774
return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
775
if (UuidAttrs.size() > 1)
776
return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
777
Guid = UuidAttrs.back()->getGuidDecl();
778
}
779
}
780
781
return new (Context)
782
CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
783
}
784
785
/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
786
ExprResult
787
Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
788
bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
789
QualType GuidType = Context.getMSGuidType();
790
GuidType.addConst();
791
792
if (isType) {
793
// The operand is a type; handle it as such.
794
TypeSourceInfo *TInfo = nullptr;
795
QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
796
&TInfo);
797
if (T.isNull())
798
return ExprError();
799
800
if (!TInfo)
801
TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
802
803
return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
804
}
805
806
// The operand is an expression.
807
return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
808
}
809
810
ExprResult
811
Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
812
assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
813
"Unknown C++ Boolean value!");
814
return new (Context)
815
CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
816
}
817
818
ExprResult
819
Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
820
return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
821
}
822
823
ExprResult
824
Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
825
bool IsThrownVarInScope = false;
826
if (Ex) {
827
// C++0x [class.copymove]p31:
828
// When certain criteria are met, an implementation is allowed to omit the
829
// copy/move construction of a class object [...]
830
//
831
// - in a throw-expression, when the operand is the name of a
832
// non-volatile automatic object (other than a function or catch-
833
// clause parameter) whose scope does not extend beyond the end of the
834
// innermost enclosing try-block (if there is one), the copy/move
835
// operation from the operand to the exception object (15.1) can be
836
// omitted by constructing the automatic object directly into the
837
// exception object
838
if (const auto *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
839
if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl());
840
Var && Var->hasLocalStorage() &&
841
!Var->getType().isVolatileQualified()) {
842
for (; S; S = S->getParent()) {
843
if (S->isDeclScope(Var)) {
844
IsThrownVarInScope = true;
845
break;
846
}
847
848
// FIXME: Many of the scope checks here seem incorrect.
849
if (S->getFlags() &
850
(Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
851
Scope::ObjCMethodScope | Scope::TryScope))
852
break;
853
}
854
}
855
}
856
857
return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
858
}
859
860
ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
861
bool IsThrownVarInScope) {
862
const llvm::Triple &T = Context.getTargetInfo().getTriple();
863
const bool IsOpenMPGPUTarget =
864
getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());
865
// Don't report an error if 'throw' is used in system headers or in an OpenMP
866
// target region compiled for a GPU architecture.
867
if (!IsOpenMPGPUTarget && !getLangOpts().CXXExceptions &&
868
!getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
869
// Delay error emission for the OpenMP device code.
870
targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
871
}
872
873
// In OpenMP target regions, we replace 'throw' with a trap on GPU targets.
874
if (IsOpenMPGPUTarget)
875
targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str();
876
877
// Exceptions aren't allowed in CUDA device code.
878
if (getLangOpts().CUDA)
879
CUDA().DiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
880
<< "throw" << llvm::to_underlying(CUDA().CurrentTarget());
881
882
if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
883
Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
884
885
// Exceptions that escape a compute construct are ill-formed.
886
if (getLangOpts().OpenACC && getCurScope() &&
887
getCurScope()->isInOpenACCComputeConstructScope(Scope::TryScope))
888
Diag(OpLoc, diag::err_acc_branch_in_out_compute_construct)
889
<< /*throw*/ 2 << /*out of*/ 0;
890
891
if (Ex && !Ex->isTypeDependent()) {
892
// Initialize the exception result. This implicitly weeds out
893
// abstract types or types with inaccessible copy constructors.
894
895
// C++0x [class.copymove]p31:
896
// When certain criteria are met, an implementation is allowed to omit the
897
// copy/move construction of a class object [...]
898
//
899
// - in a throw-expression, when the operand is the name of a
900
// non-volatile automatic object (other than a function or
901
// catch-clause
902
// parameter) whose scope does not extend beyond the end of the
903
// innermost enclosing try-block (if there is one), the copy/move
904
// operation from the operand to the exception object (15.1) can be
905
// omitted by constructing the automatic object directly into the
906
// exception object
907
NamedReturnInfo NRInfo =
908
IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
909
910
QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
911
if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
912
return ExprError();
913
914
InitializedEntity Entity =
915
InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);
916
ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
917
if (Res.isInvalid())
918
return ExprError();
919
Ex = Res.get();
920
}
921
922
// PPC MMA non-pointer types are not allowed as throw expr types.
923
if (Ex && Context.getTargetInfo().getTriple().isPPC64())
924
PPC().CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
925
926
return new (Context)
927
CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
928
}
929
930
static void
931
collectPublicBases(CXXRecordDecl *RD,
932
llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
933
llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
934
llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
935
bool ParentIsPublic) {
936
for (const CXXBaseSpecifier &BS : RD->bases()) {
937
CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
938
bool NewSubobject;
939
// Virtual bases constitute the same subobject. Non-virtual bases are
940
// always distinct subobjects.
941
if (BS.isVirtual())
942
NewSubobject = VBases.insert(BaseDecl).second;
943
else
944
NewSubobject = true;
945
946
if (NewSubobject)
947
++SubobjectsSeen[BaseDecl];
948
949
// Only add subobjects which have public access throughout the entire chain.
950
bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
951
if (PublicPath)
952
PublicSubobjectsSeen.insert(BaseDecl);
953
954
// Recurse on to each base subobject.
955
collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
956
PublicPath);
957
}
958
}
959
960
static void getUnambiguousPublicSubobjects(
961
CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
962
llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
963
llvm::SmallSet<CXXRecordDecl *, 2> VBases;
964
llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
965
SubobjectsSeen[RD] = 1;
966
PublicSubobjectsSeen.insert(RD);
967
collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
968
/*ParentIsPublic=*/true);
969
970
for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
971
// Skip ambiguous objects.
972
if (SubobjectsSeen[PublicSubobject] > 1)
973
continue;
974
975
Objects.push_back(PublicSubobject);
976
}
977
}
978
979
bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
980
QualType ExceptionObjectTy, Expr *E) {
981
// If the type of the exception would be an incomplete type or a pointer
982
// to an incomplete type other than (cv) void the program is ill-formed.
983
QualType Ty = ExceptionObjectTy;
984
bool isPointer = false;
985
if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
986
Ty = Ptr->getPointeeType();
987
isPointer = true;
988
}
989
990
// Cannot throw WebAssembly reference type.
991
if (Ty.isWebAssemblyReferenceType()) {
992
Diag(ThrowLoc, diag::err_wasm_reftype_tc) << 0 << E->getSourceRange();
993
return true;
994
}
995
996
// Cannot throw WebAssembly table.
997
if (isPointer && Ty.isWebAssemblyReferenceType()) {
998
Diag(ThrowLoc, diag::err_wasm_table_art) << 2 << E->getSourceRange();
999
return true;
1000
}
1001
1002
if (!isPointer || !Ty->isVoidType()) {
1003
if (RequireCompleteType(ThrowLoc, Ty,
1004
isPointer ? diag::err_throw_incomplete_ptr
1005
: diag::err_throw_incomplete,
1006
E->getSourceRange()))
1007
return true;
1008
1009
if (!isPointer && Ty->isSizelessType()) {
1010
Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
1011
return true;
1012
}
1013
1014
if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
1015
diag::err_throw_abstract_type, E))
1016
return true;
1017
}
1018
1019
// If the exception has class type, we need additional handling.
1020
CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1021
if (!RD)
1022
return false;
1023
1024
// If we are throwing a polymorphic class type or pointer thereof,
1025
// exception handling will make use of the vtable.
1026
MarkVTableUsed(ThrowLoc, RD);
1027
1028
// If a pointer is thrown, the referenced object will not be destroyed.
1029
if (isPointer)
1030
return false;
1031
1032
// If the class has a destructor, we must be able to call it.
1033
if (!RD->hasIrrelevantDestructor()) {
1034
if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
1035
MarkFunctionReferenced(E->getExprLoc(), Destructor);
1036
CheckDestructorAccess(E->getExprLoc(), Destructor,
1037
PDiag(diag::err_access_dtor_exception) << Ty);
1038
if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
1039
return true;
1040
}
1041
}
1042
1043
// The MSVC ABI creates a list of all types which can catch the exception
1044
// object. This list also references the appropriate copy constructor to call
1045
// if the object is caught by value and has a non-trivial copy constructor.
1046
if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1047
// We are only interested in the public, unambiguous bases contained within
1048
// the exception object. Bases which are ambiguous or otherwise
1049
// inaccessible are not catchable types.
1050
llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1051
getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1052
1053
for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1054
// Attempt to lookup the copy constructor. Various pieces of machinery
1055
// will spring into action, like template instantiation, which means this
1056
// cannot be a simple walk of the class's decls. Instead, we must perform
1057
// lookup and overload resolution.
1058
CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1059
if (!CD || CD->isDeleted())
1060
continue;
1061
1062
// Mark the constructor referenced as it is used by this throw expression.
1063
MarkFunctionReferenced(E->getExprLoc(), CD);
1064
1065
// Skip this copy constructor if it is trivial, we don't need to record it
1066
// in the catchable type data.
1067
if (CD->isTrivial())
1068
continue;
1069
1070
// The copy constructor is non-trivial, create a mapping from this class
1071
// type to this constructor.
1072
// N.B. The selection of copy constructor is not sensitive to this
1073
// particular throw-site. Lookup will be performed at the catch-site to
1074
// ensure that the copy constructor is, in fact, accessible (via
1075
// friendship or any other means).
1076
Context.addCopyConstructorForExceptionObject(Subobject, CD);
1077
1078
// We don't keep the instantiated default argument expressions around so
1079
// we must rebuild them here.
1080
for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1081
if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1082
return true;
1083
}
1084
}
1085
}
1086
1087
// Under the Itanium C++ ABI, memory for the exception object is allocated by
1088
// the runtime with no ability for the compiler to request additional
1089
// alignment. Warn if the exception type requires alignment beyond the minimum
1090
// guaranteed by the target C++ runtime.
1091
if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
1092
CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1093
CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1094
if (ExnObjAlign < TypeAlign) {
1095
Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1096
Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1097
<< Ty << (unsigned)TypeAlign.getQuantity()
1098
<< (unsigned)ExnObjAlign.getQuantity();
1099
}
1100
}
1101
if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) {
1102
if (CXXDestructorDecl *Dtor = RD->getDestructor()) {
1103
auto Ty = Dtor->getType();
1104
if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) {
1105
if (!isUnresolvedExceptionSpec(FT->getExceptionSpecType()) &&
1106
!FT->isNothrow())
1107
Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD;
1108
}
1109
}
1110
}
1111
1112
return false;
1113
}
1114
1115
static QualType adjustCVQualifiersForCXXThisWithinLambda(
1116
ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1117
DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1118
1119
QualType ClassType = ThisTy->getPointeeType();
1120
LambdaScopeInfo *CurLSI = nullptr;
1121
DeclContext *CurDC = CurSemaContext;
1122
1123
// Iterate through the stack of lambdas starting from the innermost lambda to
1124
// the outermost lambda, checking if '*this' is ever captured by copy - since
1125
// that could change the cv-qualifiers of the '*this' object.
1126
// The object referred to by '*this' starts out with the cv-qualifiers of its
1127
// member function. We then start with the innermost lambda and iterate
1128
// outward checking to see if any lambda performs a by-copy capture of '*this'
1129
// - and if so, any nested lambda must respect the 'constness' of that
1130
// capturing lamdbda's call operator.
1131
//
1132
1133
// Since the FunctionScopeInfo stack is representative of the lexical
1134
// nesting of the lambda expressions during initial parsing (and is the best
1135
// place for querying information about captures about lambdas that are
1136
// partially processed) and perhaps during instantiation of function templates
1137
// that contain lambda expressions that need to be transformed BUT not
1138
// necessarily during instantiation of a nested generic lambda's function call
1139
// operator (which might even be instantiated at the end of the TU) - at which
1140
// time the DeclContext tree is mature enough to query capture information
1141
// reliably - we use a two pronged approach to walk through all the lexically
1142
// enclosing lambda expressions:
1143
//
1144
// 1) Climb down the FunctionScopeInfo stack as long as each item represents
1145
// a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1146
// enclosed by the call-operator of the LSI below it on the stack (while
1147
// tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1148
// the stack represents the innermost lambda.
1149
//
1150
// 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1151
// represents a lambda's call operator. If it does, we must be instantiating
1152
// a generic lambda's call operator (represented by the Current LSI, and
1153
// should be the only scenario where an inconsistency between the LSI and the
1154
// DeclContext should occur), so climb out the DeclContexts if they
1155
// represent lambdas, while querying the corresponding closure types
1156
// regarding capture information.
1157
1158
// 1) Climb down the function scope info stack.
1159
for (int I = FunctionScopes.size();
1160
I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1161
(!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1162
cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1163
CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1164
CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1165
1166
if (!CurLSI->isCXXThisCaptured())
1167
continue;
1168
1169
auto C = CurLSI->getCXXThisCapture();
1170
1171
if (C.isCopyCapture()) {
1172
if (CurLSI->lambdaCaptureShouldBeConst())
1173
ClassType.addConst();
1174
return ASTCtx.getPointerType(ClassType);
1175
}
1176
}
1177
1178
// 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1179
// can happen during instantiation of its nested generic lambda call
1180
// operator); 2. if we're in a lambda scope (lambda body).
1181
if (CurLSI && isLambdaCallOperator(CurDC)) {
1182
assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1183
"While computing 'this' capture-type for a generic lambda, when we "
1184
"run out of enclosing LSI's, yet the enclosing DC is a "
1185
"lambda-call-operator we must be (i.e. Current LSI) in a generic "
1186
"lambda call oeprator");
1187
assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1188
1189
auto IsThisCaptured =
1190
[](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1191
IsConst = false;
1192
IsByCopy = false;
1193
for (auto &&C : Closure->captures()) {
1194
if (C.capturesThis()) {
1195
if (C.getCaptureKind() == LCK_StarThis)
1196
IsByCopy = true;
1197
if (Closure->getLambdaCallOperator()->isConst())
1198
IsConst = true;
1199
return true;
1200
}
1201
}
1202
return false;
1203
};
1204
1205
bool IsByCopyCapture = false;
1206
bool IsConstCapture = false;
1207
CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1208
while (Closure &&
1209
IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1210
if (IsByCopyCapture) {
1211
if (IsConstCapture)
1212
ClassType.addConst();
1213
return ASTCtx.getPointerType(ClassType);
1214
}
1215
Closure = isLambdaCallOperator(Closure->getParent())
1216
? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1217
: nullptr;
1218
}
1219
}
1220
return ThisTy;
1221
}
1222
1223
QualType Sema::getCurrentThisType() {
1224
DeclContext *DC = getFunctionLevelDeclContext();
1225
QualType ThisTy = CXXThisTypeOverride;
1226
1227
if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1228
if (method && method->isImplicitObjectMemberFunction())
1229
ThisTy = method->getThisType().getNonReferenceType();
1230
}
1231
1232
if (ThisTy.isNull() && isLambdaCallWithImplicitObjectParameter(CurContext) &&
1233
inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {
1234
1235
// This is a lambda call operator that is being instantiated as a default
1236
// initializer. DC must point to the enclosing class type, so we can recover
1237
// the 'this' type from it.
1238
QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1239
// There are no cv-qualifiers for 'this' within default initializers,
1240
// per [expr.prim.general]p4.
1241
ThisTy = Context.getPointerType(ClassTy);
1242
}
1243
1244
// If we are within a lambda's call operator, the cv-qualifiers of 'this'
1245
// might need to be adjusted if the lambda or any of its enclosing lambda's
1246
// captures '*this' by copy.
1247
if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1248
return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1249
CurContext, Context);
1250
return ThisTy;
1251
}
1252
1253
Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1254
Decl *ContextDecl,
1255
Qualifiers CXXThisTypeQuals,
1256
bool Enabled)
1257
: S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1258
{
1259
if (!Enabled || !ContextDecl)
1260
return;
1261
1262
CXXRecordDecl *Record = nullptr;
1263
if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1264
Record = Template->getTemplatedDecl();
1265
else
1266
Record = cast<CXXRecordDecl>(ContextDecl);
1267
1268
QualType T = S.Context.getRecordType(Record);
1269
T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1270
1271
S.CXXThisTypeOverride =
1272
S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T);
1273
1274
this->Enabled = true;
1275
}
1276
1277
1278
Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1279
if (Enabled) {
1280
S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1281
}
1282
}
1283
1284
static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) {
1285
SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
1286
assert(!LSI->isCXXThisCaptured());
1287
// [=, this] {}; // until C++20: Error: this when = is the default
1288
if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval &&
1289
!Sema.getLangOpts().CPlusPlus20)
1290
return;
1291
Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1292
<< FixItHint::CreateInsertion(
1293
DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1294
}
1295
1296
bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1297
bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1298
const bool ByCopy) {
1299
// We don't need to capture this in an unevaluated context.
1300
if (isUnevaluatedContext() && !Explicit)
1301
return true;
1302
1303
assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1304
1305
const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1306
? *FunctionScopeIndexToStopAt
1307
: FunctionScopes.size() - 1;
1308
1309
// Check that we can capture the *enclosing object* (referred to by '*this')
1310
// by the capturing-entity/closure (lambda/block/etc) at
1311
// MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1312
1313
// Note: The *enclosing object* can only be captured by-value by a
1314
// closure that is a lambda, using the explicit notation:
1315
// [*this] { ... }.
1316
// Every other capture of the *enclosing object* results in its by-reference
1317
// capture.
1318
1319
// For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1320
// stack), we can capture the *enclosing object* only if:
1321
// - 'L' has an explicit byref or byval capture of the *enclosing object*
1322
// - or, 'L' has an implicit capture.
1323
// AND
1324
// -- there is no enclosing closure
1325
// -- or, there is some enclosing closure 'E' that has already captured the
1326
// *enclosing object*, and every intervening closure (if any) between 'E'
1327
// and 'L' can implicitly capture the *enclosing object*.
1328
// -- or, every enclosing closure can implicitly capture the
1329
// *enclosing object*
1330
1331
1332
unsigned NumCapturingClosures = 0;
1333
for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1334
if (CapturingScopeInfo *CSI =
1335
dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1336
if (CSI->CXXThisCaptureIndex != 0) {
1337
// 'this' is already being captured; there isn't anything more to do.
1338
CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1339
break;
1340
}
1341
LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1342
if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1343
// This context can't implicitly capture 'this'; fail out.
1344
if (BuildAndDiagnose) {
1345
LSI->CallOperator->setInvalidDecl();
1346
Diag(Loc, diag::err_this_capture)
1347
<< (Explicit && idx == MaxFunctionScopesIndex);
1348
if (!Explicit)
1349
buildLambdaThisCaptureFixit(*this, LSI);
1350
}
1351
return true;
1352
}
1353
if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1354
CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1355
CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1356
CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1357
(Explicit && idx == MaxFunctionScopesIndex)) {
1358
// Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1359
// iteration through can be an explicit capture, all enclosing closures,
1360
// if any, must perform implicit captures.
1361
1362
// This closure can capture 'this'; continue looking upwards.
1363
NumCapturingClosures++;
1364
continue;
1365
}
1366
// This context can't implicitly capture 'this'; fail out.
1367
if (BuildAndDiagnose) {
1368
LSI->CallOperator->setInvalidDecl();
1369
Diag(Loc, diag::err_this_capture)
1370
<< (Explicit && idx == MaxFunctionScopesIndex);
1371
}
1372
if (!Explicit)
1373
buildLambdaThisCaptureFixit(*this, LSI);
1374
return true;
1375
}
1376
break;
1377
}
1378
if (!BuildAndDiagnose) return false;
1379
1380
// If we got here, then the closure at MaxFunctionScopesIndex on the
1381
// FunctionScopes stack, can capture the *enclosing object*, so capture it
1382
// (including implicit by-reference captures in any enclosing closures).
1383
1384
// In the loop below, respect the ByCopy flag only for the closure requesting
1385
// the capture (i.e. first iteration through the loop below). Ignore it for
1386
// all enclosing closure's up to NumCapturingClosures (since they must be
1387
// implicitly capturing the *enclosing object* by reference (see loop
1388
// above)).
1389
assert((!ByCopy ||
1390
isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1391
"Only a lambda can capture the enclosing object (referred to by "
1392
"*this) by copy");
1393
QualType ThisTy = getCurrentThisType();
1394
for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1395
--idx, --NumCapturingClosures) {
1396
CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1397
1398
// The type of the corresponding data member (not a 'this' pointer if 'by
1399
// copy').
1400
QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy;
1401
1402
bool isNested = NumCapturingClosures > 1;
1403
CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1404
}
1405
return false;
1406
}
1407
1408
ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1409
// C++20 [expr.prim.this]p1:
1410
// The keyword this names a pointer to the object for which an
1411
// implicit object member function is invoked or a non-static
1412
// data member's initializer is evaluated.
1413
QualType ThisTy = getCurrentThisType();
1414
1415
if (CheckCXXThisType(Loc, ThisTy))
1416
return ExprError();
1417
1418
return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1419
}
1420
1421
bool Sema::CheckCXXThisType(SourceLocation Loc, QualType Type) {
1422
if (!Type.isNull())
1423
return false;
1424
1425
// C++20 [expr.prim.this]p3:
1426
// If a declaration declares a member function or member function template
1427
// of a class X, the expression this is a prvalue of type
1428
// "pointer to cv-qualifier-seq X" wherever X is the current class between
1429
// the optional cv-qualifier-seq and the end of the function-definition,
1430
// member-declarator, or declarator. It shall not appear within the
1431
// declaration of either a static member function or an explicit object
1432
// member function of the current class (although its type and value
1433
// category are defined within such member functions as they are within
1434
// an implicit object member function).
1435
DeclContext *DC = getFunctionLevelDeclContext();
1436
const auto *Method = dyn_cast<CXXMethodDecl>(DC);
1437
if (Method && Method->isExplicitObjectMemberFunction()) {
1438
Diag(Loc, diag::err_invalid_this_use) << 1;
1439
} else if (Method && isLambdaCallWithExplicitObjectParameter(CurContext)) {
1440
Diag(Loc, diag::err_invalid_this_use) << 1;
1441
} else {
1442
Diag(Loc, diag::err_invalid_this_use) << 0;
1443
}
1444
return true;
1445
}
1446
1447
Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
1448
bool IsImplicit) {
1449
auto *This = CXXThisExpr::Create(Context, Loc, Type, IsImplicit);
1450
MarkThisReferenced(This);
1451
return This;
1452
}
1453
1454
void Sema::MarkThisReferenced(CXXThisExpr *This) {
1455
CheckCXXThisCapture(This->getExprLoc());
1456
if (This->isTypeDependent())
1457
return;
1458
1459
// Check if 'this' is captured by value in a lambda with a dependent explicit
1460
// object parameter, and mark it as type-dependent as well if so.
1461
auto IsDependent = [&]() {
1462
for (auto *Scope : llvm::reverse(FunctionScopes)) {
1463
auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
1464
if (!LSI)
1465
continue;
1466
1467
if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&
1468
LSI->AfterParameterList)
1469
return false;
1470
1471
// If this lambda captures 'this' by value, then 'this' is dependent iff
1472
// this lambda has a dependent explicit object parameter. If we can't
1473
// determine whether it does (e.g. because the CXXMethodDecl's type is
1474
// null), assume it doesn't.
1475
if (LSI->isCXXThisCaptured()) {
1476
if (!LSI->getCXXThisCapture().isCopyCapture())
1477
continue;
1478
1479
const auto *MD = LSI->CallOperator;
1480
if (MD->getType().isNull())
1481
return false;
1482
1483
const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
1484
return Ty && MD->isExplicitObjectMemberFunction() &&
1485
Ty->getParamType(0)->isDependentType();
1486
}
1487
}
1488
return false;
1489
}();
1490
1491
This->setCapturedByCopyInLambdaWithExplicitObjectParameter(IsDependent);
1492
}
1493
1494
bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1495
// If we're outside the body of a member function, then we'll have a specified
1496
// type for 'this'.
1497
if (CXXThisTypeOverride.isNull())
1498
return false;
1499
1500
// Determine whether we're looking into a class that's currently being
1501
// defined.
1502
CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1503
return Class && Class->isBeingDefined();
1504
}
1505
1506
ExprResult
1507
Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1508
SourceLocation LParenOrBraceLoc,
1509
MultiExprArg exprs,
1510
SourceLocation RParenOrBraceLoc,
1511
bool ListInitialization) {
1512
if (!TypeRep)
1513
return ExprError();
1514
1515
TypeSourceInfo *TInfo;
1516
QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1517
if (!TInfo)
1518
TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1519
1520
auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1521
RParenOrBraceLoc, ListInitialization);
1522
// Avoid creating a non-type-dependent expression that contains typos.
1523
// Non-type-dependent expressions are liable to be discarded without
1524
// checking for embedded typos.
1525
if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1526
!Result.get()->isTypeDependent())
1527
Result = CorrectDelayedTyposInExpr(Result.get());
1528
else if (Result.isInvalid())
1529
Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(),
1530
RParenOrBraceLoc, exprs, Ty);
1531
return Result;
1532
}
1533
1534
ExprResult
1535
Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1536
SourceLocation LParenOrBraceLoc,
1537
MultiExprArg Exprs,
1538
SourceLocation RParenOrBraceLoc,
1539
bool ListInitialization) {
1540
QualType Ty = TInfo->getType();
1541
SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1542
1543
assert((!ListInitialization || Exprs.size() == 1) &&
1544
"List initialization must have exactly one expression.");
1545
SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1546
1547
InitializedEntity Entity =
1548
InitializedEntity::InitializeTemporary(Context, TInfo);
1549
InitializationKind Kind =
1550
Exprs.size()
1551
? ListInitialization
1552
? InitializationKind::CreateDirectList(
1553
TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1554
: InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1555
RParenOrBraceLoc)
1556
: InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1557
RParenOrBraceLoc);
1558
1559
// C++17 [expr.type.conv]p1:
1560
// If the type is a placeholder for a deduced class type, [...perform class
1561
// template argument deduction...]
1562
// C++23:
1563
// Otherwise, if the type contains a placeholder type, it is replaced by the
1564
// type determined by placeholder type deduction.
1565
DeducedType *Deduced = Ty->getContainedDeducedType();
1566
if (Deduced && !Deduced->isDeduced() &&
1567
isa<DeducedTemplateSpecializationType>(Deduced)) {
1568
Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1569
Kind, Exprs);
1570
if (Ty.isNull())
1571
return ExprError();
1572
Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1573
} else if (Deduced && !Deduced->isDeduced()) {
1574
MultiExprArg Inits = Exprs;
1575
if (ListInitialization) {
1576
auto *ILE = cast<InitListExpr>(Exprs[0]);
1577
Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
1578
}
1579
1580
if (Inits.empty())
1581
return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)
1582
<< Ty << FullRange);
1583
if (Inits.size() > 1) {
1584
Expr *FirstBad = Inits[1];
1585
return ExprError(Diag(FirstBad->getBeginLoc(),
1586
diag::err_auto_expr_init_multiple_expressions)
1587
<< Ty << FullRange);
1588
}
1589
if (getLangOpts().CPlusPlus23) {
1590
if (Ty->getAs<AutoType>())
1591
Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;
1592
}
1593
Expr *Deduce = Inits[0];
1594
if (isa<InitListExpr>(Deduce))
1595
return ExprError(
1596
Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
1597
<< ListInitialization << Ty << FullRange);
1598
QualType DeducedType;
1599
TemplateDeductionInfo Info(Deduce->getExprLoc());
1600
TemplateDeductionResult Result =
1601
DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info);
1602
if (Result != TemplateDeductionResult::Success &&
1603
Result != TemplateDeductionResult::AlreadyDiagnosed)
1604
return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)
1605
<< Ty << Deduce->getType() << FullRange
1606
<< Deduce->getSourceRange());
1607
if (DeducedType.isNull()) {
1608
assert(Result == TemplateDeductionResult::AlreadyDiagnosed);
1609
return ExprError();
1610
}
1611
1612
Ty = DeducedType;
1613
Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1614
}
1615
1616
if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs))
1617
return CXXUnresolvedConstructExpr::Create(
1618
Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs,
1619
RParenOrBraceLoc, ListInitialization);
1620
1621
// C++ [expr.type.conv]p1:
1622
// If the expression list is a parenthesized single expression, the type
1623
// conversion expression is equivalent (in definedness, and if defined in
1624
// meaning) to the corresponding cast expression.
1625
if (Exprs.size() == 1 && !ListInitialization &&
1626
!isa<InitListExpr>(Exprs[0])) {
1627
Expr *Arg = Exprs[0];
1628
return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1629
RParenOrBraceLoc);
1630
}
1631
1632
// For an expression of the form T(), T shall not be an array type.
1633
QualType ElemTy = Ty;
1634
if (Ty->isArrayType()) {
1635
if (!ListInitialization)
1636
return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1637
<< FullRange);
1638
ElemTy = Context.getBaseElementType(Ty);
1639
}
1640
1641
// Only construct objects with object types.
1642
// The standard doesn't explicitly forbid function types here, but that's an
1643
// obvious oversight, as there's no way to dynamically construct a function
1644
// in general.
1645
if (Ty->isFunctionType())
1646
return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1647
<< Ty << FullRange);
1648
1649
// C++17 [expr.type.conv]p2:
1650
// If the type is cv void and the initializer is (), the expression is a
1651
// prvalue of the specified type that performs no initialization.
1652
if (!Ty->isVoidType() &&
1653
RequireCompleteType(TyBeginLoc, ElemTy,
1654
diag::err_invalid_incomplete_type_use, FullRange))
1655
return ExprError();
1656
1657
// Otherwise, the expression is a prvalue of the specified type whose
1658
// result object is direct-initialized (11.6) with the initializer.
1659
InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1660
ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1661
1662
if (Result.isInvalid())
1663
return Result;
1664
1665
Expr *Inner = Result.get();
1666
if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1667
Inner = BTE->getSubExpr();
1668
if (auto *CE = dyn_cast<ConstantExpr>(Inner);
1669
CE && CE->isImmediateInvocation())
1670
Inner = CE->getSubExpr();
1671
if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1672
!isa<CXXScalarValueInitExpr>(Inner)) {
1673
// If we created a CXXTemporaryObjectExpr, that node also represents the
1674
// functional cast. Otherwise, create an explicit cast to represent
1675
// the syntactic form of a functional-style cast that was used here.
1676
//
1677
// FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1678
// would give a more consistent AST representation than using a
1679
// CXXTemporaryObjectExpr. It's also weird that the functional cast
1680
// is sometimes handled by initialization and sometimes not.
1681
QualType ResultType = Result.get()->getType();
1682
SourceRange Locs = ListInitialization
1683
? SourceRange()
1684
: SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1685
Result = CXXFunctionalCastExpr::Create(
1686
Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1687
Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1688
Locs.getBegin(), Locs.getEnd());
1689
}
1690
1691
return Result;
1692
}
1693
1694
bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1695
// [CUDA] Ignore this function, if we can't call it.
1696
const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1697
if (getLangOpts().CUDA) {
1698
auto CallPreference = CUDA().IdentifyPreference(Caller, Method);
1699
// If it's not callable at all, it's not the right function.
1700
if (CallPreference < SemaCUDA::CFP_WrongSide)
1701
return false;
1702
if (CallPreference == SemaCUDA::CFP_WrongSide) {
1703
// Maybe. We have to check if there are better alternatives.
1704
DeclContext::lookup_result R =
1705
Method->getDeclContext()->lookup(Method->getDeclName());
1706
for (const auto *D : R) {
1707
if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1708
if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide)
1709
return false;
1710
}
1711
}
1712
// We've found no better variants.
1713
}
1714
}
1715
1716
SmallVector<const FunctionDecl*, 4> PreventedBy;
1717
bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1718
1719
if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1720
return Result;
1721
1722
// In case of CUDA, return true if none of the 1-argument deallocator
1723
// functions are actually callable.
1724
return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1725
assert(FD->getNumParams() == 1 &&
1726
"Only single-operand functions should be in PreventedBy");
1727
return CUDA().IdentifyPreference(Caller, FD) >= SemaCUDA::CFP_HostDevice;
1728
});
1729
}
1730
1731
/// Determine whether the given function is a non-placement
1732
/// deallocation function.
1733
static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1734
if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1735
return S.isUsualDeallocationFunction(Method);
1736
1737
if (FD->getOverloadedOperator() != OO_Delete &&
1738
FD->getOverloadedOperator() != OO_Array_Delete)
1739
return false;
1740
1741
unsigned UsualParams = 1;
1742
1743
if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1744
S.Context.hasSameUnqualifiedType(
1745
FD->getParamDecl(UsualParams)->getType(),
1746
S.Context.getSizeType()))
1747
++UsualParams;
1748
1749
if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1750
S.Context.hasSameUnqualifiedType(
1751
FD->getParamDecl(UsualParams)->getType(),
1752
S.Context.getTypeDeclType(S.getStdAlignValT())))
1753
++UsualParams;
1754
1755
return UsualParams == FD->getNumParams();
1756
}
1757
1758
namespace {
1759
struct UsualDeallocFnInfo {
1760
UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1761
UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1762
: Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1763
Destroying(false), HasSizeT(false), HasAlignValT(false),
1764
CUDAPref(SemaCUDA::CFP_Native) {
1765
// A function template declaration is never a usual deallocation function.
1766
if (!FD)
1767
return;
1768
unsigned NumBaseParams = 1;
1769
if (FD->isDestroyingOperatorDelete()) {
1770
Destroying = true;
1771
++NumBaseParams;
1772
}
1773
1774
if (NumBaseParams < FD->getNumParams() &&
1775
S.Context.hasSameUnqualifiedType(
1776
FD->getParamDecl(NumBaseParams)->getType(),
1777
S.Context.getSizeType())) {
1778
++NumBaseParams;
1779
HasSizeT = true;
1780
}
1781
1782
if (NumBaseParams < FD->getNumParams() &&
1783
FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1784
++NumBaseParams;
1785
HasAlignValT = true;
1786
}
1787
1788
// In CUDA, determine how much we'd like / dislike to call this.
1789
if (S.getLangOpts().CUDA)
1790
CUDAPref = S.CUDA().IdentifyPreference(
1791
S.getCurFunctionDecl(/*AllowLambda=*/true), FD);
1792
}
1793
1794
explicit operator bool() const { return FD; }
1795
1796
bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1797
bool WantAlign) const {
1798
// C++ P0722:
1799
// A destroying operator delete is preferred over a non-destroying
1800
// operator delete.
1801
if (Destroying != Other.Destroying)
1802
return Destroying;
1803
1804
// C++17 [expr.delete]p10:
1805
// If the type has new-extended alignment, a function with a parameter
1806
// of type std::align_val_t is preferred; otherwise a function without
1807
// such a parameter is preferred
1808
if (HasAlignValT != Other.HasAlignValT)
1809
return HasAlignValT == WantAlign;
1810
1811
if (HasSizeT != Other.HasSizeT)
1812
return HasSizeT == WantSize;
1813
1814
// Use CUDA call preference as a tiebreaker.
1815
return CUDAPref > Other.CUDAPref;
1816
}
1817
1818
DeclAccessPair Found;
1819
FunctionDecl *FD;
1820
bool Destroying, HasSizeT, HasAlignValT;
1821
SemaCUDA::CUDAFunctionPreference CUDAPref;
1822
};
1823
}
1824
1825
/// Determine whether a type has new-extended alignment. This may be called when
1826
/// the type is incomplete (for a delete-expression with an incomplete pointee
1827
/// type), in which case it will conservatively return false if the alignment is
1828
/// not known.
1829
static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1830
return S.getLangOpts().AlignedAllocation &&
1831
S.getASTContext().getTypeAlignIfKnown(AllocType) >
1832
S.getASTContext().getTargetInfo().getNewAlign();
1833
}
1834
1835
/// Select the correct "usual" deallocation function to use from a selection of
1836
/// deallocation functions (either global or class-scope).
1837
static UsualDeallocFnInfo resolveDeallocationOverload(
1838
Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1839
llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1840
UsualDeallocFnInfo Best;
1841
1842
for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1843
UsualDeallocFnInfo Info(S, I.getPair());
1844
if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1845
Info.CUDAPref == SemaCUDA::CFP_Never)
1846
continue;
1847
1848
if (!Best) {
1849
Best = Info;
1850
if (BestFns)
1851
BestFns->push_back(Info);
1852
continue;
1853
}
1854
1855
if (Best.isBetterThan(Info, WantSize, WantAlign))
1856
continue;
1857
1858
// If more than one preferred function is found, all non-preferred
1859
// functions are eliminated from further consideration.
1860
if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1861
BestFns->clear();
1862
1863
Best = Info;
1864
if (BestFns)
1865
BestFns->push_back(Info);
1866
}
1867
1868
return Best;
1869
}
1870
1871
/// Determine whether a given type is a class for which 'delete[]' would call
1872
/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1873
/// we need to store the array size (even if the type is
1874
/// trivially-destructible).
1875
static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1876
QualType allocType) {
1877
const RecordType *record =
1878
allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1879
if (!record) return false;
1880
1881
// Try to find an operator delete[] in class scope.
1882
1883
DeclarationName deleteName =
1884
S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1885
LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1886
S.LookupQualifiedName(ops, record->getDecl());
1887
1888
// We're just doing this for information.
1889
ops.suppressDiagnostics();
1890
1891
// Very likely: there's no operator delete[].
1892
if (ops.empty()) return false;
1893
1894
// If it's ambiguous, it should be illegal to call operator delete[]
1895
// on this thing, so it doesn't matter if we allocate extra space or not.
1896
if (ops.isAmbiguous()) return false;
1897
1898
// C++17 [expr.delete]p10:
1899
// If the deallocation functions have class scope, the one without a
1900
// parameter of type std::size_t is selected.
1901
auto Best = resolveDeallocationOverload(
1902
S, ops, /*WantSize*/false,
1903
/*WantAlign*/hasNewExtendedAlignment(S, allocType));
1904
return Best && Best.HasSizeT;
1905
}
1906
1907
ExprResult
1908
Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1909
SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1910
SourceLocation PlacementRParen, SourceRange TypeIdParens,
1911
Declarator &D, Expr *Initializer) {
1912
std::optional<Expr *> ArraySize;
1913
// If the specified type is an array, unwrap it and save the expression.
1914
if (D.getNumTypeObjects() > 0 &&
1915
D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1916
DeclaratorChunk &Chunk = D.getTypeObject(0);
1917
if (D.getDeclSpec().hasAutoTypeSpec())
1918
return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1919
<< D.getSourceRange());
1920
if (Chunk.Arr.hasStatic)
1921
return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1922
<< D.getSourceRange());
1923
if (!Chunk.Arr.NumElts && !Initializer)
1924
return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1925
<< D.getSourceRange());
1926
1927
ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1928
D.DropFirstTypeObject();
1929
}
1930
1931
// Every dimension shall be of constant size.
1932
if (ArraySize) {
1933
for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1934
if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1935
break;
1936
1937
DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1938
if (Expr *NumElts = (Expr *)Array.NumElts) {
1939
if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1940
// FIXME: GCC permits constant folding here. We should either do so consistently
1941
// or not do so at all, rather than changing behavior in C++14 onwards.
1942
if (getLangOpts().CPlusPlus14) {
1943
// C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1944
// shall be a converted constant expression (5.19) of type std::size_t
1945
// and shall evaluate to a strictly positive value.
1946
llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1947
Array.NumElts
1948
= CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1949
CCEK_ArrayBound)
1950
.get();
1951
} else {
1952
Array.NumElts =
1953
VerifyIntegerConstantExpression(
1954
NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)
1955
.get();
1956
}
1957
if (!Array.NumElts)
1958
return ExprError();
1959
}
1960
}
1961
}
1962
}
1963
1964
TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1965
QualType AllocType = TInfo->getType();
1966
if (D.isInvalidType())
1967
return ExprError();
1968
1969
SourceRange DirectInitRange;
1970
if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1971
DirectInitRange = List->getSourceRange();
1972
1973
return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1974
PlacementLParen, PlacementArgs, PlacementRParen,
1975
TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1976
Initializer);
1977
}
1978
1979
static bool isLegalArrayNewInitializer(CXXNewInitializationStyle Style,
1980
Expr *Init, bool IsCPlusPlus20) {
1981
if (!Init)
1982
return true;
1983
if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1984
return IsCPlusPlus20 || PLE->getNumExprs() == 0;
1985
if (isa<ImplicitValueInitExpr>(Init))
1986
return true;
1987
else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1988
return !CCE->isListInitialization() &&
1989
CCE->getConstructor()->isDefaultConstructor();
1990
else if (Style == CXXNewInitializationStyle::Braces) {
1991
assert(isa<InitListExpr>(Init) &&
1992
"Shouldn't create list CXXConstructExprs for arrays.");
1993
return true;
1994
}
1995
return false;
1996
}
1997
1998
bool
1999
Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
2000
if (!getLangOpts().AlignedAllocationUnavailable)
2001
return false;
2002
if (FD.isDefined())
2003
return false;
2004
std::optional<unsigned> AlignmentParam;
2005
if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
2006
AlignmentParam)
2007
return true;
2008
return false;
2009
}
2010
2011
// Emit a diagnostic if an aligned allocation/deallocation function that is not
2012
// implemented in the standard library is selected.
2013
void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
2014
SourceLocation Loc) {
2015
if (isUnavailableAlignedAllocationFunction(FD)) {
2016
const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
2017
StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
2018
getASTContext().getTargetInfo().getPlatformName());
2019
VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
2020
2021
OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
2022
bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
2023
Diag(Loc, diag::err_aligned_allocation_unavailable)
2024
<< IsDelete << FD.getType().getAsString() << OSName
2025
<< OSVersion.getAsString() << OSVersion.empty();
2026
Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
2027
}
2028
}
2029
2030
ExprResult Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
2031
SourceLocation PlacementLParen,
2032
MultiExprArg PlacementArgs,
2033
SourceLocation PlacementRParen,
2034
SourceRange TypeIdParens, QualType AllocType,
2035
TypeSourceInfo *AllocTypeInfo,
2036
std::optional<Expr *> ArraySize,
2037
SourceRange DirectInitRange, Expr *Initializer) {
2038
SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
2039
SourceLocation StartLoc = Range.getBegin();
2040
2041
CXXNewInitializationStyle InitStyle;
2042
if (DirectInitRange.isValid()) {
2043
assert(Initializer && "Have parens but no initializer.");
2044
InitStyle = CXXNewInitializationStyle::Parens;
2045
} else if (isa_and_nonnull<InitListExpr>(Initializer))
2046
InitStyle = CXXNewInitializationStyle::Braces;
2047
else {
2048
assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
2049
isa<CXXConstructExpr>(Initializer)) &&
2050
"Initializer expression that cannot have been implicitly created.");
2051
InitStyle = CXXNewInitializationStyle::None;
2052
}
2053
2054
MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
2055
if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
2056
assert(InitStyle == CXXNewInitializationStyle::Parens &&
2057
"paren init for non-call init");
2058
Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
2059
}
2060
2061
// C++11 [expr.new]p15:
2062
// A new-expression that creates an object of type T initializes that
2063
// object as follows:
2064
InitializationKind Kind = [&] {
2065
switch (InitStyle) {
2066
// - If the new-initializer is omitted, the object is default-
2067
// initialized (8.5); if no initialization is performed,
2068
// the object has indeterminate value
2069
case CXXNewInitializationStyle::None:
2070
return InitializationKind::CreateDefault(TypeRange.getBegin());
2071
// - Otherwise, the new-initializer is interpreted according to the
2072
// initialization rules of 8.5 for direct-initialization.
2073
case CXXNewInitializationStyle::Parens:
2074
return InitializationKind::CreateDirect(TypeRange.getBegin(),
2075
DirectInitRange.getBegin(),
2076
DirectInitRange.getEnd());
2077
case CXXNewInitializationStyle::Braces:
2078
return InitializationKind::CreateDirectList(TypeRange.getBegin(),
2079
Initializer->getBeginLoc(),
2080
Initializer->getEndLoc());
2081
}
2082
llvm_unreachable("Unknown initialization kind");
2083
}();
2084
2085
// C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2086
auto *Deduced = AllocType->getContainedDeducedType();
2087
if (Deduced && !Deduced->isDeduced() &&
2088
isa<DeducedTemplateSpecializationType>(Deduced)) {
2089
if (ArraySize)
2090
return ExprError(
2091
Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2092
diag::err_deduced_class_template_compound_type)
2093
<< /*array*/ 2
2094
<< (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2095
2096
InitializedEntity Entity
2097
= InitializedEntity::InitializeNew(StartLoc, AllocType);
2098
AllocType = DeduceTemplateSpecializationFromInitializer(
2099
AllocTypeInfo, Entity, Kind, Exprs);
2100
if (AllocType.isNull())
2101
return ExprError();
2102
} else if (Deduced && !Deduced->isDeduced()) {
2103
MultiExprArg Inits = Exprs;
2104
bool Braced = (InitStyle == CXXNewInitializationStyle::Braces);
2105
if (Braced) {
2106
auto *ILE = cast<InitListExpr>(Exprs[0]);
2107
Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2108
}
2109
2110
if (InitStyle == CXXNewInitializationStyle::None || Inits.empty())
2111
return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2112
<< AllocType << TypeRange);
2113
if (Inits.size() > 1) {
2114
Expr *FirstBad = Inits[1];
2115
return ExprError(Diag(FirstBad->getBeginLoc(),
2116
diag::err_auto_new_ctor_multiple_expressions)
2117
<< AllocType << TypeRange);
2118
}
2119
if (Braced && !getLangOpts().CPlusPlus17)
2120
Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2121
<< AllocType << TypeRange;
2122
Expr *Deduce = Inits[0];
2123
if (isa<InitListExpr>(Deduce))
2124
return ExprError(
2125
Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
2126
<< Braced << AllocType << TypeRange);
2127
QualType DeducedType;
2128
TemplateDeductionInfo Info(Deduce->getExprLoc());
2129
TemplateDeductionResult Result =
2130
DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);
2131
if (Result != TemplateDeductionResult::Success &&
2132
Result != TemplateDeductionResult::AlreadyDiagnosed)
2133
return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2134
<< AllocType << Deduce->getType() << TypeRange
2135
<< Deduce->getSourceRange());
2136
if (DeducedType.isNull()) {
2137
assert(Result == TemplateDeductionResult::AlreadyDiagnosed);
2138
return ExprError();
2139
}
2140
AllocType = DeducedType;
2141
}
2142
2143
// Per C++0x [expr.new]p5, the type being constructed may be a
2144
// typedef of an array type.
2145
if (!ArraySize) {
2146
if (const ConstantArrayType *Array
2147
= Context.getAsConstantArrayType(AllocType)) {
2148
ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2149
Context.getSizeType(),
2150
TypeRange.getEnd());
2151
AllocType = Array->getElementType();
2152
}
2153
}
2154
2155
if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2156
return ExprError();
2157
2158
if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))
2159
return ExprError();
2160
2161
// In ARC, infer 'retaining' for the allocated
2162
if (getLangOpts().ObjCAutoRefCount &&
2163
AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2164
AllocType->isObjCLifetimeType()) {
2165
AllocType = Context.getLifetimeQualifiedType(AllocType,
2166
AllocType->getObjCARCImplicitLifetime());
2167
}
2168
2169
QualType ResultType = Context.getPointerType(AllocType);
2170
2171
if (ArraySize && *ArraySize &&
2172
(*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2173
ExprResult result = CheckPlaceholderExpr(*ArraySize);
2174
if (result.isInvalid()) return ExprError();
2175
ArraySize = result.get();
2176
}
2177
// C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2178
// integral or enumeration type with a non-negative value."
2179
// C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2180
// enumeration type, or a class type for which a single non-explicit
2181
// conversion function to integral or unscoped enumeration type exists.
2182
// C++1y [expr.new]p6: The expression [...] is implicitly converted to
2183
// std::size_t.
2184
std::optional<uint64_t> KnownArraySize;
2185
if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2186
ExprResult ConvertedSize;
2187
if (getLangOpts().CPlusPlus14) {
2188
assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2189
2190
ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
2191
AA_Converting);
2192
2193
if (!ConvertedSize.isInvalid() &&
2194
(*ArraySize)->getType()->getAs<RecordType>())
2195
// Diagnose the compatibility of this conversion.
2196
Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2197
<< (*ArraySize)->getType() << 0 << "'size_t'";
2198
} else {
2199
class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2200
protected:
2201
Expr *ArraySize;
2202
2203
public:
2204
SizeConvertDiagnoser(Expr *ArraySize)
2205
: ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2206
ArraySize(ArraySize) {}
2207
2208
SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2209
QualType T) override {
2210
return S.Diag(Loc, diag::err_array_size_not_integral)
2211
<< S.getLangOpts().CPlusPlus11 << T;
2212
}
2213
2214
SemaDiagnosticBuilder diagnoseIncomplete(
2215
Sema &S, SourceLocation Loc, QualType T) override {
2216
return S.Diag(Loc, diag::err_array_size_incomplete_type)
2217
<< T << ArraySize->getSourceRange();
2218
}
2219
2220
SemaDiagnosticBuilder diagnoseExplicitConv(
2221
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2222
return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2223
}
2224
2225
SemaDiagnosticBuilder noteExplicitConv(
2226
Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2227
return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2228
<< ConvTy->isEnumeralType() << ConvTy;
2229
}
2230
2231
SemaDiagnosticBuilder diagnoseAmbiguous(
2232
Sema &S, SourceLocation Loc, QualType T) override {
2233
return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2234
}
2235
2236
SemaDiagnosticBuilder noteAmbiguous(
2237
Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2238
return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2239
<< ConvTy->isEnumeralType() << ConvTy;
2240
}
2241
2242
SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2243
QualType T,
2244
QualType ConvTy) override {
2245
return S.Diag(Loc,
2246
S.getLangOpts().CPlusPlus11
2247
? diag::warn_cxx98_compat_array_size_conversion
2248
: diag::ext_array_size_conversion)
2249
<< T << ConvTy->isEnumeralType() << ConvTy;
2250
}
2251
} SizeDiagnoser(*ArraySize);
2252
2253
ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2254
SizeDiagnoser);
2255
}
2256
if (ConvertedSize.isInvalid())
2257
return ExprError();
2258
2259
ArraySize = ConvertedSize.get();
2260
QualType SizeType = (*ArraySize)->getType();
2261
2262
if (!SizeType->isIntegralOrUnscopedEnumerationType())
2263
return ExprError();
2264
2265
// C++98 [expr.new]p7:
2266
// The expression in a direct-new-declarator shall have integral type
2267
// with a non-negative value.
2268
//
2269
// Let's see if this is a constant < 0. If so, we reject it out of hand,
2270
// per CWG1464. Otherwise, if it's not a constant, we must have an
2271
// unparenthesized array type.
2272
2273
// We've already performed any required implicit conversion to integer or
2274
// unscoped enumeration type.
2275
// FIXME: Per CWG1464, we are required to check the value prior to
2276
// converting to size_t. This will never find a negative array size in
2277
// C++14 onwards, because Value is always unsigned here!
2278
if (std::optional<llvm::APSInt> Value =
2279
(*ArraySize)->getIntegerConstantExpr(Context)) {
2280
if (Value->isSigned() && Value->isNegative()) {
2281
return ExprError(Diag((*ArraySize)->getBeginLoc(),
2282
diag::err_typecheck_negative_array_size)
2283
<< (*ArraySize)->getSourceRange());
2284
}
2285
2286
if (!AllocType->isDependentType()) {
2287
unsigned ActiveSizeBits =
2288
ConstantArrayType::getNumAddressingBits(Context, AllocType, *Value);
2289
if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2290
return ExprError(
2291
Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2292
<< toString(*Value, 10) << (*ArraySize)->getSourceRange());
2293
}
2294
2295
KnownArraySize = Value->getZExtValue();
2296
} else if (TypeIdParens.isValid()) {
2297
// Can't have dynamic array size when the type-id is in parentheses.
2298
Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2299
<< (*ArraySize)->getSourceRange()
2300
<< FixItHint::CreateRemoval(TypeIdParens.getBegin())
2301
<< FixItHint::CreateRemoval(TypeIdParens.getEnd());
2302
2303
TypeIdParens = SourceRange();
2304
}
2305
2306
// Note that we do *not* convert the argument in any way. It can
2307
// be signed, larger than size_t, whatever.
2308
}
2309
2310
FunctionDecl *OperatorNew = nullptr;
2311
FunctionDecl *OperatorDelete = nullptr;
2312
unsigned Alignment =
2313
AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2314
unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2315
bool PassAlignment = getLangOpts().AlignedAllocation &&
2316
Alignment > NewAlignment;
2317
2318
if (CheckArgsForPlaceholders(PlacementArgs))
2319
return ExprError();
2320
2321
AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
2322
if (!AllocType->isDependentType() &&
2323
!Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2324
FindAllocationFunctions(
2325
StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2326
AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs,
2327
OperatorNew, OperatorDelete))
2328
return ExprError();
2329
2330
// If this is an array allocation, compute whether the usual array
2331
// deallocation function for the type has a size_t parameter.
2332
bool UsualArrayDeleteWantsSize = false;
2333
if (ArraySize && !AllocType->isDependentType())
2334
UsualArrayDeleteWantsSize =
2335
doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2336
2337
SmallVector<Expr *, 8> AllPlaceArgs;
2338
if (OperatorNew) {
2339
auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2340
VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2341
: VariadicDoesNotApply;
2342
2343
// We've already converted the placement args, just fill in any default
2344
// arguments. Skip the first parameter because we don't have a corresponding
2345
// argument. Skip the second parameter too if we're passing in the
2346
// alignment; we've already filled it in.
2347
unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
2348
if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2349
NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2350
CallType))
2351
return ExprError();
2352
2353
if (!AllPlaceArgs.empty())
2354
PlacementArgs = AllPlaceArgs;
2355
2356
// We would like to perform some checking on the given `operator new` call,
2357
// but the PlacementArgs does not contain the implicit arguments,
2358
// namely allocation size and maybe allocation alignment,
2359
// so we need to conjure them.
2360
2361
QualType SizeTy = Context.getSizeType();
2362
unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2363
2364
llvm::APInt SingleEltSize(
2365
SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2366
2367
// How many bytes do we want to allocate here?
2368
std::optional<llvm::APInt> AllocationSize;
2369
if (!ArraySize && !AllocType->isDependentType()) {
2370
// For non-array operator new, we only want to allocate one element.
2371
AllocationSize = SingleEltSize;
2372
} else if (KnownArraySize && !AllocType->isDependentType()) {
2373
// For array operator new, only deal with static array size case.
2374
bool Overflow;
2375
AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2376
.umul_ov(SingleEltSize, Overflow);
2377
(void)Overflow;
2378
assert(
2379
!Overflow &&
2380
"Expected that all the overflows would have been handled already.");
2381
}
2382
2383
IntegerLiteral AllocationSizeLiteral(
2384
Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2385
SizeTy, SourceLocation());
2386
// Otherwise, if we failed to constant-fold the allocation size, we'll
2387
// just give up and pass-in something opaque, that isn't a null pointer.
2388
OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue,
2389
OK_Ordinary, /*SourceExpr=*/nullptr);
2390
2391
// Let's synthesize the alignment argument in case we will need it.
2392
// Since we *really* want to allocate these on stack, this is slightly ugly
2393
// because there might not be a `std::align_val_t` type.
2394
EnumDecl *StdAlignValT = getStdAlignValT();
2395
QualType AlignValT =
2396
StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy;
2397
IntegerLiteral AlignmentLiteral(
2398
Context,
2399
llvm::APInt(Context.getTypeSize(SizeTy),
2400
Alignment / Context.getCharWidth()),
2401
SizeTy, SourceLocation());
2402
ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2403
CK_IntegralCast, &AlignmentLiteral,
2404
VK_PRValue, FPOptionsOverride());
2405
2406
// Adjust placement args by prepending conjured size and alignment exprs.
2407
llvm::SmallVector<Expr *, 8> CallArgs;
2408
CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2409
CallArgs.emplace_back(AllocationSize
2410
? static_cast<Expr *>(&AllocationSizeLiteral)
2411
: &OpaqueAllocationSize);
2412
if (PassAlignment)
2413
CallArgs.emplace_back(&DesiredAlignment);
2414
CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2415
2416
DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2417
2418
checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2419
/*IsMemberFunction=*/false, StartLoc, Range, CallType);
2420
2421
// Warn if the type is over-aligned and is being allocated by (unaligned)
2422
// global operator new.
2423
if (PlacementArgs.empty() && !PassAlignment &&
2424
(OperatorNew->isImplicit() ||
2425
(OperatorNew->getBeginLoc().isValid() &&
2426
getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2427
if (Alignment > NewAlignment)
2428
Diag(StartLoc, diag::warn_overaligned_type)
2429
<< AllocType
2430
<< unsigned(Alignment / Context.getCharWidth())
2431
<< unsigned(NewAlignment / Context.getCharWidth());
2432
}
2433
}
2434
2435
// Array 'new' can't have any initializers except empty parentheses.
2436
// Initializer lists are also allowed, in C++11. Rely on the parser for the
2437
// dialect distinction.
2438
if (ArraySize && !isLegalArrayNewInitializer(InitStyle, Initializer,
2439
getLangOpts().CPlusPlus20)) {
2440
SourceRange InitRange(Exprs.front()->getBeginLoc(),
2441
Exprs.back()->getEndLoc());
2442
Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2443
return ExprError();
2444
}
2445
2446
// If we can perform the initialization, and we've not already done so,
2447
// do it now.
2448
if (!AllocType->isDependentType() &&
2449
!Expr::hasAnyTypeDependentArguments(Exprs)) {
2450
// The type we initialize is the complete type, including the array bound.
2451
QualType InitType;
2452
if (KnownArraySize)
2453
InitType = Context.getConstantArrayType(
2454
AllocType,
2455
llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2456
*KnownArraySize),
2457
*ArraySize, ArraySizeModifier::Normal, 0);
2458
else if (ArraySize)
2459
InitType = Context.getIncompleteArrayType(AllocType,
2460
ArraySizeModifier::Normal, 0);
2461
else
2462
InitType = AllocType;
2463
2464
InitializedEntity Entity
2465
= InitializedEntity::InitializeNew(StartLoc, InitType);
2466
InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2467
ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);
2468
if (FullInit.isInvalid())
2469
return ExprError();
2470
2471
// FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2472
// we don't want the initialized object to be destructed.
2473
// FIXME: We should not create these in the first place.
2474
if (CXXBindTemporaryExpr *Binder =
2475
dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2476
FullInit = Binder->getSubExpr();
2477
2478
Initializer = FullInit.get();
2479
2480
// FIXME: If we have a KnownArraySize, check that the array bound of the
2481
// initializer is no greater than that constant value.
2482
2483
if (ArraySize && !*ArraySize) {
2484
auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2485
if (CAT) {
2486
// FIXME: Track that the array size was inferred rather than explicitly
2487
// specified.
2488
ArraySize = IntegerLiteral::Create(
2489
Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2490
} else {
2491
Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2492
<< Initializer->getSourceRange();
2493
}
2494
}
2495
}
2496
2497
// Mark the new and delete operators as referenced.
2498
if (OperatorNew) {
2499
if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2500
return ExprError();
2501
MarkFunctionReferenced(StartLoc, OperatorNew);
2502
}
2503
if (OperatorDelete) {
2504
if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2505
return ExprError();
2506
MarkFunctionReferenced(StartLoc, OperatorDelete);
2507
}
2508
2509
return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2510
PassAlignment, UsualArrayDeleteWantsSize,
2511
PlacementArgs, TypeIdParens, ArraySize, InitStyle,
2512
Initializer, ResultType, AllocTypeInfo, Range,
2513
DirectInitRange);
2514
}
2515
2516
bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2517
SourceRange R) {
2518
// C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2519
// abstract class type or array thereof.
2520
if (AllocType->isFunctionType())
2521
return Diag(Loc, diag::err_bad_new_type)
2522
<< AllocType << 0 << R;
2523
else if (AllocType->isReferenceType())
2524
return Diag(Loc, diag::err_bad_new_type)
2525
<< AllocType << 1 << R;
2526
else if (!AllocType->isDependentType() &&
2527
RequireCompleteSizedType(
2528
Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2529
return true;
2530
else if (RequireNonAbstractType(Loc, AllocType,
2531
diag::err_allocation_of_abstract_type))
2532
return true;
2533
else if (AllocType->isVariablyModifiedType())
2534
return Diag(Loc, diag::err_variably_modified_new_type)
2535
<< AllocType;
2536
else if (AllocType.getAddressSpace() != LangAS::Default &&
2537
!getLangOpts().OpenCLCPlusPlus)
2538
return Diag(Loc, diag::err_address_space_qualified_new)
2539
<< AllocType.getUnqualifiedType()
2540
<< AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2541
else if (getLangOpts().ObjCAutoRefCount) {
2542
if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2543
QualType BaseAllocType = Context.getBaseElementType(AT);
2544
if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2545
BaseAllocType->isObjCLifetimeType())
2546
return Diag(Loc, diag::err_arc_new_array_without_ownership)
2547
<< BaseAllocType;
2548
}
2549
}
2550
2551
return false;
2552
}
2553
2554
static bool resolveAllocationOverload(
2555
Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2556
bool &PassAlignment, FunctionDecl *&Operator,
2557
OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2558
OverloadCandidateSet Candidates(R.getNameLoc(),
2559
OverloadCandidateSet::CSK_Normal);
2560
for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2561
Alloc != AllocEnd; ++Alloc) {
2562
// Even member operator new/delete are implicitly treated as
2563
// static, so don't use AddMemberCandidate.
2564
NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2565
2566
if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2567
S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2568
/*ExplicitTemplateArgs=*/nullptr, Args,
2569
Candidates,
2570
/*SuppressUserConversions=*/false);
2571
continue;
2572
}
2573
2574
FunctionDecl *Fn = cast<FunctionDecl>(D);
2575
S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2576
/*SuppressUserConversions=*/false);
2577
}
2578
2579
// Do the resolution.
2580
OverloadCandidateSet::iterator Best;
2581
switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2582
case OR_Success: {
2583
// Got one!
2584
FunctionDecl *FnDecl = Best->Function;
2585
if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2586
Best->FoundDecl) == Sema::AR_inaccessible)
2587
return true;
2588
2589
Operator = FnDecl;
2590
return false;
2591
}
2592
2593
case OR_No_Viable_Function:
2594
// C++17 [expr.new]p13:
2595
// If no matching function is found and the allocated object type has
2596
// new-extended alignment, the alignment argument is removed from the
2597
// argument list, and overload resolution is performed again.
2598
if (PassAlignment) {
2599
PassAlignment = false;
2600
AlignArg = Args[1];
2601
Args.erase(Args.begin() + 1);
2602
return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2603
Operator, &Candidates, AlignArg,
2604
Diagnose);
2605
}
2606
2607
// MSVC will fall back on trying to find a matching global operator new
2608
// if operator new[] cannot be found. Also, MSVC will leak by not
2609
// generating a call to operator delete or operator delete[], but we
2610
// will not replicate that bug.
2611
// FIXME: Find out how this interacts with the std::align_val_t fallback
2612
// once MSVC implements it.
2613
if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2614
S.Context.getLangOpts().MSVCCompat) {
2615
R.clear();
2616
R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2617
S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2618
// FIXME: This will give bad diagnostics pointing at the wrong functions.
2619
return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2620
Operator, /*Candidates=*/nullptr,
2621
/*AlignArg=*/nullptr, Diagnose);
2622
}
2623
2624
if (Diagnose) {
2625
// If this is an allocation of the form 'new (p) X' for some object
2626
// pointer p (or an expression that will decay to such a pointer),
2627
// diagnose the missing inclusion of <new>.
2628
if (!R.isClassLookup() && Args.size() == 2 &&
2629
(Args[1]->getType()->isObjectPointerType() ||
2630
Args[1]->getType()->isArrayType())) {
2631
S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2632
<< R.getLookupName() << Range;
2633
// Listing the candidates is unlikely to be useful; skip it.
2634
return true;
2635
}
2636
2637
// Finish checking all candidates before we note any. This checking can
2638
// produce additional diagnostics so can't be interleaved with our
2639
// emission of notes.
2640
//
2641
// For an aligned allocation, separately check the aligned and unaligned
2642
// candidates with their respective argument lists.
2643
SmallVector<OverloadCandidate*, 32> Cands;
2644
SmallVector<OverloadCandidate*, 32> AlignedCands;
2645
llvm::SmallVector<Expr*, 4> AlignedArgs;
2646
if (AlignedCandidates) {
2647
auto IsAligned = [](OverloadCandidate &C) {
2648
return C.Function->getNumParams() > 1 &&
2649
C.Function->getParamDecl(1)->getType()->isAlignValT();
2650
};
2651
auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2652
2653
AlignedArgs.reserve(Args.size() + 1);
2654
AlignedArgs.push_back(Args[0]);
2655
AlignedArgs.push_back(AlignArg);
2656
AlignedArgs.append(Args.begin() + 1, Args.end());
2657
AlignedCands = AlignedCandidates->CompleteCandidates(
2658
S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2659
2660
Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2661
R.getNameLoc(), IsUnaligned);
2662
} else {
2663
Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2664
R.getNameLoc());
2665
}
2666
2667
S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2668
<< R.getLookupName() << Range;
2669
if (AlignedCandidates)
2670
AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2671
R.getNameLoc());
2672
Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2673
}
2674
return true;
2675
2676
case OR_Ambiguous:
2677
if (Diagnose) {
2678
Candidates.NoteCandidates(
2679
PartialDiagnosticAt(R.getNameLoc(),
2680
S.PDiag(diag::err_ovl_ambiguous_call)
2681
<< R.getLookupName() << Range),
2682
S, OCD_AmbiguousCandidates, Args);
2683
}
2684
return true;
2685
2686
case OR_Deleted: {
2687
if (Diagnose)
2688
S.DiagnoseUseOfDeletedFunction(R.getNameLoc(), Range, R.getLookupName(),
2689
Candidates, Best->Function, Args);
2690
return true;
2691
}
2692
}
2693
llvm_unreachable("Unreachable, bad result from BestViableFunction");
2694
}
2695
2696
bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2697
AllocationFunctionScope NewScope,
2698
AllocationFunctionScope DeleteScope,
2699
QualType AllocType, bool IsArray,
2700
bool &PassAlignment, MultiExprArg PlaceArgs,
2701
FunctionDecl *&OperatorNew,
2702
FunctionDecl *&OperatorDelete,
2703
bool Diagnose) {
2704
// --- Choosing an allocation function ---
2705
// C++ 5.3.4p8 - 14 & 18
2706
// 1) If looking in AFS_Global scope for allocation functions, only look in
2707
// the global scope. Else, if AFS_Class, only look in the scope of the
2708
// allocated class. If AFS_Both, look in both.
2709
// 2) If an array size is given, look for operator new[], else look for
2710
// operator new.
2711
// 3) The first argument is always size_t. Append the arguments from the
2712
// placement form.
2713
2714
SmallVector<Expr*, 8> AllocArgs;
2715
AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2716
2717
// We don't care about the actual value of these arguments.
2718
// FIXME: Should the Sema create the expression and embed it in the syntax
2719
// tree? Or should the consumer just recalculate the value?
2720
// FIXME: Using a dummy value will interact poorly with attribute enable_if.
2721
QualType SizeTy = Context.getSizeType();
2722
unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2723
IntegerLiteral Size(Context, llvm::APInt::getZero(SizeTyWidth), SizeTy,
2724
SourceLocation());
2725
AllocArgs.push_back(&Size);
2726
2727
QualType AlignValT = Context.VoidTy;
2728
if (PassAlignment) {
2729
DeclareGlobalNewDelete();
2730
AlignValT = Context.getTypeDeclType(getStdAlignValT());
2731
}
2732
CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2733
if (PassAlignment)
2734
AllocArgs.push_back(&Align);
2735
2736
AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2737
2738
// C++ [expr.new]p8:
2739
// If the allocated type is a non-array type, the allocation
2740
// function's name is operator new and the deallocation function's
2741
// name is operator delete. If the allocated type is an array
2742
// type, the allocation function's name is operator new[] and the
2743
// deallocation function's name is operator delete[].
2744
DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2745
IsArray ? OO_Array_New : OO_New);
2746
2747
QualType AllocElemType = Context.getBaseElementType(AllocType);
2748
2749
// Find the allocation function.
2750
{
2751
LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2752
2753
// C++1z [expr.new]p9:
2754
// If the new-expression begins with a unary :: operator, the allocation
2755
// function's name is looked up in the global scope. Otherwise, if the
2756
// allocated type is a class type T or array thereof, the allocation
2757
// function's name is looked up in the scope of T.
2758
if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2759
LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2760
2761
// We can see ambiguity here if the allocation function is found in
2762
// multiple base classes.
2763
if (R.isAmbiguous())
2764
return true;
2765
2766
// If this lookup fails to find the name, or if the allocated type is not
2767
// a class type, the allocation function's name is looked up in the
2768
// global scope.
2769
if (R.empty()) {
2770
if (NewScope == AFS_Class)
2771
return true;
2772
2773
LookupQualifiedName(R, Context.getTranslationUnitDecl());
2774
}
2775
2776
if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2777
if (PlaceArgs.empty()) {
2778
Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2779
} else {
2780
Diag(StartLoc, diag::err_openclcxx_placement_new);
2781
}
2782
return true;
2783
}
2784
2785
assert(!R.empty() && "implicitly declared allocation functions not found");
2786
assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2787
2788
// We do our own custom access checks below.
2789
R.suppressDiagnostics();
2790
2791
if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2792
OperatorNew, /*Candidates=*/nullptr,
2793
/*AlignArg=*/nullptr, Diagnose))
2794
return true;
2795
}
2796
2797
// We don't need an operator delete if we're running under -fno-exceptions.
2798
if (!getLangOpts().Exceptions) {
2799
OperatorDelete = nullptr;
2800
return false;
2801
}
2802
2803
// Note, the name of OperatorNew might have been changed from array to
2804
// non-array by resolveAllocationOverload.
2805
DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2806
OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2807
? OO_Array_Delete
2808
: OO_Delete);
2809
2810
// C++ [expr.new]p19:
2811
//
2812
// If the new-expression begins with a unary :: operator, the
2813
// deallocation function's name is looked up in the global
2814
// scope. Otherwise, if the allocated type is a class type T or an
2815
// array thereof, the deallocation function's name is looked up in
2816
// the scope of T. If this lookup fails to find the name, or if
2817
// the allocated type is not a class type or array thereof, the
2818
// deallocation function's name is looked up in the global scope.
2819
LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2820
if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2821
auto *RD =
2822
cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2823
LookupQualifiedName(FoundDelete, RD);
2824
}
2825
if (FoundDelete.isAmbiguous())
2826
return true; // FIXME: clean up expressions?
2827
2828
// Filter out any destroying operator deletes. We can't possibly call such a
2829
// function in this context, because we're handling the case where the object
2830
// was not successfully constructed.
2831
// FIXME: This is not covered by the language rules yet.
2832
{
2833
LookupResult::Filter Filter = FoundDelete.makeFilter();
2834
while (Filter.hasNext()) {
2835
auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
2836
if (FD && FD->isDestroyingOperatorDelete())
2837
Filter.erase();
2838
}
2839
Filter.done();
2840
}
2841
2842
bool FoundGlobalDelete = FoundDelete.empty();
2843
if (FoundDelete.empty()) {
2844
FoundDelete.clear(LookupOrdinaryName);
2845
2846
if (DeleteScope == AFS_Class)
2847
return true;
2848
2849
DeclareGlobalNewDelete();
2850
LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2851
}
2852
2853
FoundDelete.suppressDiagnostics();
2854
2855
SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2856
2857
// Whether we're looking for a placement operator delete is dictated
2858
// by whether we selected a placement operator new, not by whether
2859
// we had explicit placement arguments. This matters for things like
2860
// struct A { void *operator new(size_t, int = 0); ... };
2861
// A *a = new A()
2862
//
2863
// We don't have any definition for what a "placement allocation function"
2864
// is, but we assume it's any allocation function whose
2865
// parameter-declaration-clause is anything other than (size_t).
2866
//
2867
// FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2868
// This affects whether an exception from the constructor of an overaligned
2869
// type uses the sized or non-sized form of aligned operator delete.
2870
bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2871
OperatorNew->isVariadic();
2872
2873
if (isPlacementNew) {
2874
// C++ [expr.new]p20:
2875
// A declaration of a placement deallocation function matches the
2876
// declaration of a placement allocation function if it has the
2877
// same number of parameters and, after parameter transformations
2878
// (8.3.5), all parameter types except the first are
2879
// identical. [...]
2880
//
2881
// To perform this comparison, we compute the function type that
2882
// the deallocation function should have, and use that type both
2883
// for template argument deduction and for comparison purposes.
2884
QualType ExpectedFunctionType;
2885
{
2886
auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2887
2888
SmallVector<QualType, 4> ArgTypes;
2889
ArgTypes.push_back(Context.VoidPtrTy);
2890
for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2891
ArgTypes.push_back(Proto->getParamType(I));
2892
2893
FunctionProtoType::ExtProtoInfo EPI;
2894
// FIXME: This is not part of the standard's rule.
2895
EPI.Variadic = Proto->isVariadic();
2896
2897
ExpectedFunctionType
2898
= Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2899
}
2900
2901
for (LookupResult::iterator D = FoundDelete.begin(),
2902
DEnd = FoundDelete.end();
2903
D != DEnd; ++D) {
2904
FunctionDecl *Fn = nullptr;
2905
if (FunctionTemplateDecl *FnTmpl =
2906
dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2907
// Perform template argument deduction to try to match the
2908
// expected function type.
2909
TemplateDeductionInfo Info(StartLoc);
2910
if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2911
Info) != TemplateDeductionResult::Success)
2912
continue;
2913
} else
2914
Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2915
2916
if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2917
ExpectedFunctionType,
2918
/*AdjustExcpetionSpec*/true),
2919
ExpectedFunctionType))
2920
Matches.push_back(std::make_pair(D.getPair(), Fn));
2921
}
2922
2923
if (getLangOpts().CUDA)
2924
CUDA().EraseUnwantedMatches(getCurFunctionDecl(/*AllowLambda=*/true),
2925
Matches);
2926
} else {
2927
// C++1y [expr.new]p22:
2928
// For a non-placement allocation function, the normal deallocation
2929
// function lookup is used
2930
//
2931
// Per [expr.delete]p10, this lookup prefers a member operator delete
2932
// without a size_t argument, but prefers a non-member operator delete
2933
// with a size_t where possible (which it always is in this case).
2934
llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2935
UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2936
*this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2937
/*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2938
&BestDeallocFns);
2939
if (Selected)
2940
Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2941
else {
2942
// If we failed to select an operator, all remaining functions are viable
2943
// but ambiguous.
2944
for (auto Fn : BestDeallocFns)
2945
Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2946
}
2947
}
2948
2949
// C++ [expr.new]p20:
2950
// [...] If the lookup finds a single matching deallocation
2951
// function, that function will be called; otherwise, no
2952
// deallocation function will be called.
2953
if (Matches.size() == 1) {
2954
OperatorDelete = Matches[0].second;
2955
2956
// C++1z [expr.new]p23:
2957
// If the lookup finds a usual deallocation function (3.7.4.2)
2958
// with a parameter of type std::size_t and that function, considered
2959
// as a placement deallocation function, would have been
2960
// selected as a match for the allocation function, the program
2961
// is ill-formed.
2962
if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2963
isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2964
UsualDeallocFnInfo Info(*this,
2965
DeclAccessPair::make(OperatorDelete, AS_public));
2966
// Core issue, per mail to core reflector, 2016-10-09:
2967
// If this is a member operator delete, and there is a corresponding
2968
// non-sized member operator delete, this isn't /really/ a sized
2969
// deallocation function, it just happens to have a size_t parameter.
2970
bool IsSizedDelete = Info.HasSizeT;
2971
if (IsSizedDelete && !FoundGlobalDelete) {
2972
auto NonSizedDelete =
2973
resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2974
/*WantAlign*/Info.HasAlignValT);
2975
if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2976
NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2977
IsSizedDelete = false;
2978
}
2979
2980
if (IsSizedDelete) {
2981
SourceRange R = PlaceArgs.empty()
2982
? SourceRange()
2983
: SourceRange(PlaceArgs.front()->getBeginLoc(),
2984
PlaceArgs.back()->getEndLoc());
2985
Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2986
if (!OperatorDelete->isImplicit())
2987
Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2988
<< DeleteName;
2989
}
2990
}
2991
2992
CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2993
Matches[0].first);
2994
} else if (!Matches.empty()) {
2995
// We found multiple suitable operators. Per [expr.new]p20, that means we
2996
// call no 'operator delete' function, but we should at least warn the user.
2997
// FIXME: Suppress this warning if the construction cannot throw.
2998
Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2999
<< DeleteName << AllocElemType;
3000
3001
for (auto &Match : Matches)
3002
Diag(Match.second->getLocation(),
3003
diag::note_member_declared_here) << DeleteName;
3004
}
3005
3006
return false;
3007
}
3008
3009
void Sema::DeclareGlobalNewDelete() {
3010
if (GlobalNewDeleteDeclared)
3011
return;
3012
3013
// The implicitly declared new and delete operators
3014
// are not supported in OpenCL.
3015
if (getLangOpts().OpenCLCPlusPlus)
3016
return;
3017
3018
// C++ [basic.stc.dynamic.general]p2:
3019
// The library provides default definitions for the global allocation
3020
// and deallocation functions. Some global allocation and deallocation
3021
// functions are replaceable ([new.delete]); these are attached to the
3022
// global module ([module.unit]).
3023
if (getLangOpts().CPlusPlusModules && getCurrentModule())
3024
PushGlobalModuleFragment(SourceLocation());
3025
3026
// C++ [basic.std.dynamic]p2:
3027
// [...] The following allocation and deallocation functions (18.4) are
3028
// implicitly declared in global scope in each translation unit of a
3029
// program
3030
//
3031
// C++03:
3032
// void* operator new(std::size_t) throw(std::bad_alloc);
3033
// void* operator new[](std::size_t) throw(std::bad_alloc);
3034
// void operator delete(void*) throw();
3035
// void operator delete[](void*) throw();
3036
// C++11:
3037
// void* operator new(std::size_t);
3038
// void* operator new[](std::size_t);
3039
// void operator delete(void*) noexcept;
3040
// void operator delete[](void*) noexcept;
3041
// C++1y:
3042
// void* operator new(std::size_t);
3043
// void* operator new[](std::size_t);
3044
// void operator delete(void*) noexcept;
3045
// void operator delete[](void*) noexcept;
3046
// void operator delete(void*, std::size_t) noexcept;
3047
// void operator delete[](void*, std::size_t) noexcept;
3048
//
3049
// These implicit declarations introduce only the function names operator
3050
// new, operator new[], operator delete, operator delete[].
3051
//
3052
// Here, we need to refer to std::bad_alloc, so we will implicitly declare
3053
// "std" or "bad_alloc" as necessary to form the exception specification.
3054
// However, we do not make these implicit declarations visible to name
3055
// lookup.
3056
if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
3057
// The "std::bad_alloc" class has not yet been declared, so build it
3058
// implicitly.
3059
StdBadAlloc = CXXRecordDecl::Create(
3060
Context, TagTypeKind::Class, getOrCreateStdNamespace(),
3061
SourceLocation(), SourceLocation(),
3062
&PP.getIdentifierTable().get("bad_alloc"), nullptr);
3063
getStdBadAlloc()->setImplicit(true);
3064
3065
// The implicitly declared "std::bad_alloc" should live in global module
3066
// fragment.
3067
if (TheGlobalModuleFragment) {
3068
getStdBadAlloc()->setModuleOwnershipKind(
3069
Decl::ModuleOwnershipKind::ReachableWhenImported);
3070
getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);
3071
}
3072
}
3073
if (!StdAlignValT && getLangOpts().AlignedAllocation) {
3074
// The "std::align_val_t" enum class has not yet been declared, so build it
3075
// implicitly.
3076
auto *AlignValT = EnumDecl::Create(
3077
Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
3078
&PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
3079
3080
// The implicitly declared "std::align_val_t" should live in global module
3081
// fragment.
3082
if (TheGlobalModuleFragment) {
3083
AlignValT->setModuleOwnershipKind(
3084
Decl::ModuleOwnershipKind::ReachableWhenImported);
3085
AlignValT->setLocalOwningModule(TheGlobalModuleFragment);
3086
}
3087
3088
AlignValT->setIntegerType(Context.getSizeType());
3089
AlignValT->setPromotionType(Context.getSizeType());
3090
AlignValT->setImplicit(true);
3091
3092
StdAlignValT = AlignValT;
3093
}
3094
3095
GlobalNewDeleteDeclared = true;
3096
3097
QualType VoidPtr = Context.getPointerType(Context.VoidTy);
3098
QualType SizeT = Context.getSizeType();
3099
3100
auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3101
QualType Return, QualType Param) {
3102
llvm::SmallVector<QualType, 3> Params;
3103
Params.push_back(Param);
3104
3105
// Create up to four variants of the function (sized/aligned).
3106
bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3107
(Kind == OO_Delete || Kind == OO_Array_Delete);
3108
bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3109
3110
int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3111
int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3112
for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3113
if (Sized)
3114
Params.push_back(SizeT);
3115
3116
for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3117
if (Aligned)
3118
Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
3119
3120
DeclareGlobalAllocationFunction(
3121
Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3122
3123
if (Aligned)
3124
Params.pop_back();
3125
}
3126
}
3127
};
3128
3129
DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3130
DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3131
DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3132
DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3133
3134
if (getLangOpts().CPlusPlusModules && getCurrentModule())
3135
PopGlobalModuleFragment();
3136
}
3137
3138
/// DeclareGlobalAllocationFunction - Declares a single implicit global
3139
/// allocation function if it doesn't already exist.
3140
void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
3141
QualType Return,
3142
ArrayRef<QualType> Params) {
3143
DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
3144
3145
// Check if this function is already declared.
3146
DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3147
for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3148
Alloc != AllocEnd; ++Alloc) {
3149
// Only look at non-template functions, as it is the predefined,
3150
// non-templated allocation function we are trying to declare here.
3151
if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3152
if (Func->getNumParams() == Params.size()) {
3153
llvm::SmallVector<QualType, 3> FuncParams;
3154
for (auto *P : Func->parameters())
3155
FuncParams.push_back(
3156
Context.getCanonicalType(P->getType().getUnqualifiedType()));
3157
if (llvm::ArrayRef(FuncParams) == Params) {
3158
// Make the function visible to name lookup, even if we found it in
3159
// an unimported module. It either is an implicitly-declared global
3160
// allocation function, or is suppressing that function.
3161
Func->setVisibleDespiteOwningModule();
3162
return;
3163
}
3164
}
3165
}
3166
}
3167
3168
FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
3169
/*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
3170
3171
QualType BadAllocType;
3172
bool HasBadAllocExceptionSpec
3173
= (Name.getCXXOverloadedOperator() == OO_New ||
3174
Name.getCXXOverloadedOperator() == OO_Array_New);
3175
if (HasBadAllocExceptionSpec) {
3176
if (!getLangOpts().CPlusPlus11) {
3177
BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
3178
assert(StdBadAlloc && "Must have std::bad_alloc declared");
3179
EPI.ExceptionSpec.Type = EST_Dynamic;
3180
EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);
3181
}
3182
if (getLangOpts().NewInfallible) {
3183
EPI.ExceptionSpec.Type = EST_DynamicNone;
3184
}
3185
} else {
3186
EPI.ExceptionSpec =
3187
getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
3188
}
3189
3190
auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3191
QualType FnType = Context.getFunctionType(Return, Params, EPI);
3192
FunctionDecl *Alloc = FunctionDecl::Create(
3193
Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3194
/*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3195
true);
3196
Alloc->setImplicit();
3197
// Global allocation functions should always be visible.
3198
Alloc->setVisibleDespiteOwningModule();
3199
3200
if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible &&
3201
!getLangOpts().CheckNew)
3202
Alloc->addAttr(
3203
ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3204
3205
// C++ [basic.stc.dynamic.general]p2:
3206
// The library provides default definitions for the global allocation
3207
// and deallocation functions. Some global allocation and deallocation
3208
// functions are replaceable ([new.delete]); these are attached to the
3209
// global module ([module.unit]).
3210
//
3211
// In the language wording, these functions are attched to the global
3212
// module all the time. But in the implementation, the global module
3213
// is only meaningful when we're in a module unit. So here we attach
3214
// these allocation functions to global module conditionally.
3215
if (TheGlobalModuleFragment) {
3216
Alloc->setModuleOwnershipKind(
3217
Decl::ModuleOwnershipKind::ReachableWhenImported);
3218
Alloc->setLocalOwningModule(TheGlobalModuleFragment);
3219
}
3220
3221
if (LangOpts.hasGlobalAllocationFunctionVisibility())
3222
Alloc->addAttr(VisibilityAttr::CreateImplicit(
3223
Context, LangOpts.hasHiddenGlobalAllocationFunctionVisibility()
3224
? VisibilityAttr::Hidden
3225
: LangOpts.hasProtectedGlobalAllocationFunctionVisibility()
3226
? VisibilityAttr::Protected
3227
: VisibilityAttr::Default));
3228
3229
llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
3230
for (QualType T : Params) {
3231
ParamDecls.push_back(ParmVarDecl::Create(
3232
Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3233
/*TInfo=*/nullptr, SC_None, nullptr));
3234
ParamDecls.back()->setImplicit();
3235
}
3236
Alloc->setParams(ParamDecls);
3237
if (ExtraAttr)
3238
Alloc->addAttr(ExtraAttr);
3239
AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc);
3240
Context.getTranslationUnitDecl()->addDecl(Alloc);
3241
IdResolver.tryAddTopLevelDecl(Alloc, Name);
3242
};
3243
3244
if (!LangOpts.CUDA)
3245
CreateAllocationFunctionDecl(nullptr);
3246
else {
3247
// Host and device get their own declaration so each can be
3248
// defined or re-declared independently.
3249
CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3250
CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3251
}
3252
}
3253
3254
FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
3255
bool CanProvideSize,
3256
bool Overaligned,
3257
DeclarationName Name) {
3258
DeclareGlobalNewDelete();
3259
3260
LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3261
LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
3262
3263
// FIXME: It's possible for this to result in ambiguity, through a
3264
// user-declared variadic operator delete or the enable_if attribute. We
3265
// should probably not consider those cases to be usual deallocation
3266
// functions. But for now we just make an arbitrary choice in that case.
3267
auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3268
Overaligned);
3269
assert(Result.FD && "operator delete missing from global scope?");
3270
return Result.FD;
3271
}
3272
3273
FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
3274
CXXRecordDecl *RD) {
3275
DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
3276
3277
FunctionDecl *OperatorDelete = nullptr;
3278
if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3279
return nullptr;
3280
if (OperatorDelete)
3281
return OperatorDelete;
3282
3283
// If there's no class-specific operator delete, look up the global
3284
// non-array delete.
3285
return FindUsualDeallocationFunction(
3286
Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
3287
Name);
3288
}
3289
3290
bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3291
DeclarationName Name,
3292
FunctionDecl *&Operator, bool Diagnose,
3293
bool WantSize, bool WantAligned) {
3294
LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3295
// Try to find operator delete/operator delete[] in class scope.
3296
LookupQualifiedName(Found, RD);
3297
3298
if (Found.isAmbiguous())
3299
return true;
3300
3301
Found.suppressDiagnostics();
3302
3303
bool Overaligned =
3304
WantAligned || hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3305
3306
// C++17 [expr.delete]p10:
3307
// If the deallocation functions have class scope, the one without a
3308
// parameter of type std::size_t is selected.
3309
llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
3310
resolveDeallocationOverload(*this, Found, /*WantSize*/ WantSize,
3311
/*WantAlign*/ Overaligned, &Matches);
3312
3313
// If we could find an overload, use it.
3314
if (Matches.size() == 1) {
3315
Operator = cast<CXXMethodDecl>(Matches[0].FD);
3316
3317
// FIXME: DiagnoseUseOfDecl?
3318
if (Operator->isDeleted()) {
3319
if (Diagnose) {
3320
StringLiteral *Msg = Operator->getDeletedMessage();
3321
Diag(StartLoc, diag::err_deleted_function_use)
3322
<< (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
3323
NoteDeletedFunction(Operator);
3324
}
3325
return true;
3326
}
3327
3328
if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3329
Matches[0].Found, Diagnose) == AR_inaccessible)
3330
return true;
3331
3332
return false;
3333
}
3334
3335
// We found multiple suitable operators; complain about the ambiguity.
3336
// FIXME: The standard doesn't say to do this; it appears that the intent
3337
// is that this should never happen.
3338
if (!Matches.empty()) {
3339
if (Diagnose) {
3340
Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3341
<< Name << RD;
3342
for (auto &Match : Matches)
3343
Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3344
}
3345
return true;
3346
}
3347
3348
// We did find operator delete/operator delete[] declarations, but
3349
// none of them were suitable.
3350
if (!Found.empty()) {
3351
if (Diagnose) {
3352
Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3353
<< Name << RD;
3354
3355
for (NamedDecl *D : Found)
3356
Diag(D->getUnderlyingDecl()->getLocation(),
3357
diag::note_member_declared_here) << Name;
3358
}
3359
return true;
3360
}
3361
3362
Operator = nullptr;
3363
return false;
3364
}
3365
3366
namespace {
3367
/// Checks whether delete-expression, and new-expression used for
3368
/// initializing deletee have the same array form.
3369
class MismatchingNewDeleteDetector {
3370
public:
3371
enum MismatchResult {
3372
/// Indicates that there is no mismatch or a mismatch cannot be proven.
3373
NoMismatch,
3374
/// Indicates that variable is initialized with mismatching form of \a new.
3375
VarInitMismatches,
3376
/// Indicates that member is initialized with mismatching form of \a new.
3377
MemberInitMismatches,
3378
/// Indicates that 1 or more constructors' definitions could not been
3379
/// analyzed, and they will be checked again at the end of translation unit.
3380
AnalyzeLater
3381
};
3382
3383
/// \param EndOfTU True, if this is the final analysis at the end of
3384
/// translation unit. False, if this is the initial analysis at the point
3385
/// delete-expression was encountered.
3386
explicit MismatchingNewDeleteDetector(bool EndOfTU)
3387
: Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3388
HasUndefinedConstructors(false) {}
3389
3390
/// Checks whether pointee of a delete-expression is initialized with
3391
/// matching form of new-expression.
3392
///
3393
/// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3394
/// point where delete-expression is encountered, then a warning will be
3395
/// issued immediately. If return value is \c AnalyzeLater at the point where
3396
/// delete-expression is seen, then member will be analyzed at the end of
3397
/// translation unit. \c AnalyzeLater is returned iff at least one constructor
3398
/// couldn't be analyzed. If at least one constructor initializes the member
3399
/// with matching type of new, the return value is \c NoMismatch.
3400
MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3401
/// Analyzes a class member.
3402
/// \param Field Class member to analyze.
3403
/// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3404
/// for deleting the \p Field.
3405
MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3406
FieldDecl *Field;
3407
/// List of mismatching new-expressions used for initialization of the pointee
3408
llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3409
/// Indicates whether delete-expression was in array form.
3410
bool IsArrayForm;
3411
3412
private:
3413
const bool EndOfTU;
3414
/// Indicates that there is at least one constructor without body.
3415
bool HasUndefinedConstructors;
3416
/// Returns \c CXXNewExpr from given initialization expression.
3417
/// \param E Expression used for initializing pointee in delete-expression.
3418
/// E can be a single-element \c InitListExpr consisting of new-expression.
3419
const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3420
/// Returns whether member is initialized with mismatching form of
3421
/// \c new either by the member initializer or in-class initialization.
3422
///
3423
/// If bodies of all constructors are not visible at the end of translation
3424
/// unit or at least one constructor initializes member with the matching
3425
/// form of \c new, mismatch cannot be proven, and this function will return
3426
/// \c NoMismatch.
3427
MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3428
/// Returns whether variable is initialized with mismatching form of
3429
/// \c new.
3430
///
3431
/// If variable is initialized with matching form of \c new or variable is not
3432
/// initialized with a \c new expression, this function will return true.
3433
/// If variable is initialized with mismatching form of \c new, returns false.
3434
/// \param D Variable to analyze.
3435
bool hasMatchingVarInit(const DeclRefExpr *D);
3436
/// Checks whether the constructor initializes pointee with mismatching
3437
/// form of \c new.
3438
///
3439
/// Returns true, if member is initialized with matching form of \c new in
3440
/// member initializer list. Returns false, if member is initialized with the
3441
/// matching form of \c new in this constructor's initializer or given
3442
/// constructor isn't defined at the point where delete-expression is seen, or
3443
/// member isn't initialized by the constructor.
3444
bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3445
/// Checks whether member is initialized with matching form of
3446
/// \c new in member initializer list.
3447
bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3448
/// Checks whether member is initialized with mismatching form of \c new by
3449
/// in-class initializer.
3450
MismatchResult analyzeInClassInitializer();
3451
};
3452
}
3453
3454
MismatchingNewDeleteDetector::MismatchResult
3455
MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3456
NewExprs.clear();
3457
assert(DE && "Expected delete-expression");
3458
IsArrayForm = DE->isArrayForm();
3459
const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3460
if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3461
return analyzeMemberExpr(ME);
3462
} else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3463
if (!hasMatchingVarInit(D))
3464
return VarInitMismatches;
3465
}
3466
return NoMismatch;
3467
}
3468
3469
const CXXNewExpr *
3470
MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3471
assert(E != nullptr && "Expected a valid initializer expression");
3472
E = E->IgnoreParenImpCasts();
3473
if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3474
if (ILE->getNumInits() == 1)
3475
E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3476
}
3477
3478
return dyn_cast_or_null<const CXXNewExpr>(E);
3479
}
3480
3481
bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3482
const CXXCtorInitializer *CI) {
3483
const CXXNewExpr *NE = nullptr;
3484
if (Field == CI->getMember() &&
3485
(NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3486
if (NE->isArray() == IsArrayForm)
3487
return true;
3488
else
3489
NewExprs.push_back(NE);
3490
}
3491
return false;
3492
}
3493
3494
bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3495
const CXXConstructorDecl *CD) {
3496
if (CD->isImplicit())
3497
return false;
3498
const FunctionDecl *Definition = CD;
3499
if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3500
HasUndefinedConstructors = true;
3501
return EndOfTU;
3502
}
3503
for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3504
if (hasMatchingNewInCtorInit(CI))
3505
return true;
3506
}
3507
return false;
3508
}
3509
3510
MismatchingNewDeleteDetector::MismatchResult
3511
MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3512
assert(Field != nullptr && "This should be called only for members");
3513
const Expr *InitExpr = Field->getInClassInitializer();
3514
if (!InitExpr)
3515
return EndOfTU ? NoMismatch : AnalyzeLater;
3516
if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3517
if (NE->isArray() != IsArrayForm) {
3518
NewExprs.push_back(NE);
3519
return MemberInitMismatches;
3520
}
3521
}
3522
return NoMismatch;
3523
}
3524
3525
MismatchingNewDeleteDetector::MismatchResult
3526
MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3527
bool DeleteWasArrayForm) {
3528
assert(Field != nullptr && "Analysis requires a valid class member.");
3529
this->Field = Field;
3530
IsArrayForm = DeleteWasArrayForm;
3531
const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3532
for (const auto *CD : RD->ctors()) {
3533
if (hasMatchingNewInCtor(CD))
3534
return NoMismatch;
3535
}
3536
if (HasUndefinedConstructors)
3537
return EndOfTU ? NoMismatch : AnalyzeLater;
3538
if (!NewExprs.empty())
3539
return MemberInitMismatches;
3540
return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3541
: NoMismatch;
3542
}
3543
3544
MismatchingNewDeleteDetector::MismatchResult
3545
MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3546
assert(ME != nullptr && "Expected a member expression");
3547
if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3548
return analyzeField(F, IsArrayForm);
3549
return NoMismatch;
3550
}
3551
3552
bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3553
const CXXNewExpr *NE = nullptr;
3554
if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3555
if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3556
NE->isArray() != IsArrayForm) {
3557
NewExprs.push_back(NE);
3558
}
3559
}
3560
return NewExprs.empty();
3561
}
3562
3563
static void
3564
DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3565
const MismatchingNewDeleteDetector &Detector) {
3566
SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3567
FixItHint H;
3568
if (!Detector.IsArrayForm)
3569
H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3570
else {
3571
SourceLocation RSquare = Lexer::findLocationAfterToken(
3572
DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3573
SemaRef.getLangOpts(), true);
3574
if (RSquare.isValid())
3575
H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3576
}
3577
SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3578
<< Detector.IsArrayForm << H;
3579
3580
for (const auto *NE : Detector.NewExprs)
3581
SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3582
<< Detector.IsArrayForm;
3583
}
3584
3585
void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3586
if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3587
return;
3588
MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3589
switch (Detector.analyzeDeleteExpr(DE)) {
3590
case MismatchingNewDeleteDetector::VarInitMismatches:
3591
case MismatchingNewDeleteDetector::MemberInitMismatches: {
3592
DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3593
break;
3594
}
3595
case MismatchingNewDeleteDetector::AnalyzeLater: {
3596
DeleteExprs[Detector.Field].push_back(
3597
std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3598
break;
3599
}
3600
case MismatchingNewDeleteDetector::NoMismatch:
3601
break;
3602
}
3603
}
3604
3605
void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3606
bool DeleteWasArrayForm) {
3607
MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3608
switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3609
case MismatchingNewDeleteDetector::VarInitMismatches:
3610
llvm_unreachable("This analysis should have been done for class members.");
3611
case MismatchingNewDeleteDetector::AnalyzeLater:
3612
llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3613
"translation unit.");
3614
case MismatchingNewDeleteDetector::MemberInitMismatches:
3615
DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3616
break;
3617
case MismatchingNewDeleteDetector::NoMismatch:
3618
break;
3619
}
3620
}
3621
3622
ExprResult
3623
Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3624
bool ArrayForm, Expr *ExE) {
3625
// C++ [expr.delete]p1:
3626
// The operand shall have a pointer type, or a class type having a single
3627
// non-explicit conversion function to a pointer type. The result has type
3628
// void.
3629
//
3630
// DR599 amends "pointer type" to "pointer to object type" in both cases.
3631
3632
ExprResult Ex = ExE;
3633
FunctionDecl *OperatorDelete = nullptr;
3634
bool ArrayFormAsWritten = ArrayForm;
3635
bool UsualArrayDeleteWantsSize = false;
3636
3637
if (!Ex.get()->isTypeDependent()) {
3638
// Perform lvalue-to-rvalue cast, if needed.
3639
Ex = DefaultLvalueConversion(Ex.get());
3640
if (Ex.isInvalid())
3641
return ExprError();
3642
3643
QualType Type = Ex.get()->getType();
3644
3645
class DeleteConverter : public ContextualImplicitConverter {
3646
public:
3647
DeleteConverter() : ContextualImplicitConverter(false, true) {}
3648
3649
bool match(QualType ConvType) override {
3650
// FIXME: If we have an operator T* and an operator void*, we must pick
3651
// the operator T*.
3652
if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3653
if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3654
return true;
3655
return false;
3656
}
3657
3658
SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3659
QualType T) override {
3660
return S.Diag(Loc, diag::err_delete_operand) << T;
3661
}
3662
3663
SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3664
QualType T) override {
3665
return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3666
}
3667
3668
SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3669
QualType T,
3670
QualType ConvTy) override {
3671
return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3672
}
3673
3674
SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3675
QualType ConvTy) override {
3676
return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3677
<< ConvTy;
3678
}
3679
3680
SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3681
QualType T) override {
3682
return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3683
}
3684
3685
SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3686
QualType ConvTy) override {
3687
return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3688
<< ConvTy;
3689
}
3690
3691
SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3692
QualType T,
3693
QualType ConvTy) override {
3694
llvm_unreachable("conversion functions are permitted");
3695
}
3696
} Converter;
3697
3698
Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3699
if (Ex.isInvalid())
3700
return ExprError();
3701
Type = Ex.get()->getType();
3702
if (!Converter.match(Type))
3703
// FIXME: PerformContextualImplicitConversion should return ExprError
3704
// itself in this case.
3705
return ExprError();
3706
3707
QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
3708
QualType PointeeElem = Context.getBaseElementType(Pointee);
3709
3710
if (Pointee.getAddressSpace() != LangAS::Default &&
3711
!getLangOpts().OpenCLCPlusPlus)
3712
return Diag(Ex.get()->getBeginLoc(),
3713
diag::err_address_space_qualified_delete)
3714
<< Pointee.getUnqualifiedType()
3715
<< Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3716
3717
CXXRecordDecl *PointeeRD = nullptr;
3718
if (Pointee->isVoidType() && !isSFINAEContext()) {
3719
// The C++ standard bans deleting a pointer to a non-object type, which
3720
// effectively bans deletion of "void*". However, most compilers support
3721
// this, so we treat it as a warning unless we're in a SFINAE context.
3722
// But we still prohibit this since C++26.
3723
Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete
3724
: diag::ext_delete_void_ptr_operand)
3725
<< (LangOpts.CPlusPlus26 ? Pointee : Type)
3726
<< Ex.get()->getSourceRange();
3727
} else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3728
Pointee->isSizelessType()) {
3729
return ExprError(Diag(StartLoc, diag::err_delete_operand)
3730
<< Type << Ex.get()->getSourceRange());
3731
} else if (!Pointee->isDependentType()) {
3732
// FIXME: This can result in errors if the definition was imported from a
3733
// module but is hidden.
3734
if (!RequireCompleteType(StartLoc, Pointee,
3735
LangOpts.CPlusPlus26
3736
? diag::err_delete_incomplete
3737
: diag::warn_delete_incomplete,
3738
Ex.get())) {
3739
if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3740
PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3741
}
3742
}
3743
3744
if (Pointee->isArrayType() && !ArrayForm) {
3745
Diag(StartLoc, diag::warn_delete_array_type)
3746
<< Type << Ex.get()->getSourceRange()
3747
<< FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3748
ArrayForm = true;
3749
}
3750
3751
DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3752
ArrayForm ? OO_Array_Delete : OO_Delete);
3753
3754
if (PointeeRD) {
3755
if (!UseGlobal &&
3756
FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3757
OperatorDelete))
3758
return ExprError();
3759
3760
// If we're allocating an array of records, check whether the
3761
// usual operator delete[] has a size_t parameter.
3762
if (ArrayForm) {
3763
// If the user specifically asked to use the global allocator,
3764
// we'll need to do the lookup into the class.
3765
if (UseGlobal)
3766
UsualArrayDeleteWantsSize =
3767
doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3768
3769
// Otherwise, the usual operator delete[] should be the
3770
// function we just found.
3771
else if (isa_and_nonnull<CXXMethodDecl>(OperatorDelete))
3772
UsualArrayDeleteWantsSize =
3773
UsualDeallocFnInfo(*this,
3774
DeclAccessPair::make(OperatorDelete, AS_public))
3775
.HasSizeT;
3776
}
3777
3778
if (!PointeeRD->hasIrrelevantDestructor())
3779
if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3780
MarkFunctionReferenced(StartLoc,
3781
const_cast<CXXDestructorDecl*>(Dtor));
3782
if (DiagnoseUseOfDecl(Dtor, StartLoc))
3783
return ExprError();
3784
}
3785
3786
CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3787
/*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3788
/*WarnOnNonAbstractTypes=*/!ArrayForm,
3789
SourceLocation());
3790
}
3791
3792
if (!OperatorDelete) {
3793
if (getLangOpts().OpenCLCPlusPlus) {
3794
Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3795
return ExprError();
3796
}
3797
3798
bool IsComplete = isCompleteType(StartLoc, Pointee);
3799
bool CanProvideSize =
3800
IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3801
Pointee.isDestructedType());
3802
bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3803
3804
// Look for a global declaration.
3805
OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3806
Overaligned, DeleteName);
3807
}
3808
3809
MarkFunctionReferenced(StartLoc, OperatorDelete);
3810
3811
// Check access and ambiguity of destructor if we're going to call it.
3812
// Note that this is required even for a virtual delete.
3813
bool IsVirtualDelete = false;
3814
if (PointeeRD) {
3815
if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3816
CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3817
PDiag(diag::err_access_dtor) << PointeeElem);
3818
IsVirtualDelete = Dtor->isVirtual();
3819
}
3820
}
3821
3822
DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3823
3824
// Convert the operand to the type of the first parameter of operator
3825
// delete. This is only necessary if we selected a destroying operator
3826
// delete that we are going to call (non-virtually); converting to void*
3827
// is trivial and left to AST consumers to handle.
3828
QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3829
if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3830
Qualifiers Qs = Pointee.getQualifiers();
3831
if (Qs.hasCVRQualifiers()) {
3832
// Qualifiers are irrelevant to this conversion; we're only looking
3833
// for access and ambiguity.
3834
Qs.removeCVRQualifiers();
3835
QualType Unqual = Context.getPointerType(
3836
Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3837
Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3838
}
3839
Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3840
if (Ex.isInvalid())
3841
return ExprError();
3842
}
3843
}
3844
3845
CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3846
Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3847
UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3848
AnalyzeDeleteExprMismatch(Result);
3849
return Result;
3850
}
3851
3852
static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3853
bool IsDelete,
3854
FunctionDecl *&Operator) {
3855
3856
DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3857
IsDelete ? OO_Delete : OO_New);
3858
3859
LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3860
S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3861
assert(!R.empty() && "implicitly declared allocation functions not found");
3862
assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3863
3864
// We do our own custom access checks below.
3865
R.suppressDiagnostics();
3866
3867
SmallVector<Expr *, 8> Args(TheCall->arguments());
3868
OverloadCandidateSet Candidates(R.getNameLoc(),
3869
OverloadCandidateSet::CSK_Normal);
3870
for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3871
FnOvl != FnOvlEnd; ++FnOvl) {
3872
// Even member operator new/delete are implicitly treated as
3873
// static, so don't use AddMemberCandidate.
3874
NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3875
3876
if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3877
S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3878
/*ExplicitTemplateArgs=*/nullptr, Args,
3879
Candidates,
3880
/*SuppressUserConversions=*/false);
3881
continue;
3882
}
3883
3884
FunctionDecl *Fn = cast<FunctionDecl>(D);
3885
S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3886
/*SuppressUserConversions=*/false);
3887
}
3888
3889
SourceRange Range = TheCall->getSourceRange();
3890
3891
// Do the resolution.
3892
OverloadCandidateSet::iterator Best;
3893
switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3894
case OR_Success: {
3895
// Got one!
3896
FunctionDecl *FnDecl = Best->Function;
3897
assert(R.getNamingClass() == nullptr &&
3898
"class members should not be considered");
3899
3900
if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3901
S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3902
<< (IsDelete ? 1 : 0) << Range;
3903
S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3904
<< R.getLookupName() << FnDecl->getSourceRange();
3905
return true;
3906
}
3907
3908
Operator = FnDecl;
3909
return false;
3910
}
3911
3912
case OR_No_Viable_Function:
3913
Candidates.NoteCandidates(
3914
PartialDiagnosticAt(R.getNameLoc(),
3915
S.PDiag(diag::err_ovl_no_viable_function_in_call)
3916
<< R.getLookupName() << Range),
3917
S, OCD_AllCandidates, Args);
3918
return true;
3919
3920
case OR_Ambiguous:
3921
Candidates.NoteCandidates(
3922
PartialDiagnosticAt(R.getNameLoc(),
3923
S.PDiag(diag::err_ovl_ambiguous_call)
3924
<< R.getLookupName() << Range),
3925
S, OCD_AmbiguousCandidates, Args);
3926
return true;
3927
3928
case OR_Deleted:
3929
S.DiagnoseUseOfDeletedFunction(R.getNameLoc(), Range, R.getLookupName(),
3930
Candidates, Best->Function, Args);
3931
return true;
3932
}
3933
llvm_unreachable("Unreachable, bad result from BestViableFunction");
3934
}
3935
3936
ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3937
bool IsDelete) {
3938
CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3939
if (!getLangOpts().CPlusPlus) {
3940
Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3941
<< (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3942
<< "C++";
3943
return ExprError();
3944
}
3945
// CodeGen assumes it can find the global new and delete to call,
3946
// so ensure that they are declared.
3947
DeclareGlobalNewDelete();
3948
3949
FunctionDecl *OperatorNewOrDelete = nullptr;
3950
if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3951
OperatorNewOrDelete))
3952
return ExprError();
3953
assert(OperatorNewOrDelete && "should be found");
3954
3955
DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3956
MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3957
3958
TheCall->setType(OperatorNewOrDelete->getReturnType());
3959
for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3960
QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3961
InitializedEntity Entity =
3962
InitializedEntity::InitializeParameter(Context, ParamTy, false);
3963
ExprResult Arg = PerformCopyInitialization(
3964
Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3965
if (Arg.isInvalid())
3966
return ExprError();
3967
TheCall->setArg(i, Arg.get());
3968
}
3969
auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3970
assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3971
"Callee expected to be implicit cast to a builtin function pointer");
3972
Callee->setType(OperatorNewOrDelete->getType());
3973
3974
return TheCallResult;
3975
}
3976
3977
void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3978
bool IsDelete, bool CallCanBeVirtual,
3979
bool WarnOnNonAbstractTypes,
3980
SourceLocation DtorLoc) {
3981
if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3982
return;
3983
3984
// C++ [expr.delete]p3:
3985
// In the first alternative (delete object), if the static type of the
3986
// object to be deleted is different from its dynamic type, the static
3987
// type shall be a base class of the dynamic type of the object to be
3988
// deleted and the static type shall have a virtual destructor or the
3989
// behavior is undefined.
3990
//
3991
const CXXRecordDecl *PointeeRD = dtor->getParent();
3992
// Note: a final class cannot be derived from, no issue there
3993
if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3994
return;
3995
3996
// If the superclass is in a system header, there's nothing that can be done.
3997
// The `delete` (where we emit the warning) can be in a system header,
3998
// what matters for this warning is where the deleted type is defined.
3999
if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
4000
return;
4001
4002
QualType ClassType = dtor->getFunctionObjectParameterType();
4003
if (PointeeRD->isAbstract()) {
4004
// If the class is abstract, we warn by default, because we're
4005
// sure the code has undefined behavior.
4006
Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
4007
<< ClassType;
4008
} else if (WarnOnNonAbstractTypes) {
4009
// Otherwise, if this is not an array delete, it's a bit suspect,
4010
// but not necessarily wrong.
4011
Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
4012
<< ClassType;
4013
}
4014
if (!IsDelete) {
4015
std::string TypeStr;
4016
ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
4017
Diag(DtorLoc, diag::note_delete_non_virtual)
4018
<< FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
4019
}
4020
}
4021
4022
Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
4023
SourceLocation StmtLoc,
4024
ConditionKind CK) {
4025
ExprResult E =
4026
CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
4027
if (E.isInvalid())
4028
return ConditionError();
4029
return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
4030
CK == ConditionKind::ConstexprIf);
4031
}
4032
4033
ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
4034
SourceLocation StmtLoc,
4035
ConditionKind CK) {
4036
if (ConditionVar->isInvalidDecl())
4037
return ExprError();
4038
4039
QualType T = ConditionVar->getType();
4040
4041
// C++ [stmt.select]p2:
4042
// The declarator shall not specify a function or an array.
4043
if (T->isFunctionType())
4044
return ExprError(Diag(ConditionVar->getLocation(),
4045
diag::err_invalid_use_of_function_type)
4046
<< ConditionVar->getSourceRange());
4047
else if (T->isArrayType())
4048
return ExprError(Diag(ConditionVar->getLocation(),
4049
diag::err_invalid_use_of_array_type)
4050
<< ConditionVar->getSourceRange());
4051
4052
ExprResult Condition = BuildDeclRefExpr(
4053
ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
4054
ConditionVar->getLocation());
4055
4056
switch (CK) {
4057
case ConditionKind::Boolean:
4058
return CheckBooleanCondition(StmtLoc, Condition.get());
4059
4060
case ConditionKind::ConstexprIf:
4061
return CheckBooleanCondition(StmtLoc, Condition.get(), true);
4062
4063
case ConditionKind::Switch:
4064
return CheckSwitchCondition(StmtLoc, Condition.get());
4065
}
4066
4067
llvm_unreachable("unexpected condition kind");
4068
}
4069
4070
ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4071
// C++11 6.4p4:
4072
// The value of a condition that is an initialized declaration in a statement
4073
// other than a switch statement is the value of the declared variable
4074
// implicitly converted to type bool. If that conversion is ill-formed, the
4075
// program is ill-formed.
4076
// The value of a condition that is an expression is the value of the
4077
// expression, implicitly converted to bool.
4078
//
4079
// C++23 8.5.2p2
4080
// If the if statement is of the form if constexpr, the value of the condition
4081
// is contextually converted to bool and the converted expression shall be
4082
// a constant expression.
4083
//
4084
4085
ExprResult E = PerformContextuallyConvertToBool(CondExpr);
4086
if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4087
return E;
4088
4089
// FIXME: Return this value to the caller so they don't need to recompute it.
4090
llvm::APSInt Cond;
4091
E = VerifyIntegerConstantExpression(
4092
E.get(), &Cond,
4093
diag::err_constexpr_if_condition_expression_is_not_constant);
4094
return E;
4095
}
4096
4097
bool
4098
Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
4099
// Look inside the implicit cast, if it exists.
4100
if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
4101
From = Cast->getSubExpr();
4102
4103
// A string literal (2.13.4) that is not a wide string literal can
4104
// be converted to an rvalue of type "pointer to char"; a wide
4105
// string literal can be converted to an rvalue of type "pointer
4106
// to wchar_t" (C++ 4.2p2).
4107
if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4108
if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4109
if (const BuiltinType *ToPointeeType
4110
= ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4111
// This conversion is considered only when there is an
4112
// explicit appropriate pointer target type (C++ 4.2p2).
4113
if (!ToPtrType->getPointeeType().hasQualifiers()) {
4114
switch (StrLit->getKind()) {
4115
case StringLiteralKind::UTF8:
4116
case StringLiteralKind::UTF16:
4117
case StringLiteralKind::UTF32:
4118
// We don't allow UTF literals to be implicitly converted
4119
break;
4120
case StringLiteralKind::Ordinary:
4121
return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4122
ToPointeeType->getKind() == BuiltinType::Char_S);
4123
case StringLiteralKind::Wide:
4124
return Context.typesAreCompatible(Context.getWideCharType(),
4125
QualType(ToPointeeType, 0));
4126
case StringLiteralKind::Unevaluated:
4127
assert(false && "Unevaluated string literal in expression");
4128
break;
4129
}
4130
}
4131
}
4132
4133
return false;
4134
}
4135
4136
static ExprResult BuildCXXCastArgument(Sema &S,
4137
SourceLocation CastLoc,
4138
QualType Ty,
4139
CastKind Kind,
4140
CXXMethodDecl *Method,
4141
DeclAccessPair FoundDecl,
4142
bool HadMultipleCandidates,
4143
Expr *From) {
4144
switch (Kind) {
4145
default: llvm_unreachable("Unhandled cast kind!");
4146
case CK_ConstructorConversion: {
4147
CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
4148
SmallVector<Expr*, 8> ConstructorArgs;
4149
4150
if (S.RequireNonAbstractType(CastLoc, Ty,
4151
diag::err_allocation_of_abstract_type))
4152
return ExprError();
4153
4154
if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4155
ConstructorArgs))
4156
return ExprError();
4157
4158
S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4159
InitializedEntity::InitializeTemporary(Ty));
4160
if (S.DiagnoseUseOfDecl(Method, CastLoc))
4161
return ExprError();
4162
4163
ExprResult Result = S.BuildCXXConstructExpr(
4164
CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4165
ConstructorArgs, HadMultipleCandidates,
4166
/*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4167
CXXConstructionKind::Complete, SourceRange());
4168
if (Result.isInvalid())
4169
return ExprError();
4170
4171
return S.MaybeBindToTemporary(Result.getAs<Expr>());
4172
}
4173
4174
case CK_UserDefinedConversion: {
4175
assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4176
4177
S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4178
if (S.DiagnoseUseOfDecl(Method, CastLoc))
4179
return ExprError();
4180
4181
// Create an implicit call expr that calls it.
4182
CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4183
ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4184
HadMultipleCandidates);
4185
if (Result.isInvalid())
4186
return ExprError();
4187
// Record usage of conversion in an implicit cast.
4188
Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4189
CK_UserDefinedConversion, Result.get(),
4190
nullptr, Result.get()->getValueKind(),
4191
S.CurFPFeatureOverrides());
4192
4193
return S.MaybeBindToTemporary(Result.get());
4194
}
4195
}
4196
}
4197
4198
ExprResult
4199
Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4200
const ImplicitConversionSequence &ICS,
4201
AssignmentAction Action,
4202
CheckedConversionKind CCK) {
4203
// C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4204
if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp &&
4205
!From->getType()->isRecordType())
4206
return From;
4207
4208
switch (ICS.getKind()) {
4209
case ImplicitConversionSequence::StandardConversion: {
4210
ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4211
Action, CCK);
4212
if (Res.isInvalid())
4213
return ExprError();
4214
From = Res.get();
4215
break;
4216
}
4217
4218
case ImplicitConversionSequence::UserDefinedConversion: {
4219
4220
FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
4221
CastKind CastKind;
4222
QualType BeforeToType;
4223
assert(FD && "no conversion function for user-defined conversion seq");
4224
if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4225
CastKind = CK_UserDefinedConversion;
4226
4227
// If the user-defined conversion is specified by a conversion function,
4228
// the initial standard conversion sequence converts the source type to
4229
// the implicit object parameter of the conversion function.
4230
BeforeToType = Context.getTagDeclType(Conv->getParent());
4231
} else {
4232
const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4233
CastKind = CK_ConstructorConversion;
4234
// Do no conversion if dealing with ... for the first conversion.
4235
if (!ICS.UserDefined.EllipsisConversion) {
4236
// If the user-defined conversion is specified by a constructor, the
4237
// initial standard conversion sequence converts the source type to
4238
// the type required by the argument of the constructor
4239
BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4240
}
4241
}
4242
// Watch out for ellipsis conversion.
4243
if (!ICS.UserDefined.EllipsisConversion) {
4244
ExprResult Res =
4245
PerformImplicitConversion(From, BeforeToType,
4246
ICS.UserDefined.Before, AA_Converting,
4247
CCK);
4248
if (Res.isInvalid())
4249
return ExprError();
4250
From = Res.get();
4251
}
4252
4253
ExprResult CastArg = BuildCXXCastArgument(
4254
*this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4255
cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4256
ICS.UserDefined.HadMultipleCandidates, From);
4257
4258
if (CastArg.isInvalid())
4259
return ExprError();
4260
4261
From = CastArg.get();
4262
4263
// C++ [over.match.oper]p7:
4264
// [...] the second standard conversion sequence of a user-defined
4265
// conversion sequence is not applied.
4266
if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp)
4267
return From;
4268
4269
return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4270
AA_Converting, CCK);
4271
}
4272
4273
case ImplicitConversionSequence::AmbiguousConversion:
4274
ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4275
PDiag(diag::err_typecheck_ambiguous_condition)
4276
<< From->getSourceRange());
4277
return ExprError();
4278
4279
case ImplicitConversionSequence::EllipsisConversion:
4280
case ImplicitConversionSequence::StaticObjectArgumentConversion:
4281
llvm_unreachable("bad conversion");
4282
4283
case ImplicitConversionSequence::BadConversion:
4284
Sema::AssignConvertType ConvTy =
4285
CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4286
bool Diagnosed = DiagnoseAssignmentResult(
4287
ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
4288
ToType, From->getType(), From, Action);
4289
assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4290
return ExprError();
4291
}
4292
4293
// Everything went well.
4294
return From;
4295
}
4296
4297
// adjustVectorType - Compute the intermediate cast type casting elements of the
4298
// from type to the elements of the to type without resizing the vector.
4299
static QualType adjustVectorType(ASTContext &Context, QualType FromTy,
4300
QualType ToType, QualType *ElTy = nullptr) {
4301
auto *ToVec = ToType->castAs<VectorType>();
4302
QualType ElType = ToVec->getElementType();
4303
if (ElTy)
4304
*ElTy = ElType;
4305
if (!FromTy->isVectorType())
4306
return ElType;
4307
auto *FromVec = FromTy->castAs<VectorType>();
4308
return Context.getExtVectorType(ElType, FromVec->getNumElements());
4309
}
4310
4311
ExprResult
4312
Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4313
const StandardConversionSequence& SCS,
4314
AssignmentAction Action,
4315
CheckedConversionKind CCK) {
4316
bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||
4317
CCK == CheckedConversionKind::FunctionalCast);
4318
4319
// Overall FIXME: we are recomputing too many types here and doing far too
4320
// much extra work. What this means is that we need to keep track of more
4321
// information that is computed when we try the implicit conversion initially,
4322
// so that we don't need to recompute anything here.
4323
QualType FromType = From->getType();
4324
4325
if (SCS.CopyConstructor) {
4326
// FIXME: When can ToType be a reference type?
4327
assert(!ToType->isReferenceType());
4328
if (SCS.Second == ICK_Derived_To_Base) {
4329
SmallVector<Expr*, 8> ConstructorArgs;
4330
if (CompleteConstructorCall(
4331
cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4332
/*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4333
return ExprError();
4334
return BuildCXXConstructExpr(
4335
/*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4336
SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs,
4337
/*HadMultipleCandidates*/ false,
4338
/*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4339
CXXConstructionKind::Complete, SourceRange());
4340
}
4341
return BuildCXXConstructExpr(
4342
/*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4343
SCS.FoundCopyConstructor, SCS.CopyConstructor, From,
4344
/*HadMultipleCandidates*/ false,
4345
/*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4346
CXXConstructionKind::Complete, SourceRange());
4347
}
4348
4349
// Resolve overloaded function references.
4350
if (Context.hasSameType(FromType, Context.OverloadTy)) {
4351
DeclAccessPair Found;
4352
FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
4353
true, Found);
4354
if (!Fn)
4355
return ExprError();
4356
4357
if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4358
return ExprError();
4359
4360
ExprResult Res = FixOverloadedFunctionReference(From, Found, Fn);
4361
if (Res.isInvalid())
4362
return ExprError();
4363
4364
// We might get back another placeholder expression if we resolved to a
4365
// builtin.
4366
Res = CheckPlaceholderExpr(Res.get());
4367
if (Res.isInvalid())
4368
return ExprError();
4369
4370
From = Res.get();
4371
FromType = From->getType();
4372
}
4373
4374
// If we're converting to an atomic type, first convert to the corresponding
4375
// non-atomic type.
4376
QualType ToAtomicType;
4377
if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4378
ToAtomicType = ToType;
4379
ToType = ToAtomic->getValueType();
4380
}
4381
4382
QualType InitialFromType = FromType;
4383
// Perform the first implicit conversion.
4384
switch (SCS.First) {
4385
case ICK_Identity:
4386
if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4387
FromType = FromAtomic->getValueType().getUnqualifiedType();
4388
From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4389
From, /*BasePath=*/nullptr, VK_PRValue,
4390
FPOptionsOverride());
4391
}
4392
break;
4393
4394
case ICK_Lvalue_To_Rvalue: {
4395
assert(From->getObjectKind() != OK_ObjCProperty);
4396
ExprResult FromRes = DefaultLvalueConversion(From);
4397
if (FromRes.isInvalid())
4398
return ExprError();
4399
4400
From = FromRes.get();
4401
FromType = From->getType();
4402
break;
4403
}
4404
4405
case ICK_Array_To_Pointer:
4406
FromType = Context.getArrayDecayedType(FromType);
4407
From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4408
/*BasePath=*/nullptr, CCK)
4409
.get();
4410
break;
4411
4412
case ICK_HLSL_Array_RValue:
4413
FromType = Context.getArrayParameterType(FromType);
4414
From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue,
4415
/*BasePath=*/nullptr, CCK)
4416
.get();
4417
break;
4418
4419
case ICK_Function_To_Pointer:
4420
FromType = Context.getPointerType(FromType);
4421
From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4422
VK_PRValue, /*BasePath=*/nullptr, CCK)
4423
.get();
4424
break;
4425
4426
default:
4427
llvm_unreachable("Improper first standard conversion");
4428
}
4429
4430
// Perform the second implicit conversion
4431
switch (SCS.Second) {
4432
case ICK_Identity:
4433
// C++ [except.spec]p5:
4434
// [For] assignment to and initialization of pointers to functions,
4435
// pointers to member functions, and references to functions: the
4436
// target entity shall allow at least the exceptions allowed by the
4437
// source value in the assignment or initialization.
4438
switch (Action) {
4439
case AA_Assigning:
4440
case AA_Initializing:
4441
// Note, function argument passing and returning are initialization.
4442
case AA_Passing:
4443
case AA_Returning:
4444
case AA_Sending:
4445
case AA_Passing_CFAudited:
4446
if (CheckExceptionSpecCompatibility(From, ToType))
4447
return ExprError();
4448
break;
4449
4450
case AA_Casting:
4451
case AA_Converting:
4452
// Casts and implicit conversions are not initialization, so are not
4453
// checked for exception specification mismatches.
4454
break;
4455
}
4456
// Nothing else to do.
4457
break;
4458
4459
case ICK_Integral_Promotion:
4460
case ICK_Integral_Conversion: {
4461
QualType ElTy = ToType;
4462
QualType StepTy = ToType;
4463
if (ToType->isVectorType())
4464
StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);
4465
if (ElTy->isBooleanType()) {
4466
assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4467
SCS.Second == ICK_Integral_Promotion &&
4468
"only enums with fixed underlying type can promote to bool");
4469
From = ImpCastExprToType(From, StepTy, CK_IntegralToBoolean, VK_PRValue,
4470
/*BasePath=*/nullptr, CCK)
4471
.get();
4472
} else {
4473
From = ImpCastExprToType(From, StepTy, CK_IntegralCast, VK_PRValue,
4474
/*BasePath=*/nullptr, CCK)
4475
.get();
4476
}
4477
break;
4478
}
4479
4480
case ICK_Floating_Promotion:
4481
case ICK_Floating_Conversion: {
4482
QualType StepTy = ToType;
4483
if (ToType->isVectorType())
4484
StepTy = adjustVectorType(Context, FromType, ToType);
4485
From = ImpCastExprToType(From, StepTy, CK_FloatingCast, VK_PRValue,
4486
/*BasePath=*/nullptr, CCK)
4487
.get();
4488
break;
4489
}
4490
4491
case ICK_Complex_Promotion:
4492
case ICK_Complex_Conversion: {
4493
QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4494
QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4495
CastKind CK;
4496
if (FromEl->isRealFloatingType()) {
4497
if (ToEl->isRealFloatingType())
4498
CK = CK_FloatingComplexCast;
4499
else
4500
CK = CK_FloatingComplexToIntegralComplex;
4501
} else if (ToEl->isRealFloatingType()) {
4502
CK = CK_IntegralComplexToFloatingComplex;
4503
} else {
4504
CK = CK_IntegralComplexCast;
4505
}
4506
From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4507
CCK)
4508
.get();
4509
break;
4510
}
4511
4512
case ICK_Floating_Integral: {
4513
QualType ElTy = ToType;
4514
QualType StepTy = ToType;
4515
if (ToType->isVectorType())
4516
StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);
4517
if (ElTy->isRealFloatingType())
4518
From = ImpCastExprToType(From, StepTy, CK_IntegralToFloating, VK_PRValue,
4519
/*BasePath=*/nullptr, CCK)
4520
.get();
4521
else
4522
From = ImpCastExprToType(From, StepTy, CK_FloatingToIntegral, VK_PRValue,
4523
/*BasePath=*/nullptr, CCK)
4524
.get();
4525
break;
4526
}
4527
4528
case ICK_Fixed_Point_Conversion:
4529
assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&
4530
"Attempting implicit fixed point conversion without a fixed "
4531
"point operand");
4532
if (FromType->isFloatingType())
4533
From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint,
4534
VK_PRValue,
4535
/*BasePath=*/nullptr, CCK).get();
4536
else if (ToType->isFloatingType())
4537
From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating,
4538
VK_PRValue,
4539
/*BasePath=*/nullptr, CCK).get();
4540
else if (FromType->isIntegralType(Context))
4541
From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint,
4542
VK_PRValue,
4543
/*BasePath=*/nullptr, CCK).get();
4544
else if (ToType->isIntegralType(Context))
4545
From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral,
4546
VK_PRValue,
4547
/*BasePath=*/nullptr, CCK).get();
4548
else if (ToType->isBooleanType())
4549
From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean,
4550
VK_PRValue,
4551
/*BasePath=*/nullptr, CCK).get();
4552
else
4553
From = ImpCastExprToType(From, ToType, CK_FixedPointCast,
4554
VK_PRValue,
4555
/*BasePath=*/nullptr, CCK).get();
4556
break;
4557
4558
case ICK_Compatible_Conversion:
4559
From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4560
/*BasePath=*/nullptr, CCK).get();
4561
break;
4562
4563
case ICK_Writeback_Conversion:
4564
case ICK_Pointer_Conversion: {
4565
if (SCS.IncompatibleObjC && Action != AA_Casting) {
4566
// Diagnose incompatible Objective-C conversions
4567
if (Action == AA_Initializing || Action == AA_Assigning)
4568
Diag(From->getBeginLoc(),
4569
diag::ext_typecheck_convert_incompatible_pointer)
4570
<< ToType << From->getType() << Action << From->getSourceRange()
4571
<< 0;
4572
else
4573
Diag(From->getBeginLoc(),
4574
diag::ext_typecheck_convert_incompatible_pointer)
4575
<< From->getType() << ToType << Action << From->getSourceRange()
4576
<< 0;
4577
4578
if (From->getType()->isObjCObjectPointerType() &&
4579
ToType->isObjCObjectPointerType())
4580
ObjC().EmitRelatedResultTypeNote(From);
4581
} else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4582
!ObjC().CheckObjCARCUnavailableWeakConversion(ToType,
4583
From->getType())) {
4584
if (Action == AA_Initializing)
4585
Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4586
else
4587
Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4588
<< (Action == AA_Casting) << From->getType() << ToType
4589
<< From->getSourceRange();
4590
}
4591
4592
// Defer address space conversion to the third conversion.
4593
QualType FromPteeType = From->getType()->getPointeeType();
4594
QualType ToPteeType = ToType->getPointeeType();
4595
QualType NewToType = ToType;
4596
if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4597
FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4598
NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4599
NewToType = Context.getAddrSpaceQualType(NewToType,
4600
FromPteeType.getAddressSpace());
4601
if (ToType->isObjCObjectPointerType())
4602
NewToType = Context.getObjCObjectPointerType(NewToType);
4603
else if (ToType->isBlockPointerType())
4604
NewToType = Context.getBlockPointerType(NewToType);
4605
else
4606
NewToType = Context.getPointerType(NewToType);
4607
}
4608
4609
CastKind Kind;
4610
CXXCastPath BasePath;
4611
if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4612
return ExprError();
4613
4614
// Make sure we extend blocks if necessary.
4615
// FIXME: doing this here is really ugly.
4616
if (Kind == CK_BlockPointerToObjCPointerCast) {
4617
ExprResult E = From;
4618
(void)ObjC().PrepareCastToObjCObjectPointer(E);
4619
From = E.get();
4620
}
4621
if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4622
ObjC().CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4623
From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4624
.get();
4625
break;
4626
}
4627
4628
case ICK_Pointer_Member: {
4629
CastKind Kind;
4630
CXXCastPath BasePath;
4631
if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4632
return ExprError();
4633
if (CheckExceptionSpecCompatibility(From, ToType))
4634
return ExprError();
4635
4636
// We may not have been able to figure out what this member pointer resolved
4637
// to up until this exact point. Attempt to lock-in it's inheritance model.
4638
if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4639
(void)isCompleteType(From->getExprLoc(), From->getType());
4640
(void)isCompleteType(From->getExprLoc(), ToType);
4641
}
4642
4643
From =
4644
ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
4645
break;
4646
}
4647
4648
case ICK_Boolean_Conversion: {
4649
// Perform half-to-boolean conversion via float.
4650
if (From->getType()->isHalfType()) {
4651
From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4652
FromType = Context.FloatTy;
4653
}
4654
QualType ElTy = FromType;
4655
QualType StepTy = ToType;
4656
if (FromType->isVectorType()) {
4657
if (getLangOpts().HLSL)
4658
StepTy = adjustVectorType(Context, FromType, ToType);
4659
ElTy = FromType->castAs<VectorType>()->getElementType();
4660
}
4661
4662
From = ImpCastExprToType(From, StepTy, ScalarTypeToBooleanCastKind(ElTy),
4663
VK_PRValue,
4664
/*BasePath=*/nullptr, CCK)
4665
.get();
4666
break;
4667
}
4668
4669
case ICK_Derived_To_Base: {
4670
CXXCastPath BasePath;
4671
if (CheckDerivedToBaseConversion(
4672
From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4673
From->getSourceRange(), &BasePath, CStyle))
4674
return ExprError();
4675
4676
From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4677
CK_DerivedToBase, From->getValueKind(),
4678
&BasePath, CCK).get();
4679
break;
4680
}
4681
4682
case ICK_Vector_Conversion:
4683
From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4684
/*BasePath=*/nullptr, CCK)
4685
.get();
4686
break;
4687
4688
case ICK_SVE_Vector_Conversion:
4689
case ICK_RVV_Vector_Conversion:
4690
From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4691
/*BasePath=*/nullptr, CCK)
4692
.get();
4693
break;
4694
4695
case ICK_Vector_Splat: {
4696
// Vector splat from any arithmetic type to a vector.
4697
Expr *Elem = prepareVectorSplat(ToType, From).get();
4698
From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4699
/*BasePath=*/nullptr, CCK)
4700
.get();
4701
break;
4702
}
4703
4704
case ICK_Complex_Real:
4705
// Case 1. x -> _Complex y
4706
if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4707
QualType ElType = ToComplex->getElementType();
4708
bool isFloatingComplex = ElType->isRealFloatingType();
4709
4710
// x -> y
4711
if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4712
// do nothing
4713
} else if (From->getType()->isRealFloatingType()) {
4714
From = ImpCastExprToType(From, ElType,
4715
isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4716
} else {
4717
assert(From->getType()->isIntegerType());
4718
From = ImpCastExprToType(From, ElType,
4719
isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4720
}
4721
// y -> _Complex y
4722
From = ImpCastExprToType(From, ToType,
4723
isFloatingComplex ? CK_FloatingRealToComplex
4724
: CK_IntegralRealToComplex).get();
4725
4726
// Case 2. _Complex x -> y
4727
} else {
4728
auto *FromComplex = From->getType()->castAs<ComplexType>();
4729
QualType ElType = FromComplex->getElementType();
4730
bool isFloatingComplex = ElType->isRealFloatingType();
4731
4732
// _Complex x -> x
4733
From = ImpCastExprToType(From, ElType,
4734
isFloatingComplex ? CK_FloatingComplexToReal
4735
: CK_IntegralComplexToReal,
4736
VK_PRValue, /*BasePath=*/nullptr, CCK)
4737
.get();
4738
4739
// x -> y
4740
if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4741
// do nothing
4742
} else if (ToType->isRealFloatingType()) {
4743
From = ImpCastExprToType(From, ToType,
4744
isFloatingComplex ? CK_FloatingCast
4745
: CK_IntegralToFloating,
4746
VK_PRValue, /*BasePath=*/nullptr, CCK)
4747
.get();
4748
} else {
4749
assert(ToType->isIntegerType());
4750
From = ImpCastExprToType(From, ToType,
4751
isFloatingComplex ? CK_FloatingToIntegral
4752
: CK_IntegralCast,
4753
VK_PRValue, /*BasePath=*/nullptr, CCK)
4754
.get();
4755
}
4756
}
4757
break;
4758
4759
case ICK_Block_Pointer_Conversion: {
4760
LangAS AddrSpaceL =
4761
ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4762
LangAS AddrSpaceR =
4763
FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4764
assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4765
"Invalid cast");
4766
CastKind Kind =
4767
AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4768
From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4769
VK_PRValue, /*BasePath=*/nullptr, CCK)
4770
.get();
4771
break;
4772
}
4773
4774
case ICK_TransparentUnionConversion: {
4775
ExprResult FromRes = From;
4776
Sema::AssignConvertType ConvTy =
4777
CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4778
if (FromRes.isInvalid())
4779
return ExprError();
4780
From = FromRes.get();
4781
assert ((ConvTy == Sema::Compatible) &&
4782
"Improper transparent union conversion");
4783
(void)ConvTy;
4784
break;
4785
}
4786
4787
case ICK_Zero_Event_Conversion:
4788
case ICK_Zero_Queue_Conversion:
4789
From = ImpCastExprToType(From, ToType,
4790
CK_ZeroToOCLOpaqueType,
4791
From->getValueKind()).get();
4792
break;
4793
4794
case ICK_Lvalue_To_Rvalue:
4795
case ICK_Array_To_Pointer:
4796
case ICK_Function_To_Pointer:
4797
case ICK_Function_Conversion:
4798
case ICK_Qualification:
4799
case ICK_Num_Conversion_Kinds:
4800
case ICK_C_Only_Conversion:
4801
case ICK_Incompatible_Pointer_Conversion:
4802
case ICK_HLSL_Array_RValue:
4803
case ICK_HLSL_Vector_Truncation:
4804
case ICK_HLSL_Vector_Splat:
4805
llvm_unreachable("Improper second standard conversion");
4806
}
4807
4808
if (SCS.Dimension != ICK_Identity) {
4809
// If SCS.Element is not ICK_Identity the To and From types must be HLSL
4810
// vectors or matrices.
4811
4812
// TODO: Support HLSL matrices.
4813
assert((!From->getType()->isMatrixType() && !ToType->isMatrixType()) &&
4814
"Dimension conversion for matrix types is not implemented yet.");
4815
assert(ToType->isVectorType() &&
4816
"Dimension conversion is only supported for vector types.");
4817
switch (SCS.Dimension) {
4818
case ICK_HLSL_Vector_Splat: {
4819
// Vector splat from any arithmetic type to a vector.
4820
Expr *Elem = prepareVectorSplat(ToType, From).get();
4821
From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4822
/*BasePath=*/nullptr, CCK)
4823
.get();
4824
break;
4825
}
4826
case ICK_HLSL_Vector_Truncation: {
4827
// Note: HLSL built-in vectors are ExtVectors. Since this truncates a
4828
// vector to a smaller vector, this can only operate on arguments where
4829
// the source and destination types are ExtVectors.
4830
assert(From->getType()->isExtVectorType() && ToType->isExtVectorType() &&
4831
"HLSL vector truncation should only apply to ExtVectors");
4832
auto *FromVec = From->getType()->castAs<VectorType>();
4833
auto *ToVec = ToType->castAs<VectorType>();
4834
QualType ElType = FromVec->getElementType();
4835
QualType TruncTy =
4836
Context.getExtVectorType(ElType, ToVec->getNumElements());
4837
From = ImpCastExprToType(From, TruncTy, CK_HLSLVectorTruncation,
4838
From->getValueKind())
4839
.get();
4840
break;
4841
}
4842
case ICK_Identity:
4843
default:
4844
llvm_unreachable("Improper element standard conversion");
4845
}
4846
}
4847
4848
switch (SCS.Third) {
4849
case ICK_Identity:
4850
// Nothing to do.
4851
break;
4852
4853
case ICK_Function_Conversion:
4854
// If both sides are functions (or pointers/references to them), there could
4855
// be incompatible exception declarations.
4856
if (CheckExceptionSpecCompatibility(From, ToType))
4857
return ExprError();
4858
4859
From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
4860
/*BasePath=*/nullptr, CCK)
4861
.get();
4862
break;
4863
4864
case ICK_Qualification: {
4865
ExprValueKind VK = From->getValueKind();
4866
CastKind CK = CK_NoOp;
4867
4868
if (ToType->isReferenceType() &&
4869
ToType->getPointeeType().getAddressSpace() !=
4870
From->getType().getAddressSpace())
4871
CK = CK_AddressSpaceConversion;
4872
4873
if (ToType->isPointerType() &&
4874
ToType->getPointeeType().getAddressSpace() !=
4875
From->getType()->getPointeeType().getAddressSpace())
4876
CK = CK_AddressSpaceConversion;
4877
4878
if (!isCast(CCK) &&
4879
!ToType->getPointeeType().getQualifiers().hasUnaligned() &&
4880
From->getType()->getPointeeType().getQualifiers().hasUnaligned()) {
4881
Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)
4882
<< InitialFromType << ToType;
4883
}
4884
4885
From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4886
/*BasePath=*/nullptr, CCK)
4887
.get();
4888
4889
if (SCS.DeprecatedStringLiteralToCharPtr &&
4890
!getLangOpts().WritableStrings) {
4891
Diag(From->getBeginLoc(),
4892
getLangOpts().CPlusPlus11
4893
? diag::ext_deprecated_string_literal_conversion
4894
: diag::warn_deprecated_string_literal_conversion)
4895
<< ToType.getNonReferenceType();
4896
}
4897
4898
break;
4899
}
4900
4901
default:
4902
llvm_unreachable("Improper third standard conversion");
4903
}
4904
4905
// If this conversion sequence involved a scalar -> atomic conversion, perform
4906
// that conversion now.
4907
if (!ToAtomicType.isNull()) {
4908
assert(Context.hasSameType(
4909
ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4910
From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4911
VK_PRValue, nullptr, CCK)
4912
.get();
4913
}
4914
4915
// Materialize a temporary if we're implicitly converting to a reference
4916
// type. This is not required by the C++ rules but is necessary to maintain
4917
// AST invariants.
4918
if (ToType->isReferenceType() && From->isPRValue()) {
4919
ExprResult Res = TemporaryMaterializationConversion(From);
4920
if (Res.isInvalid())
4921
return ExprError();
4922
From = Res.get();
4923
}
4924
4925
// If this conversion sequence succeeded and involved implicitly converting a
4926
// _Nullable type to a _Nonnull one, complain.
4927
if (!isCast(CCK))
4928
diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4929
From->getBeginLoc());
4930
4931
return From;
4932
}
4933
4934
/// Checks that type T is not a VLA.
4935
///
4936
/// @returns @c true if @p T is VLA and a diagnostic was emitted,
4937
/// @c false otherwise.
4938
static bool DiagnoseVLAInCXXTypeTrait(Sema &S, const TypeSourceInfo *T,
4939
clang::tok::TokenKind TypeTraitID) {
4940
if (!T->getType()->isVariableArrayType())
4941
return false;
4942
4943
S.Diag(T->getTypeLoc().getBeginLoc(), diag::err_vla_unsupported)
4944
<< 1 << TypeTraitID;
4945
return true;
4946
}
4947
4948
/// Check the completeness of a type in a unary type trait.
4949
///
4950
/// If the particular type trait requires a complete type, tries to complete
4951
/// it. If completing the type fails, a diagnostic is emitted and false
4952
/// returned. If completing the type succeeds or no completion was required,
4953
/// returns true.
4954
static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4955
SourceLocation Loc,
4956
QualType ArgTy) {
4957
// C++0x [meta.unary.prop]p3:
4958
// For all of the class templates X declared in this Clause, instantiating
4959
// that template with a template argument that is a class template
4960
// specialization may result in the implicit instantiation of the template
4961
// argument if and only if the semantics of X require that the argument
4962
// must be a complete type.
4963
// We apply this rule to all the type trait expressions used to implement
4964
// these class templates. We also try to follow any GCC documented behavior
4965
// in these expressions to ensure portability of standard libraries.
4966
switch (UTT) {
4967
default: llvm_unreachable("not a UTT");
4968
// is_complete_type somewhat obviously cannot require a complete type.
4969
case UTT_IsCompleteType:
4970
// Fall-through
4971
4972
// These traits are modeled on the type predicates in C++0x
4973
// [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4974
// requiring a complete type, as whether or not they return true cannot be
4975
// impacted by the completeness of the type.
4976
case UTT_IsVoid:
4977
case UTT_IsIntegral:
4978
case UTT_IsFloatingPoint:
4979
case UTT_IsArray:
4980
case UTT_IsBoundedArray:
4981
case UTT_IsPointer:
4982
case UTT_IsNullPointer:
4983
case UTT_IsReferenceable:
4984
case UTT_IsLvalueReference:
4985
case UTT_IsRvalueReference:
4986
case UTT_IsMemberFunctionPointer:
4987
case UTT_IsMemberObjectPointer:
4988
case UTT_IsEnum:
4989
case UTT_IsScopedEnum:
4990
case UTT_IsUnion:
4991
case UTT_IsClass:
4992
case UTT_IsFunction:
4993
case UTT_IsReference:
4994
case UTT_IsArithmetic:
4995
case UTT_IsFundamental:
4996
case UTT_IsObject:
4997
case UTT_IsScalar:
4998
case UTT_IsCompound:
4999
case UTT_IsMemberPointer:
5000
// Fall-through
5001
5002
// These traits are modeled on type predicates in C++0x [meta.unary.prop]
5003
// which requires some of its traits to have the complete type. However,
5004
// the completeness of the type cannot impact these traits' semantics, and
5005
// so they don't require it. This matches the comments on these traits in
5006
// Table 49.
5007
case UTT_IsConst:
5008
case UTT_IsVolatile:
5009
case UTT_IsSigned:
5010
case UTT_IsUnboundedArray:
5011
case UTT_IsUnsigned:
5012
5013
// This type trait always returns false, checking the type is moot.
5014
case UTT_IsInterfaceClass:
5015
return true;
5016
5017
// C++14 [meta.unary.prop]:
5018
// If T is a non-union class type, T shall be a complete type.
5019
case UTT_IsEmpty:
5020
case UTT_IsPolymorphic:
5021
case UTT_IsAbstract:
5022
if (const auto *RD = ArgTy->getAsCXXRecordDecl())
5023
if (!RD->isUnion())
5024
return !S.RequireCompleteType(
5025
Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5026
return true;
5027
5028
// C++14 [meta.unary.prop]:
5029
// If T is a class type, T shall be a complete type.
5030
case UTT_IsFinal:
5031
case UTT_IsSealed:
5032
if (ArgTy->getAsCXXRecordDecl())
5033
return !S.RequireCompleteType(
5034
Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5035
return true;
5036
5037
// LWG3823: T shall be an array type, a complete type, or cv void.
5038
case UTT_IsAggregate:
5039
if (ArgTy->isArrayType() || ArgTy->isVoidType())
5040
return true;
5041
5042
return !S.RequireCompleteType(
5043
Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5044
5045
// C++1z [meta.unary.prop]:
5046
// remove_all_extents_t<T> shall be a complete type or cv void.
5047
case UTT_IsTrivial:
5048
case UTT_IsTriviallyCopyable:
5049
case UTT_IsStandardLayout:
5050
case UTT_IsPOD:
5051
case UTT_IsLiteral:
5052
case UTT_IsBitwiseCloneable:
5053
// By analogy, is_trivially_relocatable and is_trivially_equality_comparable
5054
// impose the same constraints.
5055
case UTT_IsTriviallyRelocatable:
5056
case UTT_IsTriviallyEqualityComparable:
5057
case UTT_CanPassInRegs:
5058
// Per the GCC type traits documentation, T shall be a complete type, cv void,
5059
// or an array of unknown bound. But GCC actually imposes the same constraints
5060
// as above.
5061
case UTT_HasNothrowAssign:
5062
case UTT_HasNothrowMoveAssign:
5063
case UTT_HasNothrowConstructor:
5064
case UTT_HasNothrowCopy:
5065
case UTT_HasTrivialAssign:
5066
case UTT_HasTrivialMoveAssign:
5067
case UTT_HasTrivialDefaultConstructor:
5068
case UTT_HasTrivialMoveConstructor:
5069
case UTT_HasTrivialCopy:
5070
case UTT_HasTrivialDestructor:
5071
case UTT_HasVirtualDestructor:
5072
// has_unique_object_representations<T> when T is an array is defined in terms
5073
// of has_unique_object_representations<remove_all_extents_t<T>>, so the base
5074
// type needs to be complete even if the type is an incomplete array type.
5075
case UTT_HasUniqueObjectRepresentations:
5076
ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
5077
[[fallthrough]];
5078
5079
// C++1z [meta.unary.prop]:
5080
// T shall be a complete type, cv void, or an array of unknown bound.
5081
case UTT_IsDestructible:
5082
case UTT_IsNothrowDestructible:
5083
case UTT_IsTriviallyDestructible:
5084
if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
5085
return true;
5086
5087
return !S.RequireCompleteType(
5088
Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5089
}
5090
}
5091
5092
static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
5093
Sema &Self, SourceLocation KeyLoc, ASTContext &C,
5094
bool (CXXRecordDecl::*HasTrivial)() const,
5095
bool (CXXRecordDecl::*HasNonTrivial)() const,
5096
bool (CXXMethodDecl::*IsDesiredOp)() const)
5097
{
5098
CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5099
if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
5100
return true;
5101
5102
DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
5103
DeclarationNameInfo NameInfo(Name, KeyLoc);
5104
LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
5105
if (Self.LookupQualifiedName(Res, RD)) {
5106
bool FoundOperator = false;
5107
Res.suppressDiagnostics();
5108
for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
5109
Op != OpEnd; ++Op) {
5110
if (isa<FunctionTemplateDecl>(*Op))
5111
continue;
5112
5113
CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
5114
if((Operator->*IsDesiredOp)()) {
5115
FoundOperator = true;
5116
auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
5117
CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5118
if (!CPT || !CPT->isNothrow())
5119
return false;
5120
}
5121
}
5122
return FoundOperator;
5123
}
5124
return false;
5125
}
5126
5127
static bool HasNonDeletedDefaultedEqualityComparison(Sema &S,
5128
const CXXRecordDecl *Decl,
5129
SourceLocation KeyLoc) {
5130
if (Decl->isUnion())
5131
return false;
5132
if (Decl->isLambda())
5133
return Decl->isCapturelessLambda();
5134
5135
{
5136
EnterExpressionEvaluationContext UnevaluatedContext(
5137
S, Sema::ExpressionEvaluationContext::Unevaluated);
5138
Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5139
Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
5140
5141
// const ClassT& obj;
5142
OpaqueValueExpr Operand(
5143
KeyLoc,
5144
Decl->getTypeForDecl()->getCanonicalTypeUnqualified().withConst(),
5145
ExprValueKind::VK_LValue);
5146
UnresolvedSet<16> Functions;
5147
// obj == obj;
5148
S.LookupBinOp(S.TUScope, {}, BinaryOperatorKind::BO_EQ, Functions);
5149
5150
auto Result = S.CreateOverloadedBinOp(KeyLoc, BinaryOperatorKind::BO_EQ,
5151
Functions, &Operand, &Operand);
5152
if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5153
return false;
5154
5155
const auto *CallExpr = dyn_cast<CXXOperatorCallExpr>(Result.get());
5156
if (!CallExpr)
5157
return false;
5158
const auto *Callee = CallExpr->getDirectCallee();
5159
auto ParamT = Callee->getParamDecl(0)->getType();
5160
if (!Callee->isDefaulted())
5161
return false;
5162
if (!ParamT->isReferenceType() && !Decl->isTriviallyCopyable())
5163
return false;
5164
if (ParamT.getNonReferenceType()->getUnqualifiedDesugaredType() !=
5165
Decl->getTypeForDecl())
5166
return false;
5167
}
5168
5169
return llvm::all_of(Decl->bases(),
5170
[&](const CXXBaseSpecifier &BS) {
5171
if (const auto *RD = BS.getType()->getAsCXXRecordDecl())
5172
return HasNonDeletedDefaultedEqualityComparison(
5173
S, RD, KeyLoc);
5174
return true;
5175
}) &&
5176
llvm::all_of(Decl->fields(), [&](const FieldDecl *FD) {
5177
auto Type = FD->getType();
5178
if (Type->isArrayType())
5179
Type = Type->getBaseElementTypeUnsafe()
5180
->getCanonicalTypeUnqualified();
5181
5182
if (Type->isReferenceType() || Type->isEnumeralType())
5183
return false;
5184
if (const auto *RD = Type->getAsCXXRecordDecl())
5185
return HasNonDeletedDefaultedEqualityComparison(S, RD, KeyLoc);
5186
return true;
5187
});
5188
}
5189
5190
static bool isTriviallyEqualityComparableType(Sema &S, QualType Type, SourceLocation KeyLoc) {
5191
QualType CanonicalType = Type.getCanonicalType();
5192
if (CanonicalType->isIncompleteType() || CanonicalType->isDependentType() ||
5193
CanonicalType->isEnumeralType() || CanonicalType->isArrayType())
5194
return false;
5195
5196
if (const auto *RD = CanonicalType->getAsCXXRecordDecl()) {
5197
if (!HasNonDeletedDefaultedEqualityComparison(S, RD, KeyLoc))
5198
return false;
5199
}
5200
5201
return S.getASTContext().hasUniqueObjectRepresentations(
5202
CanonicalType, /*CheckIfTriviallyCopyable=*/false);
5203
}
5204
5205
static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
5206
SourceLocation KeyLoc,
5207
TypeSourceInfo *TInfo) {
5208
QualType T = TInfo->getType();
5209
assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5210
5211
ASTContext &C = Self.Context;
5212
switch(UTT) {
5213
default: llvm_unreachable("not a UTT");
5214
// Type trait expressions corresponding to the primary type category
5215
// predicates in C++0x [meta.unary.cat].
5216
case UTT_IsVoid:
5217
return T->isVoidType();
5218
case UTT_IsIntegral:
5219
return T->isIntegralType(C);
5220
case UTT_IsFloatingPoint:
5221
return T->isFloatingType();
5222
case UTT_IsArray:
5223
// Zero-sized arrays aren't considered arrays in partial specializations,
5224
// so __is_array shouldn't consider them arrays either.
5225
if (const auto *CAT = C.getAsConstantArrayType(T))
5226
return CAT->getSize() != 0;
5227
return T->isArrayType();
5228
case UTT_IsBoundedArray:
5229
if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_bounded_array))
5230
return false;
5231
// Zero-sized arrays aren't considered arrays in partial specializations,
5232
// so __is_bounded_array shouldn't consider them arrays either.
5233
if (const auto *CAT = C.getAsConstantArrayType(T))
5234
return CAT->getSize() != 0;
5235
return T->isArrayType() && !T->isIncompleteArrayType();
5236
case UTT_IsUnboundedArray:
5237
if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_unbounded_array))
5238
return false;
5239
return T->isIncompleteArrayType();
5240
case UTT_IsPointer:
5241
return T->isAnyPointerType();
5242
case UTT_IsNullPointer:
5243
return T->isNullPtrType();
5244
case UTT_IsLvalueReference:
5245
return T->isLValueReferenceType();
5246
case UTT_IsRvalueReference:
5247
return T->isRValueReferenceType();
5248
case UTT_IsMemberFunctionPointer:
5249
return T->isMemberFunctionPointerType();
5250
case UTT_IsMemberObjectPointer:
5251
return T->isMemberDataPointerType();
5252
case UTT_IsEnum:
5253
return T->isEnumeralType();
5254
case UTT_IsScopedEnum:
5255
return T->isScopedEnumeralType();
5256
case UTT_IsUnion:
5257
return T->isUnionType();
5258
case UTT_IsClass:
5259
return T->isClassType() || T->isStructureType() || T->isInterfaceType();
5260
case UTT_IsFunction:
5261
return T->isFunctionType();
5262
5263
// Type trait expressions which correspond to the convenient composition
5264
// predicates in C++0x [meta.unary.comp].
5265
case UTT_IsReference:
5266
return T->isReferenceType();
5267
case UTT_IsArithmetic:
5268
return T->isArithmeticType() && !T->isEnumeralType();
5269
case UTT_IsFundamental:
5270
return T->isFundamentalType();
5271
case UTT_IsObject:
5272
return T->isObjectType();
5273
case UTT_IsScalar:
5274
// Note: semantic analysis depends on Objective-C lifetime types to be
5275
// considered scalar types. However, such types do not actually behave
5276
// like scalar types at run time (since they may require retain/release
5277
// operations), so we report them as non-scalar.
5278
if (T->isObjCLifetimeType()) {
5279
switch (T.getObjCLifetime()) {
5280
case Qualifiers::OCL_None:
5281
case Qualifiers::OCL_ExplicitNone:
5282
return true;
5283
5284
case Qualifiers::OCL_Strong:
5285
case Qualifiers::OCL_Weak:
5286
case Qualifiers::OCL_Autoreleasing:
5287
return false;
5288
}
5289
}
5290
5291
return T->isScalarType();
5292
case UTT_IsCompound:
5293
return T->isCompoundType();
5294
case UTT_IsMemberPointer:
5295
return T->isMemberPointerType();
5296
5297
// Type trait expressions which correspond to the type property predicates
5298
// in C++0x [meta.unary.prop].
5299
case UTT_IsConst:
5300
return T.isConstQualified();
5301
case UTT_IsVolatile:
5302
return T.isVolatileQualified();
5303
case UTT_IsTrivial:
5304
return T.isTrivialType(C);
5305
case UTT_IsTriviallyCopyable:
5306
return T.isTriviallyCopyableType(C);
5307
case UTT_IsStandardLayout:
5308
return T->isStandardLayoutType();
5309
case UTT_IsPOD:
5310
return T.isPODType(C);
5311
case UTT_IsLiteral:
5312
return T->isLiteralType(C);
5313
case UTT_IsEmpty:
5314
if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5315
return !RD->isUnion() && RD->isEmpty();
5316
return false;
5317
case UTT_IsPolymorphic:
5318
if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5319
return !RD->isUnion() && RD->isPolymorphic();
5320
return false;
5321
case UTT_IsAbstract:
5322
if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5323
return !RD->isUnion() && RD->isAbstract();
5324
return false;
5325
case UTT_IsAggregate:
5326
// Report vector extensions and complex types as aggregates because they
5327
// support aggregate initialization. GCC mirrors this behavior for vectors
5328
// but not _Complex.
5329
return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
5330
T->isAnyComplexType();
5331
// __is_interface_class only returns true when CL is invoked in /CLR mode and
5332
// even then only when it is used with the 'interface struct ...' syntax
5333
// Clang doesn't support /CLR which makes this type trait moot.
5334
case UTT_IsInterfaceClass:
5335
return false;
5336
case UTT_IsFinal:
5337
case UTT_IsSealed:
5338
if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5339
return RD->hasAttr<FinalAttr>();
5340
return false;
5341
case UTT_IsSigned:
5342
// Enum types should always return false.
5343
// Floating points should always return true.
5344
return T->isFloatingType() ||
5345
(T->isSignedIntegerType() && !T->isEnumeralType());
5346
case UTT_IsUnsigned:
5347
// Enum types should always return false.
5348
return T->isUnsignedIntegerType() && !T->isEnumeralType();
5349
5350
// Type trait expressions which query classes regarding their construction,
5351
// destruction, and copying. Rather than being based directly on the
5352
// related type predicates in the standard, they are specified by both
5353
// GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
5354
// specifications.
5355
//
5356
// 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
5357
// 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5358
//
5359
// Note that these builtins do not behave as documented in g++: if a class
5360
// has both a trivial and a non-trivial special member of a particular kind,
5361
// they return false! For now, we emulate this behavior.
5362
// FIXME: This appears to be a g++ bug: more complex cases reveal that it
5363
// does not correctly compute triviality in the presence of multiple special
5364
// members of the same kind. Revisit this once the g++ bug is fixed.
5365
case UTT_HasTrivialDefaultConstructor:
5366
// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5367
// If __is_pod (type) is true then the trait is true, else if type is
5368
// a cv class or union type (or array thereof) with a trivial default
5369
// constructor ([class.ctor]) then the trait is true, else it is false.
5370
if (T.isPODType(C))
5371
return true;
5372
if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5373
return RD->hasTrivialDefaultConstructor() &&
5374
!RD->hasNonTrivialDefaultConstructor();
5375
return false;
5376
case UTT_HasTrivialMoveConstructor:
5377
// This trait is implemented by MSVC 2012 and needed to parse the
5378
// standard library headers. Specifically this is used as the logic
5379
// behind std::is_trivially_move_constructible (20.9.4.3).
5380
if (T.isPODType(C))
5381
return true;
5382
if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5383
return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
5384
return false;
5385
case UTT_HasTrivialCopy:
5386
// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5387
// If __is_pod (type) is true or type is a reference type then
5388
// the trait is true, else if type is a cv class or union type
5389
// with a trivial copy constructor ([class.copy]) then the trait
5390
// is true, else it is false.
5391
if (T.isPODType(C) || T->isReferenceType())
5392
return true;
5393
if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5394
return RD->hasTrivialCopyConstructor() &&
5395
!RD->hasNonTrivialCopyConstructor();
5396
return false;
5397
case UTT_HasTrivialMoveAssign:
5398
// This trait is implemented by MSVC 2012 and needed to parse the
5399
// standard library headers. Specifically it is used as the logic
5400
// behind std::is_trivially_move_assignable (20.9.4.3)
5401
if (T.isPODType(C))
5402
return true;
5403
if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5404
return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
5405
return false;
5406
case UTT_HasTrivialAssign:
5407
// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5408
// If type is const qualified or is a reference type then the
5409
// trait is false. Otherwise if __is_pod (type) is true then the
5410
// trait is true, else if type is a cv class or union type with
5411
// a trivial copy assignment ([class.copy]) then the trait is
5412
// true, else it is false.
5413
// Note: the const and reference restrictions are interesting,
5414
// given that const and reference members don't prevent a class
5415
// from having a trivial copy assignment operator (but do cause
5416
// errors if the copy assignment operator is actually used, q.v.
5417
// [class.copy]p12).
5418
5419
if (T.isConstQualified())
5420
return false;
5421
if (T.isPODType(C))
5422
return true;
5423
if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5424
return RD->hasTrivialCopyAssignment() &&
5425
!RD->hasNonTrivialCopyAssignment();
5426
return false;
5427
case UTT_IsDestructible:
5428
case UTT_IsTriviallyDestructible:
5429
case UTT_IsNothrowDestructible:
5430
// C++14 [meta.unary.prop]:
5431
// For reference types, is_destructible<T>::value is true.
5432
if (T->isReferenceType())
5433
return true;
5434
5435
// Objective-C++ ARC: autorelease types don't require destruction.
5436
if (T->isObjCLifetimeType() &&
5437
T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5438
return true;
5439
5440
// C++14 [meta.unary.prop]:
5441
// For incomplete types and function types, is_destructible<T>::value is
5442
// false.
5443
if (T->isIncompleteType() || T->isFunctionType())
5444
return false;
5445
5446
// A type that requires destruction (via a non-trivial destructor or ARC
5447
// lifetime semantics) is not trivially-destructible.
5448
if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
5449
return false;
5450
5451
// C++14 [meta.unary.prop]:
5452
// For object types and given U equal to remove_all_extents_t<T>, if the
5453
// expression std::declval<U&>().~U() is well-formed when treated as an
5454
// unevaluated operand (Clause 5), then is_destructible<T>::value is true
5455
if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5456
CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
5457
if (!Destructor)
5458
return false;
5459
// C++14 [dcl.fct.def.delete]p2:
5460
// A program that refers to a deleted function implicitly or
5461
// explicitly, other than to declare it, is ill-formed.
5462
if (Destructor->isDeleted())
5463
return false;
5464
if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
5465
return false;
5466
if (UTT == UTT_IsNothrowDestructible) {
5467
auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
5468
CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5469
if (!CPT || !CPT->isNothrow())
5470
return false;
5471
}
5472
}
5473
return true;
5474
5475
case UTT_HasTrivialDestructor:
5476
// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5477
// If __is_pod (type) is true or type is a reference type
5478
// then the trait is true, else if type is a cv class or union
5479
// type (or array thereof) with a trivial destructor
5480
// ([class.dtor]) then the trait is true, else it is
5481
// false.
5482
if (T.isPODType(C) || T->isReferenceType())
5483
return true;
5484
5485
// Objective-C++ ARC: autorelease types don't require destruction.
5486
if (T->isObjCLifetimeType() &&
5487
T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5488
return true;
5489
5490
if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5491
return RD->hasTrivialDestructor();
5492
return false;
5493
// TODO: Propagate nothrowness for implicitly declared special members.
5494
case UTT_HasNothrowAssign:
5495
// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5496
// If type is const qualified or is a reference type then the
5497
// trait is false. Otherwise if __has_trivial_assign (type)
5498
// is true then the trait is true, else if type is a cv class
5499
// or union type with copy assignment operators that are known
5500
// not to throw an exception then the trait is true, else it is
5501
// false.
5502
if (C.getBaseElementType(T).isConstQualified())
5503
return false;
5504
if (T->isReferenceType())
5505
return false;
5506
if (T.isPODType(C) || T->isObjCLifetimeType())
5507
return true;
5508
5509
if (const RecordType *RT = T->getAs<RecordType>())
5510
return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5511
&CXXRecordDecl::hasTrivialCopyAssignment,
5512
&CXXRecordDecl::hasNonTrivialCopyAssignment,
5513
&CXXMethodDecl::isCopyAssignmentOperator);
5514
return false;
5515
case UTT_HasNothrowMoveAssign:
5516
// This trait is implemented by MSVC 2012 and needed to parse the
5517
// standard library headers. Specifically this is used as the logic
5518
// behind std::is_nothrow_move_assignable (20.9.4.3).
5519
if (T.isPODType(C))
5520
return true;
5521
5522
if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
5523
return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5524
&CXXRecordDecl::hasTrivialMoveAssignment,
5525
&CXXRecordDecl::hasNonTrivialMoveAssignment,
5526
&CXXMethodDecl::isMoveAssignmentOperator);
5527
return false;
5528
case UTT_HasNothrowCopy:
5529
// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5530
// If __has_trivial_copy (type) is true then the trait is true, else
5531
// if type is a cv class or union type with copy constructors that are
5532
// known not to throw an exception then the trait is true, else it is
5533
// false.
5534
if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
5535
return true;
5536
if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
5537
if (RD->hasTrivialCopyConstructor() &&
5538
!RD->hasNonTrivialCopyConstructor())
5539
return true;
5540
5541
bool FoundConstructor = false;
5542
unsigned FoundTQs;
5543
for (const auto *ND : Self.LookupConstructors(RD)) {
5544
// A template constructor is never a copy constructor.
5545
// FIXME: However, it may actually be selected at the actual overload
5546
// resolution point.
5547
if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5548
continue;
5549
// UsingDecl itself is not a constructor
5550
if (isa<UsingDecl>(ND))
5551
continue;
5552
auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5553
if (Constructor->isCopyConstructor(FoundTQs)) {
5554
FoundConstructor = true;
5555
auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5556
CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5557
if (!CPT)
5558
return false;
5559
// TODO: check whether evaluating default arguments can throw.
5560
// For now, we'll be conservative and assume that they can throw.
5561
if (!CPT->isNothrow() || CPT->getNumParams() > 1)
5562
return false;
5563
}
5564
}
5565
5566
return FoundConstructor;
5567
}
5568
return false;
5569
case UTT_HasNothrowConstructor:
5570
// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5571
// If __has_trivial_constructor (type) is true then the trait is
5572
// true, else if type is a cv class or union type (or array
5573
// thereof) with a default constructor that is known not to
5574
// throw an exception then the trait is true, else it is false.
5575
if (T.isPODType(C) || T->isObjCLifetimeType())
5576
return true;
5577
if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5578
if (RD->hasTrivialDefaultConstructor() &&
5579
!RD->hasNonTrivialDefaultConstructor())
5580
return true;
5581
5582
bool FoundConstructor = false;
5583
for (const auto *ND : Self.LookupConstructors(RD)) {
5584
// FIXME: In C++0x, a constructor template can be a default constructor.
5585
if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5586
continue;
5587
// UsingDecl itself is not a constructor
5588
if (isa<UsingDecl>(ND))
5589
continue;
5590
auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5591
if (Constructor->isDefaultConstructor()) {
5592
FoundConstructor = true;
5593
auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5594
CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5595
if (!CPT)
5596
return false;
5597
// FIXME: check whether evaluating default arguments can throw.
5598
// For now, we'll be conservative and assume that they can throw.
5599
if (!CPT->isNothrow() || CPT->getNumParams() > 0)
5600
return false;
5601
}
5602
}
5603
return FoundConstructor;
5604
}
5605
return false;
5606
case UTT_HasVirtualDestructor:
5607
// http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5608
// If type is a class type with a virtual destructor ([class.dtor])
5609
// then the trait is true, else it is false.
5610
if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5611
if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
5612
return Destructor->isVirtual();
5613
return false;
5614
5615
// These type trait expressions are modeled on the specifications for the
5616
// Embarcadero C++0x type trait functions:
5617
// http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5618
case UTT_IsCompleteType:
5619
// http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5620
// Returns True if and only if T is a complete type at the point of the
5621
// function call.
5622
return !T->isIncompleteType();
5623
case UTT_HasUniqueObjectRepresentations:
5624
return C.hasUniqueObjectRepresentations(T);
5625
case UTT_IsTriviallyRelocatable:
5626
return T.isTriviallyRelocatableType(C);
5627
case UTT_IsBitwiseCloneable:
5628
return T.isBitwiseCloneableType(C);
5629
case UTT_IsReferenceable:
5630
return T.isReferenceable();
5631
case UTT_CanPassInRegs:
5632
if (CXXRecordDecl *RD = T->getAsCXXRecordDecl(); RD && !T.hasQualifiers())
5633
return RD->canPassInRegisters();
5634
Self.Diag(KeyLoc, diag::err_builtin_pass_in_regs_non_class) << T;
5635
return false;
5636
case UTT_IsTriviallyEqualityComparable:
5637
return isTriviallyEqualityComparableType(Self, T, KeyLoc);
5638
}
5639
}
5640
5641
static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs,
5642
const TypeSourceInfo *Rhs, SourceLocation KeyLoc);
5643
5644
static ExprResult CheckConvertibilityForTypeTraits(
5645
Sema &Self, const TypeSourceInfo *Lhs, const TypeSourceInfo *Rhs,
5646
SourceLocation KeyLoc, llvm::BumpPtrAllocator &OpaqueExprAllocator) {
5647
5648
QualType LhsT = Lhs->getType();
5649
QualType RhsT = Rhs->getType();
5650
5651
// C++0x [meta.rel]p4:
5652
// Given the following function prototype:
5653
//
5654
// template <class T>
5655
// typename add_rvalue_reference<T>::type create();
5656
//
5657
// the predicate condition for a template specialization
5658
// is_convertible<From, To> shall be satisfied if and only if
5659
// the return expression in the following code would be
5660
// well-formed, including any implicit conversions to the return
5661
// type of the function:
5662
//
5663
// To test() {
5664
// return create<From>();
5665
// }
5666
//
5667
// Access checking is performed as if in a context unrelated to To and
5668
// From. Only the validity of the immediate context of the expression
5669
// of the return-statement (including conversions to the return type)
5670
// is considered.
5671
//
5672
// We model the initialization as a copy-initialization of a temporary
5673
// of the appropriate type, which for this expression is identical to the
5674
// return statement (since NRVO doesn't apply).
5675
5676
// Functions aren't allowed to return function or array types.
5677
if (RhsT->isFunctionType() || RhsT->isArrayType())
5678
return ExprError();
5679
5680
// A function definition requires a complete, non-abstract return type.
5681
if (!Self.isCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT) ||
5682
Self.isAbstractType(Rhs->getTypeLoc().getBeginLoc(), RhsT))
5683
return ExprError();
5684
5685
// Compute the result of add_rvalue_reference.
5686
if (LhsT->isObjectType() || LhsT->isFunctionType())
5687
LhsT = Self.Context.getRValueReferenceType(LhsT);
5688
5689
// Build a fake source and destination for initialization.
5690
InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
5691
Expr *From = new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5692
OpaqueValueExpr(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5693
Expr::getValueKindForType(LhsT));
5694
InitializationKind Kind =
5695
InitializationKind::CreateCopy(KeyLoc, SourceLocation());
5696
5697
// Perform the initialization in an unevaluated context within a SFINAE
5698
// trap at translation unit scope.
5699
EnterExpressionEvaluationContext Unevaluated(
5700
Self, Sema::ExpressionEvaluationContext::Unevaluated);
5701
Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5702
Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5703
InitializationSequence Init(Self, To, Kind, From);
5704
if (Init.Failed())
5705
return ExprError();
5706
5707
ExprResult Result = Init.Perform(Self, To, Kind, From);
5708
if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5709
return ExprError();
5710
5711
return Result;
5712
}
5713
5714
static bool EvaluateBooleanTypeTrait(Sema &S, TypeTrait Kind,
5715
SourceLocation KWLoc,
5716
ArrayRef<TypeSourceInfo *> Args,
5717
SourceLocation RParenLoc,
5718
bool IsDependent) {
5719
if (IsDependent)
5720
return false;
5721
5722
if (Kind <= UTT_Last)
5723
return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]);
5724
5725
// Evaluate ReferenceBindsToTemporary and ReferenceConstructsFromTemporary
5726
// alongside the IsConstructible traits to avoid duplication.
5727
if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary &&
5728
Kind != BTT_ReferenceConstructsFromTemporary &&
5729
Kind != BTT_ReferenceConvertsFromTemporary)
5730
return EvaluateBinaryTypeTrait(S, Kind, Args[0],
5731
Args[1], RParenLoc);
5732
5733
switch (Kind) {
5734
case clang::BTT_ReferenceBindsToTemporary:
5735
case clang::BTT_ReferenceConstructsFromTemporary:
5736
case clang::BTT_ReferenceConvertsFromTemporary:
5737
case clang::TT_IsConstructible:
5738
case clang::TT_IsNothrowConstructible:
5739
case clang::TT_IsTriviallyConstructible: {
5740
// C++11 [meta.unary.prop]:
5741
// is_trivially_constructible is defined as:
5742
//
5743
// is_constructible<T, Args...>::value is true and the variable
5744
// definition for is_constructible, as defined below, is known to call
5745
// no operation that is not trivial.
5746
//
5747
// The predicate condition for a template specialization
5748
// is_constructible<T, Args...> shall be satisfied if and only if the
5749
// following variable definition would be well-formed for some invented
5750
// variable t:
5751
//
5752
// T t(create<Args>()...);
5753
assert(!Args.empty());
5754
5755
// Precondition: T and all types in the parameter pack Args shall be
5756
// complete types, (possibly cv-qualified) void, or arrays of
5757
// unknown bound.
5758
for (const auto *TSI : Args) {
5759
QualType ArgTy = TSI->getType();
5760
if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
5761
continue;
5762
5763
if (S.RequireCompleteType(KWLoc, ArgTy,
5764
diag::err_incomplete_type_used_in_type_trait_expr))
5765
return false;
5766
}
5767
5768
// Make sure the first argument is not incomplete nor a function type.
5769
QualType T = Args[0]->getType();
5770
if (T->isIncompleteType() || T->isFunctionType())
5771
return false;
5772
5773
// Make sure the first argument is not an abstract type.
5774
CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5775
if (RD && RD->isAbstract())
5776
return false;
5777
5778
llvm::BumpPtrAllocator OpaqueExprAllocator;
5779
SmallVector<Expr *, 2> ArgExprs;
5780
ArgExprs.reserve(Args.size() - 1);
5781
for (unsigned I = 1, N = Args.size(); I != N; ++I) {
5782
QualType ArgTy = Args[I]->getType();
5783
if (ArgTy->isObjectType() || ArgTy->isFunctionType())
5784
ArgTy = S.Context.getRValueReferenceType(ArgTy);
5785
ArgExprs.push_back(
5786
new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5787
OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
5788
ArgTy.getNonLValueExprType(S.Context),
5789
Expr::getValueKindForType(ArgTy)));
5790
}
5791
5792
// Perform the initialization in an unevaluated context within a SFINAE
5793
// trap at translation unit scope.
5794
EnterExpressionEvaluationContext Unevaluated(
5795
S, Sema::ExpressionEvaluationContext::Unevaluated);
5796
Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5797
Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
5798
InitializedEntity To(
5799
InitializedEntity::InitializeTemporary(S.Context, Args[0]));
5800
InitializationKind InitKind(
5801
Kind == clang::BTT_ReferenceConvertsFromTemporary
5802
? InitializationKind::CreateCopy(KWLoc, KWLoc)
5803
: InitializationKind::CreateDirect(KWLoc, KWLoc, RParenLoc));
5804
InitializationSequence Init(S, To, InitKind, ArgExprs);
5805
if (Init.Failed())
5806
return false;
5807
5808
ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5809
if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5810
return false;
5811
5812
if (Kind == clang::TT_IsConstructible)
5813
return true;
5814
5815
if (Kind == clang::BTT_ReferenceBindsToTemporary ||
5816
Kind == clang::BTT_ReferenceConstructsFromTemporary ||
5817
Kind == clang::BTT_ReferenceConvertsFromTemporary) {
5818
if (!T->isReferenceType())
5819
return false;
5820
5821
if (!Init.isDirectReferenceBinding())
5822
return true;
5823
5824
if (Kind == clang::BTT_ReferenceBindsToTemporary)
5825
return false;
5826
5827
QualType U = Args[1]->getType();
5828
if (U->isReferenceType())
5829
return false;
5830
5831
TypeSourceInfo *TPtr = S.Context.CreateTypeSourceInfo(
5832
S.Context.getPointerType(T.getNonReferenceType()));
5833
TypeSourceInfo *UPtr = S.Context.CreateTypeSourceInfo(
5834
S.Context.getPointerType(U.getNonReferenceType()));
5835
return !CheckConvertibilityForTypeTraits(S, UPtr, TPtr, RParenLoc,
5836
OpaqueExprAllocator)
5837
.isInvalid();
5838
}
5839
5840
if (Kind == clang::TT_IsNothrowConstructible)
5841
return S.canThrow(Result.get()) == CT_Cannot;
5842
5843
if (Kind == clang::TT_IsTriviallyConstructible) {
5844
// Under Objective-C ARC and Weak, if the destination has non-trivial
5845
// Objective-C lifetime, this is a non-trivial construction.
5846
if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5847
return false;
5848
5849
// The initialization succeeded; now make sure there are no non-trivial
5850
// calls.
5851
return !Result.get()->hasNonTrivialCall(S.Context);
5852
}
5853
5854
llvm_unreachable("unhandled type trait");
5855
return false;
5856
}
5857
default: llvm_unreachable("not a TT");
5858
}
5859
5860
return false;
5861
}
5862
5863
namespace {
5864
void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind,
5865
SourceLocation KWLoc) {
5866
TypeTrait Replacement;
5867
switch (Kind) {
5868
case UTT_HasNothrowAssign:
5869
case UTT_HasNothrowMoveAssign:
5870
Replacement = BTT_IsNothrowAssignable;
5871
break;
5872
case UTT_HasNothrowCopy:
5873
case UTT_HasNothrowConstructor:
5874
Replacement = TT_IsNothrowConstructible;
5875
break;
5876
case UTT_HasTrivialAssign:
5877
case UTT_HasTrivialMoveAssign:
5878
Replacement = BTT_IsTriviallyAssignable;
5879
break;
5880
case UTT_HasTrivialCopy:
5881
Replacement = UTT_IsTriviallyCopyable;
5882
break;
5883
case UTT_HasTrivialDefaultConstructor:
5884
case UTT_HasTrivialMoveConstructor:
5885
Replacement = TT_IsTriviallyConstructible;
5886
break;
5887
case UTT_HasTrivialDestructor:
5888
Replacement = UTT_IsTriviallyDestructible;
5889
break;
5890
default:
5891
return;
5892
}
5893
S.Diag(KWLoc, diag::warn_deprecated_builtin)
5894
<< getTraitSpelling(Kind) << getTraitSpelling(Replacement);
5895
}
5896
}
5897
5898
bool Sema::CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N) {
5899
if (Arity && N != Arity) {
5900
Diag(Loc, diag::err_type_trait_arity)
5901
<< Arity << 0 << (Arity > 1) << (int)N << SourceRange(Loc);
5902
return false;
5903
}
5904
5905
if (!Arity && N == 0) {
5906
Diag(Loc, diag::err_type_trait_arity)
5907
<< 1 << 1 << 1 << (int)N << SourceRange(Loc);
5908
return false;
5909
}
5910
return true;
5911
}
5912
5913
enum class TypeTraitReturnType {
5914
Bool,
5915
};
5916
5917
static TypeTraitReturnType GetReturnType(TypeTrait Kind) {
5918
return TypeTraitReturnType::Bool;
5919
}
5920
5921
ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5922
ArrayRef<TypeSourceInfo *> Args,
5923
SourceLocation RParenLoc) {
5924
if (!CheckTypeTraitArity(getTypeTraitArity(Kind), KWLoc, Args.size()))
5925
return ExprError();
5926
5927
if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5928
*this, Kind, KWLoc, Args[0]->getType()))
5929
return ExprError();
5930
5931
DiagnoseBuiltinDeprecation(*this, Kind, KWLoc);
5932
5933
bool Dependent = false;
5934
for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5935
if (Args[I]->getType()->isDependentType()) {
5936
Dependent = true;
5937
break;
5938
}
5939
}
5940
5941
switch (GetReturnType(Kind)) {
5942
case TypeTraitReturnType::Bool: {
5943
bool Result = EvaluateBooleanTypeTrait(*this, Kind, KWLoc, Args, RParenLoc,
5944
Dependent);
5945
return TypeTraitExpr::Create(Context, Context.getLogicalOperationType(),
5946
KWLoc, Kind, Args, RParenLoc, Result);
5947
}
5948
}
5949
llvm_unreachable("unhandled type trait return type");
5950
}
5951
5952
ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5953
ArrayRef<ParsedType> Args,
5954
SourceLocation RParenLoc) {
5955
SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5956
ConvertedArgs.reserve(Args.size());
5957
5958
for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5959
TypeSourceInfo *TInfo;
5960
QualType T = GetTypeFromParser(Args[I], &TInfo);
5961
if (!TInfo)
5962
TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5963
5964
ConvertedArgs.push_back(TInfo);
5965
}
5966
5967
return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5968
}
5969
5970
static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs,
5971
const TypeSourceInfo *Rhs, SourceLocation KeyLoc) {
5972
QualType LhsT = Lhs->getType();
5973
QualType RhsT = Rhs->getType();
5974
5975
assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5976
"Cannot evaluate traits of dependent types");
5977
5978
switch(BTT) {
5979
case BTT_IsBaseOf: {
5980
// C++0x [meta.rel]p2
5981
// Base is a base class of Derived without regard to cv-qualifiers or
5982
// Base and Derived are not unions and name the same class type without
5983
// regard to cv-qualifiers.
5984
5985
const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5986
const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5987
if (!rhsRecord || !lhsRecord) {
5988
const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5989
const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5990
if (!LHSObjTy || !RHSObjTy)
5991
return false;
5992
5993
ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5994
ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5995
if (!BaseInterface || !DerivedInterface)
5996
return false;
5997
5998
if (Self.RequireCompleteType(
5999
Rhs->getTypeLoc().getBeginLoc(), RhsT,
6000
diag::err_incomplete_type_used_in_type_trait_expr))
6001
return false;
6002
6003
return BaseInterface->isSuperClassOf(DerivedInterface);
6004
}
6005
6006
assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
6007
== (lhsRecord == rhsRecord));
6008
6009
// Unions are never base classes, and never have base classes.
6010
// It doesn't matter if they are complete or not. See PR#41843
6011
if (lhsRecord && lhsRecord->getDecl()->isUnion())
6012
return false;
6013
if (rhsRecord && rhsRecord->getDecl()->isUnion())
6014
return false;
6015
6016
if (lhsRecord == rhsRecord)
6017
return true;
6018
6019
// C++0x [meta.rel]p2:
6020
// If Base and Derived are class types and are different types
6021
// (ignoring possible cv-qualifiers) then Derived shall be a
6022
// complete type.
6023
if (Self.RequireCompleteType(
6024
Rhs->getTypeLoc().getBeginLoc(), RhsT,
6025
diag::err_incomplete_type_used_in_type_trait_expr))
6026
return false;
6027
6028
return cast<CXXRecordDecl>(rhsRecord->getDecl())
6029
->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
6030
}
6031
case BTT_IsSame:
6032
return Self.Context.hasSameType(LhsT, RhsT);
6033
case BTT_TypeCompatible: {
6034
// GCC ignores cv-qualifiers on arrays for this builtin.
6035
Qualifiers LhsQuals, RhsQuals;
6036
QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
6037
QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
6038
return Self.Context.typesAreCompatible(Lhs, Rhs);
6039
}
6040
case BTT_IsConvertible:
6041
case BTT_IsConvertibleTo:
6042
case BTT_IsNothrowConvertible: {
6043
if (RhsT->isVoidType())
6044
return LhsT->isVoidType();
6045
llvm::BumpPtrAllocator OpaqueExprAllocator;
6046
ExprResult Result = CheckConvertibilityForTypeTraits(Self, Lhs, Rhs, KeyLoc,
6047
OpaqueExprAllocator);
6048
if (Result.isInvalid())
6049
return false;
6050
6051
if (BTT != BTT_IsNothrowConvertible)
6052
return true;
6053
6054
return Self.canThrow(Result.get()) == CT_Cannot;
6055
}
6056
6057
case BTT_IsAssignable:
6058
case BTT_IsNothrowAssignable:
6059
case BTT_IsTriviallyAssignable: {
6060
// C++11 [meta.unary.prop]p3:
6061
// is_trivially_assignable is defined as:
6062
// is_assignable<T, U>::value is true and the assignment, as defined by
6063
// is_assignable, is known to call no operation that is not trivial
6064
//
6065
// is_assignable is defined as:
6066
// The expression declval<T>() = declval<U>() is well-formed when
6067
// treated as an unevaluated operand (Clause 5).
6068
//
6069
// For both, T and U shall be complete types, (possibly cv-qualified)
6070
// void, or arrays of unknown bound.
6071
if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
6072
Self.RequireCompleteType(
6073
Lhs->getTypeLoc().getBeginLoc(), LhsT,
6074
diag::err_incomplete_type_used_in_type_trait_expr))
6075
return false;
6076
if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
6077
Self.RequireCompleteType(
6078
Rhs->getTypeLoc().getBeginLoc(), RhsT,
6079
diag::err_incomplete_type_used_in_type_trait_expr))
6080
return false;
6081
6082
// cv void is never assignable.
6083
if (LhsT->isVoidType() || RhsT->isVoidType())
6084
return false;
6085
6086
// Build expressions that emulate the effect of declval<T>() and
6087
// declval<U>().
6088
if (LhsT->isObjectType() || LhsT->isFunctionType())
6089
LhsT = Self.Context.getRValueReferenceType(LhsT);
6090
if (RhsT->isObjectType() || RhsT->isFunctionType())
6091
RhsT = Self.Context.getRValueReferenceType(RhsT);
6092
OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
6093
Expr::getValueKindForType(LhsT));
6094
OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
6095
Expr::getValueKindForType(RhsT));
6096
6097
// Attempt the assignment in an unevaluated context within a SFINAE
6098
// trap at translation unit scope.
6099
EnterExpressionEvaluationContext Unevaluated(
6100
Self, Sema::ExpressionEvaluationContext::Unevaluated);
6101
Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
6102
Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
6103
ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
6104
&Rhs);
6105
if (Result.isInvalid())
6106
return false;
6107
6108
// Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
6109
Self.CheckUnusedVolatileAssignment(Result.get());
6110
6111
if (SFINAE.hasErrorOccurred())
6112
return false;
6113
6114
if (BTT == BTT_IsAssignable)
6115
return true;
6116
6117
if (BTT == BTT_IsNothrowAssignable)
6118
return Self.canThrow(Result.get()) == CT_Cannot;
6119
6120
if (BTT == BTT_IsTriviallyAssignable) {
6121
// Under Objective-C ARC and Weak, if the destination has non-trivial
6122
// Objective-C lifetime, this is a non-trivial assignment.
6123
if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
6124
return false;
6125
6126
return !Result.get()->hasNonTrivialCall(Self.Context);
6127
}
6128
6129
llvm_unreachable("unhandled type trait");
6130
return false;
6131
}
6132
case BTT_IsLayoutCompatible: {
6133
if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType())
6134
Self.RequireCompleteType(Lhs->getTypeLoc().getBeginLoc(), LhsT,
6135
diag::err_incomplete_type);
6136
if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType())
6137
Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6138
diag::err_incomplete_type);
6139
6140
DiagnoseVLAInCXXTypeTrait(Self, Lhs, tok::kw___is_layout_compatible);
6141
DiagnoseVLAInCXXTypeTrait(Self, Rhs, tok::kw___is_layout_compatible);
6142
6143
return Self.IsLayoutCompatible(LhsT, RhsT);
6144
}
6145
case BTT_IsPointerInterconvertibleBaseOf: {
6146
if (LhsT->isStructureOrClassType() && RhsT->isStructureOrClassType() &&
6147
!Self.getASTContext().hasSameUnqualifiedType(LhsT, RhsT)) {
6148
Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6149
diag::err_incomplete_type);
6150
}
6151
6152
DiagnoseVLAInCXXTypeTrait(Self, Lhs,
6153
tok::kw___is_pointer_interconvertible_base_of);
6154
DiagnoseVLAInCXXTypeTrait(Self, Rhs,
6155
tok::kw___is_pointer_interconvertible_base_of);
6156
6157
return Self.IsPointerInterconvertibleBaseOf(Lhs, Rhs);
6158
}
6159
case BTT_IsDeducible: {
6160
const auto *TSTToBeDeduced = cast<DeducedTemplateSpecializationType>(LhsT);
6161
sema::TemplateDeductionInfo Info(KeyLoc);
6162
return Self.DeduceTemplateArgumentsFromType(
6163
TSTToBeDeduced->getTemplateName().getAsTemplateDecl(), RhsT,
6164
Info) == TemplateDeductionResult::Success;
6165
}
6166
default:
6167
llvm_unreachable("not a BTT");
6168
}
6169
llvm_unreachable("Unknown type trait or not implemented");
6170
}
6171
6172
ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
6173
SourceLocation KWLoc,
6174
ParsedType Ty,
6175
Expr* DimExpr,
6176
SourceLocation RParen) {
6177
TypeSourceInfo *TSInfo;
6178
QualType T = GetTypeFromParser(Ty, &TSInfo);
6179
if (!TSInfo)
6180
TSInfo = Context.getTrivialTypeSourceInfo(T);
6181
6182
return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
6183
}
6184
6185
static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
6186
QualType T, Expr *DimExpr,
6187
SourceLocation KeyLoc) {
6188
assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
6189
6190
switch(ATT) {
6191
case ATT_ArrayRank:
6192
if (T->isArrayType()) {
6193
unsigned Dim = 0;
6194
while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
6195
++Dim;
6196
T = AT->getElementType();
6197
}
6198
return Dim;
6199
}
6200
return 0;
6201
6202
case ATT_ArrayExtent: {
6203
llvm::APSInt Value;
6204
uint64_t Dim;
6205
if (Self.VerifyIntegerConstantExpression(
6206
DimExpr, &Value, diag::err_dimension_expr_not_constant_integer)
6207
.isInvalid())
6208
return 0;
6209
if (Value.isSigned() && Value.isNegative()) {
6210
Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
6211
<< DimExpr->getSourceRange();
6212
return 0;
6213
}
6214
Dim = Value.getLimitedValue();
6215
6216
if (T->isArrayType()) {
6217
unsigned D = 0;
6218
bool Matched = false;
6219
while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
6220
if (Dim == D) {
6221
Matched = true;
6222
break;
6223
}
6224
++D;
6225
T = AT->getElementType();
6226
}
6227
6228
if (Matched && T->isArrayType()) {
6229
if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
6230
return CAT->getLimitedSize();
6231
}
6232
}
6233
return 0;
6234
}
6235
}
6236
llvm_unreachable("Unknown type trait or not implemented");
6237
}
6238
6239
ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
6240
SourceLocation KWLoc,
6241
TypeSourceInfo *TSInfo,
6242
Expr* DimExpr,
6243
SourceLocation RParen) {
6244
QualType T = TSInfo->getType();
6245
6246
// FIXME: This should likely be tracked as an APInt to remove any host
6247
// assumptions about the width of size_t on the target.
6248
uint64_t Value = 0;
6249
if (!T->isDependentType())
6250
Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
6251
6252
// While the specification for these traits from the Embarcadero C++
6253
// compiler's documentation says the return type is 'unsigned int', Clang
6254
// returns 'size_t'. On Windows, the primary platform for the Embarcadero
6255
// compiler, there is no difference. On several other platforms this is an
6256
// important distinction.
6257
return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
6258
RParen, Context.getSizeType());
6259
}
6260
6261
ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
6262
SourceLocation KWLoc,
6263
Expr *Queried,
6264
SourceLocation RParen) {
6265
// If error parsing the expression, ignore.
6266
if (!Queried)
6267
return ExprError();
6268
6269
ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
6270
6271
return Result;
6272
}
6273
6274
static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
6275
switch (ET) {
6276
case ET_IsLValueExpr: return E->isLValue();
6277
case ET_IsRValueExpr:
6278
return E->isPRValue();
6279
}
6280
llvm_unreachable("Expression trait not covered by switch");
6281
}
6282
6283
ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
6284
SourceLocation KWLoc,
6285
Expr *Queried,
6286
SourceLocation RParen) {
6287
if (Queried->isTypeDependent()) {
6288
// Delay type-checking for type-dependent expressions.
6289
} else if (Queried->hasPlaceholderType()) {
6290
ExprResult PE = CheckPlaceholderExpr(Queried);
6291
if (PE.isInvalid()) return ExprError();
6292
return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
6293
}
6294
6295
bool Value = EvaluateExpressionTrait(ET, Queried);
6296
6297
return new (Context)
6298
ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
6299
}
6300
6301
QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
6302
ExprValueKind &VK,
6303
SourceLocation Loc,
6304
bool isIndirect) {
6305
assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
6306
"placeholders should have been weeded out by now");
6307
6308
// The LHS undergoes lvalue conversions if this is ->*, and undergoes the
6309
// temporary materialization conversion otherwise.
6310
if (isIndirect)
6311
LHS = DefaultLvalueConversion(LHS.get());
6312
else if (LHS.get()->isPRValue())
6313
LHS = TemporaryMaterializationConversion(LHS.get());
6314
if (LHS.isInvalid())
6315
return QualType();
6316
6317
// The RHS always undergoes lvalue conversions.
6318
RHS = DefaultLvalueConversion(RHS.get());
6319
if (RHS.isInvalid()) return QualType();
6320
6321
const char *OpSpelling = isIndirect ? "->*" : ".*";
6322
// C++ 5.5p2
6323
// The binary operator .* [p3: ->*] binds its second operand, which shall
6324
// be of type "pointer to member of T" (where T is a completely-defined
6325
// class type) [...]
6326
QualType RHSType = RHS.get()->getType();
6327
const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
6328
if (!MemPtr) {
6329
Diag(Loc, diag::err_bad_memptr_rhs)
6330
<< OpSpelling << RHSType << RHS.get()->getSourceRange();
6331
return QualType();
6332
}
6333
6334
QualType Class(MemPtr->getClass(), 0);
6335
6336
// Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
6337
// member pointer points must be completely-defined. However, there is no
6338
// reason for this semantic distinction, and the rule is not enforced by
6339
// other compilers. Therefore, we do not check this property, as it is
6340
// likely to be considered a defect.
6341
6342
// C++ 5.5p2
6343
// [...] to its first operand, which shall be of class T or of a class of
6344
// which T is an unambiguous and accessible base class. [p3: a pointer to
6345
// such a class]
6346
QualType LHSType = LHS.get()->getType();
6347
if (isIndirect) {
6348
if (const PointerType *Ptr = LHSType->getAs<PointerType>())
6349
LHSType = Ptr->getPointeeType();
6350
else {
6351
Diag(Loc, diag::err_bad_memptr_lhs)
6352
<< OpSpelling << 1 << LHSType
6353
<< FixItHint::CreateReplacement(SourceRange(Loc), ".*");
6354
return QualType();
6355
}
6356
}
6357
6358
if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
6359
// If we want to check the hierarchy, we need a complete type.
6360
if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
6361
OpSpelling, (int)isIndirect)) {
6362
return QualType();
6363
}
6364
6365
if (!IsDerivedFrom(Loc, LHSType, Class)) {
6366
Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
6367
<< (int)isIndirect << LHS.get()->getType();
6368
return QualType();
6369
}
6370
6371
CXXCastPath BasePath;
6372
if (CheckDerivedToBaseConversion(
6373
LHSType, Class, Loc,
6374
SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
6375
&BasePath))
6376
return QualType();
6377
6378
// Cast LHS to type of use.
6379
QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
6380
if (isIndirect)
6381
UseType = Context.getPointerType(UseType);
6382
ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
6383
LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
6384
&BasePath);
6385
}
6386
6387
if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
6388
// Diagnose use of pointer-to-member type which when used as
6389
// the functional cast in a pointer-to-member expression.
6390
Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
6391
return QualType();
6392
}
6393
6394
// C++ 5.5p2
6395
// The result is an object or a function of the type specified by the
6396
// second operand.
6397
// The cv qualifiers are the union of those in the pointer and the left side,
6398
// in accordance with 5.5p5 and 5.2.5.
6399
QualType Result = MemPtr->getPointeeType();
6400
Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
6401
6402
// C++0x [expr.mptr.oper]p6:
6403
// In a .* expression whose object expression is an rvalue, the program is
6404
// ill-formed if the second operand is a pointer to member function with
6405
// ref-qualifier &. In a ->* expression or in a .* expression whose object
6406
// expression is an lvalue, the program is ill-formed if the second operand
6407
// is a pointer to member function with ref-qualifier &&.
6408
if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
6409
switch (Proto->getRefQualifier()) {
6410
case RQ_None:
6411
// Do nothing
6412
break;
6413
6414
case RQ_LValue:
6415
if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
6416
// C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
6417
// is (exactly) 'const'.
6418
if (Proto->isConst() && !Proto->isVolatile())
6419
Diag(Loc, getLangOpts().CPlusPlus20
6420
? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
6421
: diag::ext_pointer_to_const_ref_member_on_rvalue);
6422
else
6423
Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6424
<< RHSType << 1 << LHS.get()->getSourceRange();
6425
}
6426
break;
6427
6428
case RQ_RValue:
6429
if (isIndirect || !LHS.get()->Classify(Context).isRValue())
6430
Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6431
<< RHSType << 0 << LHS.get()->getSourceRange();
6432
break;
6433
}
6434
}
6435
6436
// C++ [expr.mptr.oper]p6:
6437
// The result of a .* expression whose second operand is a pointer
6438
// to a data member is of the same value category as its
6439
// first operand. The result of a .* expression whose second
6440
// operand is a pointer to a member function is a prvalue. The
6441
// result of an ->* expression is an lvalue if its second operand
6442
// is a pointer to data member and a prvalue otherwise.
6443
if (Result->isFunctionType()) {
6444
VK = VK_PRValue;
6445
return Context.BoundMemberTy;
6446
} else if (isIndirect) {
6447
VK = VK_LValue;
6448
} else {
6449
VK = LHS.get()->getValueKind();
6450
}
6451
6452
return Result;
6453
}
6454
6455
/// Try to convert a type to another according to C++11 5.16p3.
6456
///
6457
/// This is part of the parameter validation for the ? operator. If either
6458
/// value operand is a class type, the two operands are attempted to be
6459
/// converted to each other. This function does the conversion in one direction.
6460
/// It returns true if the program is ill-formed and has already been diagnosed
6461
/// as such.
6462
static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
6463
SourceLocation QuestionLoc,
6464
bool &HaveConversion,
6465
QualType &ToType) {
6466
HaveConversion = false;
6467
ToType = To->getType();
6468
6469
InitializationKind Kind =
6470
InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
6471
// C++11 5.16p3
6472
// The process for determining whether an operand expression E1 of type T1
6473
// can be converted to match an operand expression E2 of type T2 is defined
6474
// as follows:
6475
// -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
6476
// implicitly converted to type "lvalue reference to T2", subject to the
6477
// constraint that in the conversion the reference must bind directly to
6478
// an lvalue.
6479
// -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
6480
// implicitly converted to the type "rvalue reference to R2", subject to
6481
// the constraint that the reference must bind directly.
6482
if (To->isGLValue()) {
6483
QualType T = Self.Context.getReferenceQualifiedType(To);
6484
InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
6485
6486
InitializationSequence InitSeq(Self, Entity, Kind, From);
6487
if (InitSeq.isDirectReferenceBinding()) {
6488
ToType = T;
6489
HaveConversion = true;
6490
return false;
6491
}
6492
6493
if (InitSeq.isAmbiguous())
6494
return InitSeq.Diagnose(Self, Entity, Kind, From);
6495
}
6496
6497
// -- If E2 is an rvalue, or if the conversion above cannot be done:
6498
// -- if E1 and E2 have class type, and the underlying class types are
6499
// the same or one is a base class of the other:
6500
QualType FTy = From->getType();
6501
QualType TTy = To->getType();
6502
const RecordType *FRec = FTy->getAs<RecordType>();
6503
const RecordType *TRec = TTy->getAs<RecordType>();
6504
bool FDerivedFromT = FRec && TRec && FRec != TRec &&
6505
Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
6506
if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
6507
Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
6508
// E1 can be converted to match E2 if the class of T2 is the
6509
// same type as, or a base class of, the class of T1, and
6510
// [cv2 > cv1].
6511
if (FRec == TRec || FDerivedFromT) {
6512
if (TTy.isAtLeastAsQualifiedAs(FTy)) {
6513
InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
6514
InitializationSequence InitSeq(Self, Entity, Kind, From);
6515
if (InitSeq) {
6516
HaveConversion = true;
6517
return false;
6518
}
6519
6520
if (InitSeq.isAmbiguous())
6521
return InitSeq.Diagnose(Self, Entity, Kind, From);
6522
}
6523
}
6524
6525
return false;
6526
}
6527
6528
// -- Otherwise: E1 can be converted to match E2 if E1 can be
6529
// implicitly converted to the type that expression E2 would have
6530
// if E2 were converted to an rvalue (or the type it has, if E2 is
6531
// an rvalue).
6532
//
6533
// This actually refers very narrowly to the lvalue-to-rvalue conversion, not
6534
// to the array-to-pointer or function-to-pointer conversions.
6535
TTy = TTy.getNonLValueExprType(Self.Context);
6536
6537
InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
6538
InitializationSequence InitSeq(Self, Entity, Kind, From);
6539
HaveConversion = !InitSeq.Failed();
6540
ToType = TTy;
6541
if (InitSeq.isAmbiguous())
6542
return InitSeq.Diagnose(Self, Entity, Kind, From);
6543
6544
return false;
6545
}
6546
6547
/// Try to find a common type for two according to C++0x 5.16p5.
6548
///
6549
/// This is part of the parameter validation for the ? operator. If either
6550
/// value operand is a class type, overload resolution is used to find a
6551
/// conversion to a common type.
6552
static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
6553
SourceLocation QuestionLoc) {
6554
Expr *Args[2] = { LHS.get(), RHS.get() };
6555
OverloadCandidateSet CandidateSet(QuestionLoc,
6556
OverloadCandidateSet::CSK_Operator);
6557
Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
6558
CandidateSet);
6559
6560
OverloadCandidateSet::iterator Best;
6561
switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
6562
case OR_Success: {
6563
// We found a match. Perform the conversions on the arguments and move on.
6564
ExprResult LHSRes = Self.PerformImplicitConversion(
6565
LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
6566
Sema::AA_Converting);
6567
if (LHSRes.isInvalid())
6568
break;
6569
LHS = LHSRes;
6570
6571
ExprResult RHSRes = Self.PerformImplicitConversion(
6572
RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
6573
Sema::AA_Converting);
6574
if (RHSRes.isInvalid())
6575
break;
6576
RHS = RHSRes;
6577
if (Best->Function)
6578
Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
6579
return false;
6580
}
6581
6582
case OR_No_Viable_Function:
6583
6584
// Emit a better diagnostic if one of the expressions is a null pointer
6585
// constant and the other is a pointer type. In this case, the user most
6586
// likely forgot to take the address of the other expression.
6587
if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6588
return true;
6589
6590
Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6591
<< LHS.get()->getType() << RHS.get()->getType()
6592
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6593
return true;
6594
6595
case OR_Ambiguous:
6596
Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
6597
<< LHS.get()->getType() << RHS.get()->getType()
6598
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6599
// FIXME: Print the possible common types by printing the return types of
6600
// the viable candidates.
6601
break;
6602
6603
case OR_Deleted:
6604
llvm_unreachable("Conditional operator has only built-in overloads");
6605
}
6606
return true;
6607
}
6608
6609
/// Perform an "extended" implicit conversion as returned by
6610
/// TryClassUnification.
6611
static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
6612
InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
6613
InitializationKind Kind =
6614
InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
6615
Expr *Arg = E.get();
6616
InitializationSequence InitSeq(Self, Entity, Kind, Arg);
6617
ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
6618
if (Result.isInvalid())
6619
return true;
6620
6621
E = Result;
6622
return false;
6623
}
6624
6625
// Check the condition operand of ?: to see if it is valid for the GCC
6626
// extension.
6627
static bool isValidVectorForConditionalCondition(ASTContext &Ctx,
6628
QualType CondTy) {
6629
if (!CondTy->isVectorType() && !CondTy->isExtVectorType())
6630
return false;
6631
const QualType EltTy =
6632
cast<VectorType>(CondTy.getCanonicalType())->getElementType();
6633
assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6634
return EltTy->isIntegralType(Ctx);
6635
}
6636
6637
static bool isValidSizelessVectorForConditionalCondition(ASTContext &Ctx,
6638
QualType CondTy) {
6639
if (!CondTy->isSveVLSBuiltinType())
6640
return false;
6641
const QualType EltTy =
6642
cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx);
6643
assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6644
return EltTy->isIntegralType(Ctx);
6645
}
6646
6647
QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
6648
ExprResult &RHS,
6649
SourceLocation QuestionLoc) {
6650
LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6651
RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6652
6653
QualType CondType = Cond.get()->getType();
6654
const auto *CondVT = CondType->castAs<VectorType>();
6655
QualType CondElementTy = CondVT->getElementType();
6656
unsigned CondElementCount = CondVT->getNumElements();
6657
QualType LHSType = LHS.get()->getType();
6658
const auto *LHSVT = LHSType->getAs<VectorType>();
6659
QualType RHSType = RHS.get()->getType();
6660
const auto *RHSVT = RHSType->getAs<VectorType>();
6661
6662
QualType ResultType;
6663
6664
6665
if (LHSVT && RHSVT) {
6666
if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) {
6667
Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
6668
<< /*isExtVector*/ isa<ExtVectorType>(CondVT);
6669
return {};
6670
}
6671
6672
// If both are vector types, they must be the same type.
6673
if (!Context.hasSameType(LHSType, RHSType)) {
6674
Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6675
<< LHSType << RHSType;
6676
return {};
6677
}
6678
ResultType = Context.getCommonSugaredType(LHSType, RHSType);
6679
} else if (LHSVT || RHSVT) {
6680
ResultType = CheckVectorOperands(
6681
LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
6682
/*AllowBoolConversions*/ false,
6683
/*AllowBoolOperation*/ true,
6684
/*ReportInvalid*/ true);
6685
if (ResultType.isNull())
6686
return {};
6687
} else {
6688
// Both are scalar.
6689
LHSType = LHSType.getUnqualifiedType();
6690
RHSType = RHSType.getUnqualifiedType();
6691
QualType ResultElementTy =
6692
Context.hasSameType(LHSType, RHSType)
6693
? Context.getCommonSugaredType(LHSType, RHSType)
6694
: UsualArithmeticConversions(LHS, RHS, QuestionLoc,
6695
ACK_Conditional);
6696
6697
if (ResultElementTy->isEnumeralType()) {
6698
Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6699
<< ResultElementTy;
6700
return {};
6701
}
6702
if (CondType->isExtVectorType())
6703
ResultType =
6704
Context.getExtVectorType(ResultElementTy, CondVT->getNumElements());
6705
else
6706
ResultType = Context.getVectorType(
6707
ResultElementTy, CondVT->getNumElements(), VectorKind::Generic);
6708
6709
LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6710
RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6711
}
6712
6713
assert(!ResultType.isNull() && ResultType->isVectorType() &&
6714
(!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
6715
"Result should have been a vector type");
6716
auto *ResultVectorTy = ResultType->castAs<VectorType>();
6717
QualType ResultElementTy = ResultVectorTy->getElementType();
6718
unsigned ResultElementCount = ResultVectorTy->getNumElements();
6719
6720
if (ResultElementCount != CondElementCount) {
6721
Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
6722
<< ResultType;
6723
return {};
6724
}
6725
6726
if (Context.getTypeSize(ResultElementTy) !=
6727
Context.getTypeSize(CondElementTy)) {
6728
Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
6729
<< ResultType;
6730
return {};
6731
}
6732
6733
return ResultType;
6734
}
6735
6736
QualType Sema::CheckSizelessVectorConditionalTypes(ExprResult &Cond,
6737
ExprResult &LHS,
6738
ExprResult &RHS,
6739
SourceLocation QuestionLoc) {
6740
LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6741
RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6742
6743
QualType CondType = Cond.get()->getType();
6744
const auto *CondBT = CondType->castAs<BuiltinType>();
6745
QualType CondElementTy = CondBT->getSveEltType(Context);
6746
llvm::ElementCount CondElementCount =
6747
Context.getBuiltinVectorTypeInfo(CondBT).EC;
6748
6749
QualType LHSType = LHS.get()->getType();
6750
const auto *LHSBT =
6751
LHSType->isSveVLSBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr;
6752
QualType RHSType = RHS.get()->getType();
6753
const auto *RHSBT =
6754
RHSType->isSveVLSBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr;
6755
6756
QualType ResultType;
6757
6758
if (LHSBT && RHSBT) {
6759
// If both are sizeless vector types, they must be the same type.
6760
if (!Context.hasSameType(LHSType, RHSType)) {
6761
Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6762
<< LHSType << RHSType;
6763
return QualType();
6764
}
6765
ResultType = LHSType;
6766
} else if (LHSBT || RHSBT) {
6767
ResultType = CheckSizelessVectorOperands(
6768
LHS, RHS, QuestionLoc, /*IsCompAssign*/ false, ACK_Conditional);
6769
if (ResultType.isNull())
6770
return QualType();
6771
} else {
6772
// Both are scalar so splat
6773
QualType ResultElementTy;
6774
LHSType = LHSType.getCanonicalType().getUnqualifiedType();
6775
RHSType = RHSType.getCanonicalType().getUnqualifiedType();
6776
6777
if (Context.hasSameType(LHSType, RHSType))
6778
ResultElementTy = LHSType;
6779
else
6780
ResultElementTy =
6781
UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6782
6783
if (ResultElementTy->isEnumeralType()) {
6784
Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6785
<< ResultElementTy;
6786
return QualType();
6787
}
6788
6789
ResultType = Context.getScalableVectorType(
6790
ResultElementTy, CondElementCount.getKnownMinValue());
6791
6792
LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6793
RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6794
}
6795
6796
assert(!ResultType.isNull() && ResultType->isSveVLSBuiltinType() &&
6797
"Result should have been a vector type");
6798
auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>();
6799
QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context);
6800
llvm::ElementCount ResultElementCount =
6801
Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC;
6802
6803
if (ResultElementCount != CondElementCount) {
6804
Diag(QuestionLoc, diag::err_conditional_vector_size)
6805
<< CondType << ResultType;
6806
return QualType();
6807
}
6808
6809
if (Context.getTypeSize(ResultElementTy) !=
6810
Context.getTypeSize(CondElementTy)) {
6811
Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6812
<< CondType << ResultType;
6813
return QualType();
6814
}
6815
6816
return ResultType;
6817
}
6818
6819
QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6820
ExprResult &RHS, ExprValueKind &VK,
6821
ExprObjectKind &OK,
6822
SourceLocation QuestionLoc) {
6823
// FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
6824
// pointers.
6825
6826
// Assume r-value.
6827
VK = VK_PRValue;
6828
OK = OK_Ordinary;
6829
bool IsVectorConditional =
6830
isValidVectorForConditionalCondition(Context, Cond.get()->getType());
6831
6832
bool IsSizelessVectorConditional =
6833
isValidSizelessVectorForConditionalCondition(Context,
6834
Cond.get()->getType());
6835
6836
// C++11 [expr.cond]p1
6837
// The first expression is contextually converted to bool.
6838
if (!Cond.get()->isTypeDependent()) {
6839
ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional
6840
? DefaultFunctionArrayLvalueConversion(Cond.get())
6841
: CheckCXXBooleanCondition(Cond.get());
6842
if (CondRes.isInvalid())
6843
return QualType();
6844
Cond = CondRes;
6845
} else {
6846
// To implement C++, the first expression typically doesn't alter the result
6847
// type of the conditional, however the GCC compatible vector extension
6848
// changes the result type to be that of the conditional. Since we cannot
6849
// know if this is a vector extension here, delay the conversion of the
6850
// LHS/RHS below until later.
6851
return Context.DependentTy;
6852
}
6853
6854
6855
// Either of the arguments dependent?
6856
if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
6857
return Context.DependentTy;
6858
6859
// C++11 [expr.cond]p2
6860
// If either the second or the third operand has type (cv) void, ...
6861
QualType LTy = LHS.get()->getType();
6862
QualType RTy = RHS.get()->getType();
6863
bool LVoid = LTy->isVoidType();
6864
bool RVoid = RTy->isVoidType();
6865
if (LVoid || RVoid) {
6866
// ... one of the following shall hold:
6867
// -- The second or the third operand (but not both) is a (possibly
6868
// parenthesized) throw-expression; the result is of the type
6869
// and value category of the other.
6870
bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
6871
bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
6872
6873
// Void expressions aren't legal in the vector-conditional expressions.
6874
if (IsVectorConditional) {
6875
SourceRange DiagLoc =
6876
LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
6877
bool IsThrow = LVoid ? LThrow : RThrow;
6878
Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
6879
<< DiagLoc << IsThrow;
6880
return QualType();
6881
}
6882
6883
if (LThrow != RThrow) {
6884
Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
6885
VK = NonThrow->getValueKind();
6886
// DR (no number yet): the result is a bit-field if the
6887
// non-throw-expression operand is a bit-field.
6888
OK = NonThrow->getObjectKind();
6889
return NonThrow->getType();
6890
}
6891
6892
// -- Both the second and third operands have type void; the result is of
6893
// type void and is a prvalue.
6894
if (LVoid && RVoid)
6895
return Context.getCommonSugaredType(LTy, RTy);
6896
6897
// Neither holds, error.
6898
Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
6899
<< (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
6900
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6901
return QualType();
6902
}
6903
6904
// Neither is void.
6905
if (IsVectorConditional)
6906
return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6907
6908
if (IsSizelessVectorConditional)
6909
return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6910
6911
// WebAssembly tables are not allowed as conditional LHS or RHS.
6912
if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) {
6913
Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
6914
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6915
return QualType();
6916
}
6917
6918
// C++11 [expr.cond]p3
6919
// Otherwise, if the second and third operand have different types, and
6920
// either has (cv) class type [...] an attempt is made to convert each of
6921
// those operands to the type of the other.
6922
if (!Context.hasSameType(LTy, RTy) &&
6923
(LTy->isRecordType() || RTy->isRecordType())) {
6924
// These return true if a single direction is already ambiguous.
6925
QualType L2RType, R2LType;
6926
bool HaveL2R, HaveR2L;
6927
if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
6928
return QualType();
6929
if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
6930
return QualType();
6931
6932
// If both can be converted, [...] the program is ill-formed.
6933
if (HaveL2R && HaveR2L) {
6934
Diag(QuestionLoc, diag::err_conditional_ambiguous)
6935
<< LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6936
return QualType();
6937
}
6938
6939
// If exactly one conversion is possible, that conversion is applied to
6940
// the chosen operand and the converted operands are used in place of the
6941
// original operands for the remainder of this section.
6942
if (HaveL2R) {
6943
if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
6944
return QualType();
6945
LTy = LHS.get()->getType();
6946
} else if (HaveR2L) {
6947
if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
6948
return QualType();
6949
RTy = RHS.get()->getType();
6950
}
6951
}
6952
6953
// C++11 [expr.cond]p3
6954
// if both are glvalues of the same value category and the same type except
6955
// for cv-qualification, an attempt is made to convert each of those
6956
// operands to the type of the other.
6957
// FIXME:
6958
// Resolving a defect in P0012R1: we extend this to cover all cases where
6959
// one of the operands is reference-compatible with the other, in order
6960
// to support conditionals between functions differing in noexcept. This
6961
// will similarly cover difference in array bounds after P0388R4.
6962
// FIXME: If LTy and RTy have a composite pointer type, should we convert to
6963
// that instead?
6964
ExprValueKind LVK = LHS.get()->getValueKind();
6965
ExprValueKind RVK = RHS.get()->getValueKind();
6966
if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
6967
// DerivedToBase was already handled by the class-specific case above.
6968
// FIXME: Should we allow ObjC conversions here?
6969
const ReferenceConversions AllowedConversions =
6970
ReferenceConversions::Qualification |
6971
ReferenceConversions::NestedQualification |
6972
ReferenceConversions::Function;
6973
6974
ReferenceConversions RefConv;
6975
if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6976
Ref_Compatible &&
6977
!(RefConv & ~AllowedConversions) &&
6978
// [...] subject to the constraint that the reference must bind
6979
// directly [...]
6980
!RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6981
RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
6982
RTy = RHS.get()->getType();
6983
} else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6984
Ref_Compatible &&
6985
!(RefConv & ~AllowedConversions) &&
6986
!LHS.get()->refersToBitField() &&
6987
!LHS.get()->refersToVectorElement()) {
6988
LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6989
LTy = LHS.get()->getType();
6990
}
6991
}
6992
6993
// C++11 [expr.cond]p4
6994
// If the second and third operands are glvalues of the same value
6995
// category and have the same type, the result is of that type and
6996
// value category and it is a bit-field if the second or the third
6997
// operand is a bit-field, or if both are bit-fields.
6998
// We only extend this to bitfields, not to the crazy other kinds of
6999
// l-values.
7000
bool Same = Context.hasSameType(LTy, RTy);
7001
if (Same && LVK == RVK && LVK != VK_PRValue &&
7002
LHS.get()->isOrdinaryOrBitFieldObject() &&
7003
RHS.get()->isOrdinaryOrBitFieldObject()) {
7004
VK = LHS.get()->getValueKind();
7005
if (LHS.get()->getObjectKind() == OK_BitField ||
7006
RHS.get()->getObjectKind() == OK_BitField)
7007
OK = OK_BitField;
7008
return Context.getCommonSugaredType(LTy, RTy);
7009
}
7010
7011
// C++11 [expr.cond]p5
7012
// Otherwise, the result is a prvalue. If the second and third operands
7013
// do not have the same type, and either has (cv) class type, ...
7014
if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
7015
// ... overload resolution is used to determine the conversions (if any)
7016
// to be applied to the operands. If the overload resolution fails, the
7017
// program is ill-formed.
7018
if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
7019
return QualType();
7020
}
7021
7022
// C++11 [expr.cond]p6
7023
// Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
7024
// conversions are performed on the second and third operands.
7025
LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7026
RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7027
if (LHS.isInvalid() || RHS.isInvalid())
7028
return QualType();
7029
LTy = LHS.get()->getType();
7030
RTy = RHS.get()->getType();
7031
7032
// After those conversions, one of the following shall hold:
7033
// -- The second and third operands have the same type; the result
7034
// is of that type. If the operands have class type, the result
7035
// is a prvalue temporary of the result type, which is
7036
// copy-initialized from either the second operand or the third
7037
// operand depending on the value of the first operand.
7038
if (Context.hasSameType(LTy, RTy)) {
7039
if (LTy->isRecordType()) {
7040
// The operands have class type. Make a temporary copy.
7041
ExprResult LHSCopy = PerformCopyInitialization(
7042
InitializedEntity::InitializeTemporary(LTy), SourceLocation(), LHS);
7043
if (LHSCopy.isInvalid())
7044
return QualType();
7045
7046
ExprResult RHSCopy = PerformCopyInitialization(
7047
InitializedEntity::InitializeTemporary(RTy), SourceLocation(), RHS);
7048
if (RHSCopy.isInvalid())
7049
return QualType();
7050
7051
LHS = LHSCopy;
7052
RHS = RHSCopy;
7053
}
7054
return Context.getCommonSugaredType(LTy, RTy);
7055
}
7056
7057
// Extension: conditional operator involving vector types.
7058
if (LTy->isVectorType() || RTy->isVectorType())
7059
return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
7060
/*AllowBothBool*/ true,
7061
/*AllowBoolConversions*/ false,
7062
/*AllowBoolOperation*/ false,
7063
/*ReportInvalid*/ true);
7064
7065
// -- The second and third operands have arithmetic or enumeration type;
7066
// the usual arithmetic conversions are performed to bring them to a
7067
// common type, and the result is of that type.
7068
if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
7069
QualType ResTy =
7070
UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7071
if (LHS.isInvalid() || RHS.isInvalid())
7072
return QualType();
7073
if (ResTy.isNull()) {
7074
Diag(QuestionLoc,
7075
diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
7076
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7077
return QualType();
7078
}
7079
7080
LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7081
RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7082
7083
return ResTy;
7084
}
7085
7086
// -- The second and third operands have pointer type, or one has pointer
7087
// type and the other is a null pointer constant, or both are null
7088
// pointer constants, at least one of which is non-integral; pointer
7089
// conversions and qualification conversions are performed to bring them
7090
// to their composite pointer type. The result is of the composite
7091
// pointer type.
7092
// -- The second and third operands have pointer to member type, or one has
7093
// pointer to member type and the other is a null pointer constant;
7094
// pointer to member conversions and qualification conversions are
7095
// performed to bring them to a common type, whose cv-qualification
7096
// shall match the cv-qualification of either the second or the third
7097
// operand. The result is of the common type.
7098
QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
7099
if (!Composite.isNull())
7100
return Composite;
7101
7102
// Similarly, attempt to find composite type of two objective-c pointers.
7103
Composite = ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
7104
if (LHS.isInvalid() || RHS.isInvalid())
7105
return QualType();
7106
if (!Composite.isNull())
7107
return Composite;
7108
7109
// Check if we are using a null with a non-pointer type.
7110
if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7111
return QualType();
7112
7113
Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7114
<< LHS.get()->getType() << RHS.get()->getType()
7115
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7116
return QualType();
7117
}
7118
7119
QualType Sema::FindCompositePointerType(SourceLocation Loc,
7120
Expr *&E1, Expr *&E2,
7121
bool ConvertArgs) {
7122
assert(getLangOpts().CPlusPlus && "This function assumes C++");
7123
7124
// C++1z [expr]p14:
7125
// The composite pointer type of two operands p1 and p2 having types T1
7126
// and T2
7127
QualType T1 = E1->getType(), T2 = E2->getType();
7128
7129
// where at least one is a pointer or pointer to member type or
7130
// std::nullptr_t is:
7131
bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
7132
T1->isNullPtrType();
7133
bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
7134
T2->isNullPtrType();
7135
if (!T1IsPointerLike && !T2IsPointerLike)
7136
return QualType();
7137
7138
// - if both p1 and p2 are null pointer constants, std::nullptr_t;
7139
// This can't actually happen, following the standard, but we also use this
7140
// to implement the end of [expr.conv], which hits this case.
7141
//
7142
// - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
7143
if (T1IsPointerLike &&
7144
E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
7145
if (ConvertArgs)
7146
E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
7147
? CK_NullToMemberPointer
7148
: CK_NullToPointer).get();
7149
return T1;
7150
}
7151
if (T2IsPointerLike &&
7152
E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
7153
if (ConvertArgs)
7154
E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
7155
? CK_NullToMemberPointer
7156
: CK_NullToPointer).get();
7157
return T2;
7158
}
7159
7160
// Now both have to be pointers or member pointers.
7161
if (!T1IsPointerLike || !T2IsPointerLike)
7162
return QualType();
7163
assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
7164
"nullptr_t should be a null pointer constant");
7165
7166
struct Step {
7167
enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
7168
// Qualifiers to apply under the step kind.
7169
Qualifiers Quals;
7170
/// The class for a pointer-to-member; a constant array type with a bound
7171
/// (if any) for an array.
7172
const Type *ClassOrBound;
7173
7174
Step(Kind K, const Type *ClassOrBound = nullptr)
7175
: K(K), ClassOrBound(ClassOrBound) {}
7176
QualType rebuild(ASTContext &Ctx, QualType T) const {
7177
T = Ctx.getQualifiedType(T, Quals);
7178
switch (K) {
7179
case Pointer:
7180
return Ctx.getPointerType(T);
7181
case MemberPointer:
7182
return Ctx.getMemberPointerType(T, ClassOrBound);
7183
case ObjCPointer:
7184
return Ctx.getObjCObjectPointerType(T);
7185
case Array:
7186
if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
7187
return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
7188
ArraySizeModifier::Normal, 0);
7189
else
7190
return Ctx.getIncompleteArrayType(T, ArraySizeModifier::Normal, 0);
7191
}
7192
llvm_unreachable("unknown step kind");
7193
}
7194
};
7195
7196
SmallVector<Step, 8> Steps;
7197
7198
// - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7199
// is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7200
// the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
7201
// respectively;
7202
// - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
7203
// to member of C2 of type cv2 U2" for some non-function type U, where
7204
// C1 is reference-related to C2 or C2 is reference-related to C1, the
7205
// cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
7206
// respectively;
7207
// - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
7208
// T2;
7209
//
7210
// Dismantle T1 and T2 to simultaneously determine whether they are similar
7211
// and to prepare to form the cv-combined type if so.
7212
QualType Composite1 = T1;
7213
QualType Composite2 = T2;
7214
unsigned NeedConstBefore = 0;
7215
while (true) {
7216
assert(!Composite1.isNull() && !Composite2.isNull());
7217
7218
Qualifiers Q1, Q2;
7219
Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
7220
Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
7221
7222
// Top-level qualifiers are ignored. Merge at all lower levels.
7223
if (!Steps.empty()) {
7224
// Find the qualifier union: (approximately) the unique minimal set of
7225
// qualifiers that is compatible with both types.
7226
Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() |
7227
Q2.getCVRUQualifiers());
7228
7229
// Under one level of pointer or pointer-to-member, we can change to an
7230
// unambiguous compatible address space.
7231
if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
7232
Quals.setAddressSpace(Q1.getAddressSpace());
7233
} else if (Steps.size() == 1) {
7234
bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
7235
bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
7236
if (MaybeQ1 == MaybeQ2) {
7237
// Exception for ptr size address spaces. Should be able to choose
7238
// either address space during comparison.
7239
if (isPtrSizeAddressSpace(Q1.getAddressSpace()) ||
7240
isPtrSizeAddressSpace(Q2.getAddressSpace()))
7241
MaybeQ1 = true;
7242
else
7243
return QualType(); // No unique best address space.
7244
}
7245
Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
7246
: Q2.getAddressSpace());
7247
} else {
7248
return QualType();
7249
}
7250
7251
// FIXME: In C, we merge __strong and none to __strong at the top level.
7252
if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
7253
Quals.setObjCGCAttr(Q1.getObjCGCAttr());
7254
else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7255
assert(Steps.size() == 1);
7256
else
7257
return QualType();
7258
7259
// Mismatched lifetime qualifiers never compatibly include each other.
7260
if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
7261
Quals.setObjCLifetime(Q1.getObjCLifetime());
7262
else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7263
assert(Steps.size() == 1);
7264
else
7265
return QualType();
7266
7267
Steps.back().Quals = Quals;
7268
if (Q1 != Quals || Q2 != Quals)
7269
NeedConstBefore = Steps.size() - 1;
7270
}
7271
7272
// FIXME: Can we unify the following with UnwrapSimilarTypes?
7273
7274
const ArrayType *Arr1, *Arr2;
7275
if ((Arr1 = Context.getAsArrayType(Composite1)) &&
7276
(Arr2 = Context.getAsArrayType(Composite2))) {
7277
auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
7278
auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
7279
if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
7280
Composite1 = Arr1->getElementType();
7281
Composite2 = Arr2->getElementType();
7282
Steps.emplace_back(Step::Array, CAT1);
7283
continue;
7284
}
7285
bool IAT1 = isa<IncompleteArrayType>(Arr1);
7286
bool IAT2 = isa<IncompleteArrayType>(Arr2);
7287
if ((IAT1 && IAT2) ||
7288
(getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
7289
((bool)CAT1 != (bool)CAT2) &&
7290
(Steps.empty() || Steps.back().K != Step::Array))) {
7291
// In C++20 onwards, we can unify an array of N T with an array of
7292
// a different or unknown bound. But we can't form an array whose
7293
// element type is an array of unknown bound by doing so.
7294
Composite1 = Arr1->getElementType();
7295
Composite2 = Arr2->getElementType();
7296
Steps.emplace_back(Step::Array);
7297
if (CAT1 || CAT2)
7298
NeedConstBefore = Steps.size();
7299
continue;
7300
}
7301
}
7302
7303
const PointerType *Ptr1, *Ptr2;
7304
if ((Ptr1 = Composite1->getAs<PointerType>()) &&
7305
(Ptr2 = Composite2->getAs<PointerType>())) {
7306
Composite1 = Ptr1->getPointeeType();
7307
Composite2 = Ptr2->getPointeeType();
7308
Steps.emplace_back(Step::Pointer);
7309
continue;
7310
}
7311
7312
const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
7313
if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
7314
(ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
7315
Composite1 = ObjPtr1->getPointeeType();
7316
Composite2 = ObjPtr2->getPointeeType();
7317
Steps.emplace_back(Step::ObjCPointer);
7318
continue;
7319
}
7320
7321
const MemberPointerType *MemPtr1, *MemPtr2;
7322
if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
7323
(MemPtr2 = Composite2->getAs<MemberPointerType>())) {
7324
Composite1 = MemPtr1->getPointeeType();
7325
Composite2 = MemPtr2->getPointeeType();
7326
7327
// At the top level, we can perform a base-to-derived pointer-to-member
7328
// conversion:
7329
//
7330
// - [...] where C1 is reference-related to C2 or C2 is
7331
// reference-related to C1
7332
//
7333
// (Note that the only kinds of reference-relatedness in scope here are
7334
// "same type or derived from".) At any other level, the class must
7335
// exactly match.
7336
const Type *Class = nullptr;
7337
QualType Cls1(MemPtr1->getClass(), 0);
7338
QualType Cls2(MemPtr2->getClass(), 0);
7339
if (Context.hasSameType(Cls1, Cls2))
7340
Class = MemPtr1->getClass();
7341
else if (Steps.empty())
7342
Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
7343
IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
7344
if (!Class)
7345
return QualType();
7346
7347
Steps.emplace_back(Step::MemberPointer, Class);
7348
continue;
7349
}
7350
7351
// Special case: at the top level, we can decompose an Objective-C pointer
7352
// and a 'cv void *'. Unify the qualifiers.
7353
if (Steps.empty() && ((Composite1->isVoidPointerType() &&
7354
Composite2->isObjCObjectPointerType()) ||
7355
(Composite1->isObjCObjectPointerType() &&
7356
Composite2->isVoidPointerType()))) {
7357
Composite1 = Composite1->getPointeeType();
7358
Composite2 = Composite2->getPointeeType();
7359
Steps.emplace_back(Step::Pointer);
7360
continue;
7361
}
7362
7363
// FIXME: block pointer types?
7364
7365
// Cannot unwrap any more types.
7366
break;
7367
}
7368
7369
// - if T1 or T2 is "pointer to noexcept function" and the other type is
7370
// "pointer to function", where the function types are otherwise the same,
7371
// "pointer to function";
7372
// - if T1 or T2 is "pointer to member of C1 of type function", the other
7373
// type is "pointer to member of C2 of type noexcept function", and C1
7374
// is reference-related to C2 or C2 is reference-related to C1, where
7375
// the function types are otherwise the same, "pointer to member of C2 of
7376
// type function" or "pointer to member of C1 of type function",
7377
// respectively;
7378
//
7379
// We also support 'noreturn' here, so as a Clang extension we generalize the
7380
// above to:
7381
//
7382
// - [Clang] If T1 and T2 are both of type "pointer to function" or
7383
// "pointer to member function" and the pointee types can be unified
7384
// by a function pointer conversion, that conversion is applied
7385
// before checking the following rules.
7386
//
7387
// We've already unwrapped down to the function types, and we want to merge
7388
// rather than just convert, so do this ourselves rather than calling
7389
// IsFunctionConversion.
7390
//
7391
// FIXME: In order to match the standard wording as closely as possible, we
7392
// currently only do this under a single level of pointers. Ideally, we would
7393
// allow this in general, and set NeedConstBefore to the relevant depth on
7394
// the side(s) where we changed anything. If we permit that, we should also
7395
// consider this conversion when determining type similarity and model it as
7396
// a qualification conversion.
7397
if (Steps.size() == 1) {
7398
if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
7399
if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
7400
FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
7401
FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
7402
7403
// The result is noreturn if both operands are.
7404
bool Noreturn =
7405
EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
7406
EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
7407
EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
7408
7409
// The result is nothrow if both operands are.
7410
SmallVector<QualType, 8> ExceptionTypeStorage;
7411
EPI1.ExceptionSpec = EPI2.ExceptionSpec = Context.mergeExceptionSpecs(
7412
EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage,
7413
getLangOpts().CPlusPlus17);
7414
7415
Composite1 = Context.getFunctionType(FPT1->getReturnType(),
7416
FPT1->getParamTypes(), EPI1);
7417
Composite2 = Context.getFunctionType(FPT2->getReturnType(),
7418
FPT2->getParamTypes(), EPI2);
7419
}
7420
}
7421
}
7422
7423
// There are some more conversions we can perform under exactly one pointer.
7424
if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
7425
!Context.hasSameType(Composite1, Composite2)) {
7426
// - if T1 or T2 is "pointer to cv1 void" and the other type is
7427
// "pointer to cv2 T", where T is an object type or void,
7428
// "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
7429
if (Composite1->isVoidType() && Composite2->isObjectType())
7430
Composite2 = Composite1;
7431
else if (Composite2->isVoidType() && Composite1->isObjectType())
7432
Composite1 = Composite2;
7433
// - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7434
// is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7435
// the cv-combined type of T1 and T2 or the cv-combined type of T2 and
7436
// T1, respectively;
7437
//
7438
// The "similar type" handling covers all of this except for the "T1 is a
7439
// base class of T2" case in the definition of reference-related.
7440
else if (IsDerivedFrom(Loc, Composite1, Composite2))
7441
Composite1 = Composite2;
7442
else if (IsDerivedFrom(Loc, Composite2, Composite1))
7443
Composite2 = Composite1;
7444
}
7445
7446
// At this point, either the inner types are the same or we have failed to
7447
// find a composite pointer type.
7448
if (!Context.hasSameType(Composite1, Composite2))
7449
return QualType();
7450
7451
// Per C++ [conv.qual]p3, add 'const' to every level before the last
7452
// differing qualifier.
7453
for (unsigned I = 0; I != NeedConstBefore; ++I)
7454
Steps[I].Quals.addConst();
7455
7456
// Rebuild the composite type.
7457
QualType Composite = Context.getCommonSugaredType(Composite1, Composite2);
7458
for (auto &S : llvm::reverse(Steps))
7459
Composite = S.rebuild(Context, Composite);
7460
7461
if (ConvertArgs) {
7462
// Convert the expressions to the composite pointer type.
7463
InitializedEntity Entity =
7464
InitializedEntity::InitializeTemporary(Composite);
7465
InitializationKind Kind =
7466
InitializationKind::CreateCopy(Loc, SourceLocation());
7467
7468
InitializationSequence E1ToC(*this, Entity, Kind, E1);
7469
if (!E1ToC)
7470
return QualType();
7471
7472
InitializationSequence E2ToC(*this, Entity, Kind, E2);
7473
if (!E2ToC)
7474
return QualType();
7475
7476
// FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
7477
ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
7478
if (E1Result.isInvalid())
7479
return QualType();
7480
E1 = E1Result.get();
7481
7482
ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
7483
if (E2Result.isInvalid())
7484
return QualType();
7485
E2 = E2Result.get();
7486
}
7487
7488
return Composite;
7489
}
7490
7491
ExprResult Sema::MaybeBindToTemporary(Expr *E) {
7492
if (!E)
7493
return ExprError();
7494
7495
assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
7496
7497
// If the result is a glvalue, we shouldn't bind it.
7498
if (E->isGLValue())
7499
return E;
7500
7501
// In ARC, calls that return a retainable type can return retained,
7502
// in which case we have to insert a consuming cast.
7503
if (getLangOpts().ObjCAutoRefCount &&
7504
E->getType()->isObjCRetainableType()) {
7505
7506
bool ReturnsRetained;
7507
7508
// For actual calls, we compute this by examining the type of the
7509
// called value.
7510
if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
7511
Expr *Callee = Call->getCallee()->IgnoreParens();
7512
QualType T = Callee->getType();
7513
7514
if (T == Context.BoundMemberTy) {
7515
// Handle pointer-to-members.
7516
if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
7517
T = BinOp->getRHS()->getType();
7518
else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
7519
T = Mem->getMemberDecl()->getType();
7520
}
7521
7522
if (const PointerType *Ptr = T->getAs<PointerType>())
7523
T = Ptr->getPointeeType();
7524
else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
7525
T = Ptr->getPointeeType();
7526
else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
7527
T = MemPtr->getPointeeType();
7528
7529
auto *FTy = T->castAs<FunctionType>();
7530
ReturnsRetained = FTy->getExtInfo().getProducesResult();
7531
7532
// ActOnStmtExpr arranges things so that StmtExprs of retainable
7533
// type always produce a +1 object.
7534
} else if (isa<StmtExpr>(E)) {
7535
ReturnsRetained = true;
7536
7537
// We hit this case with the lambda conversion-to-block optimization;
7538
// we don't want any extra casts here.
7539
} else if (isa<CastExpr>(E) &&
7540
isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
7541
return E;
7542
7543
// For message sends and property references, we try to find an
7544
// actual method. FIXME: we should infer retention by selector in
7545
// cases where we don't have an actual method.
7546
} else {
7547
ObjCMethodDecl *D = nullptr;
7548
if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
7549
D = Send->getMethodDecl();
7550
} else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
7551
D = BoxedExpr->getBoxingMethod();
7552
} else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
7553
// Don't do reclaims if we're using the zero-element array
7554
// constant.
7555
if (ArrayLit->getNumElements() == 0 &&
7556
Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
7557
return E;
7558
7559
D = ArrayLit->getArrayWithObjectsMethod();
7560
} else if (ObjCDictionaryLiteral *DictLit
7561
= dyn_cast<ObjCDictionaryLiteral>(E)) {
7562
// Don't do reclaims if we're using the zero-element dictionary
7563
// constant.
7564
if (DictLit->getNumElements() == 0 &&
7565
Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
7566
return E;
7567
7568
D = DictLit->getDictWithObjectsMethod();
7569
}
7570
7571
ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
7572
7573
// Don't do reclaims on performSelector calls; despite their
7574
// return type, the invoked method doesn't necessarily actually
7575
// return an object.
7576
if (!ReturnsRetained &&
7577
D && D->getMethodFamily() == OMF_performSelector)
7578
return E;
7579
}
7580
7581
// Don't reclaim an object of Class type.
7582
if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
7583
return E;
7584
7585
Cleanup.setExprNeedsCleanups(true);
7586
7587
CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
7588
: CK_ARCReclaimReturnedObject);
7589
return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
7590
VK_PRValue, FPOptionsOverride());
7591
}
7592
7593
if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
7594
Cleanup.setExprNeedsCleanups(true);
7595
7596
if (!getLangOpts().CPlusPlus)
7597
return E;
7598
7599
// Search for the base element type (cf. ASTContext::getBaseElementType) with
7600
// a fast path for the common case that the type is directly a RecordType.
7601
const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
7602
const RecordType *RT = nullptr;
7603
while (!RT) {
7604
switch (T->getTypeClass()) {
7605
case Type::Record:
7606
RT = cast<RecordType>(T);
7607
break;
7608
case Type::ConstantArray:
7609
case Type::IncompleteArray:
7610
case Type::VariableArray:
7611
case Type::DependentSizedArray:
7612
T = cast<ArrayType>(T)->getElementType().getTypePtr();
7613
break;
7614
default:
7615
return E;
7616
}
7617
}
7618
7619
// That should be enough to guarantee that this type is complete, if we're
7620
// not processing a decltype expression.
7621
CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7622
if (RD->isInvalidDecl() || RD->isDependentContext())
7623
return E;
7624
7625
bool IsDecltype = ExprEvalContexts.back().ExprContext ==
7626
ExpressionEvaluationContextRecord::EK_Decltype;
7627
CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
7628
7629
if (Destructor) {
7630
MarkFunctionReferenced(E->getExprLoc(), Destructor);
7631
CheckDestructorAccess(E->getExprLoc(), Destructor,
7632
PDiag(diag::err_access_dtor_temp)
7633
<< E->getType());
7634
if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
7635
return ExprError();
7636
7637
// If destructor is trivial, we can avoid the extra copy.
7638
if (Destructor->isTrivial())
7639
return E;
7640
7641
// We need a cleanup, but we don't need to remember the temporary.
7642
Cleanup.setExprNeedsCleanups(true);
7643
}
7644
7645
CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
7646
CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
7647
7648
if (IsDecltype)
7649
ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
7650
7651
return Bind;
7652
}
7653
7654
ExprResult
7655
Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
7656
if (SubExpr.isInvalid())
7657
return ExprError();
7658
7659
return MaybeCreateExprWithCleanups(SubExpr.get());
7660
}
7661
7662
Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
7663
assert(SubExpr && "subexpression can't be null!");
7664
7665
CleanupVarDeclMarking();
7666
7667
unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
7668
assert(ExprCleanupObjects.size() >= FirstCleanup);
7669
assert(Cleanup.exprNeedsCleanups() ||
7670
ExprCleanupObjects.size() == FirstCleanup);
7671
if (!Cleanup.exprNeedsCleanups())
7672
return SubExpr;
7673
7674
auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
7675
ExprCleanupObjects.size() - FirstCleanup);
7676
7677
auto *E = ExprWithCleanups::Create(
7678
Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
7679
DiscardCleanupsInEvaluationContext();
7680
7681
return E;
7682
}
7683
7684
Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
7685
assert(SubStmt && "sub-statement can't be null!");
7686
7687
CleanupVarDeclMarking();
7688
7689
if (!Cleanup.exprNeedsCleanups())
7690
return SubStmt;
7691
7692
// FIXME: In order to attach the temporaries, wrap the statement into
7693
// a StmtExpr; currently this is only used for asm statements.
7694
// This is hacky, either create a new CXXStmtWithTemporaries statement or
7695
// a new AsmStmtWithTemporaries.
7696
CompoundStmt *CompStmt =
7697
CompoundStmt::Create(Context, SubStmt, FPOptionsOverride(),
7698
SourceLocation(), SourceLocation());
7699
Expr *E = new (Context)
7700
StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(),
7701
/*FIXME TemplateDepth=*/0);
7702
return MaybeCreateExprWithCleanups(E);
7703
}
7704
7705
ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
7706
assert(ExprEvalContexts.back().ExprContext ==
7707
ExpressionEvaluationContextRecord::EK_Decltype &&
7708
"not in a decltype expression");
7709
7710
ExprResult Result = CheckPlaceholderExpr(E);
7711
if (Result.isInvalid())
7712
return ExprError();
7713
E = Result.get();
7714
7715
// C++11 [expr.call]p11:
7716
// If a function call is a prvalue of object type,
7717
// -- if the function call is either
7718
// -- the operand of a decltype-specifier, or
7719
// -- the right operand of a comma operator that is the operand of a
7720
// decltype-specifier,
7721
// a temporary object is not introduced for the prvalue.
7722
7723
// Recursively rebuild ParenExprs and comma expressions to strip out the
7724
// outermost CXXBindTemporaryExpr, if any.
7725
if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
7726
ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
7727
if (SubExpr.isInvalid())
7728
return ExprError();
7729
if (SubExpr.get() == PE->getSubExpr())
7730
return E;
7731
return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
7732
}
7733
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7734
if (BO->getOpcode() == BO_Comma) {
7735
ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
7736
if (RHS.isInvalid())
7737
return ExprError();
7738
if (RHS.get() == BO->getRHS())
7739
return E;
7740
return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
7741
BO->getType(), BO->getValueKind(),
7742
BO->getObjectKind(), BO->getOperatorLoc(),
7743
BO->getFPFeatures());
7744
}
7745
}
7746
7747
CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
7748
CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
7749
: nullptr;
7750
if (TopCall)
7751
E = TopCall;
7752
else
7753
TopBind = nullptr;
7754
7755
// Disable the special decltype handling now.
7756
ExprEvalContexts.back().ExprContext =
7757
ExpressionEvaluationContextRecord::EK_Other;
7758
7759
Result = CheckUnevaluatedOperand(E);
7760
if (Result.isInvalid())
7761
return ExprError();
7762
E = Result.get();
7763
7764
// In MS mode, don't perform any extra checking of call return types within a
7765
// decltype expression.
7766
if (getLangOpts().MSVCCompat)
7767
return E;
7768
7769
// Perform the semantic checks we delayed until this point.
7770
for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
7771
I != N; ++I) {
7772
CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
7773
if (Call == TopCall)
7774
continue;
7775
7776
if (CheckCallReturnType(Call->getCallReturnType(Context),
7777
Call->getBeginLoc(), Call, Call->getDirectCallee()))
7778
return ExprError();
7779
}
7780
7781
// Now all relevant types are complete, check the destructors are accessible
7782
// and non-deleted, and annotate them on the temporaries.
7783
for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
7784
I != N; ++I) {
7785
CXXBindTemporaryExpr *Bind =
7786
ExprEvalContexts.back().DelayedDecltypeBinds[I];
7787
if (Bind == TopBind)
7788
continue;
7789
7790
CXXTemporary *Temp = Bind->getTemporary();
7791
7792
CXXRecordDecl *RD =
7793
Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7794
CXXDestructorDecl *Destructor = LookupDestructor(RD);
7795
Temp->setDestructor(Destructor);
7796
7797
MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
7798
CheckDestructorAccess(Bind->getExprLoc(), Destructor,
7799
PDiag(diag::err_access_dtor_temp)
7800
<< Bind->getType());
7801
if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
7802
return ExprError();
7803
7804
// We need a cleanup, but we don't need to remember the temporary.
7805
Cleanup.setExprNeedsCleanups(true);
7806
}
7807
7808
// Possibly strip off the top CXXBindTemporaryExpr.
7809
return E;
7810
}
7811
7812
/// Note a set of 'operator->' functions that were used for a member access.
7813
static void noteOperatorArrows(Sema &S,
7814
ArrayRef<FunctionDecl *> OperatorArrows) {
7815
unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
7816
// FIXME: Make this configurable?
7817
unsigned Limit = 9;
7818
if (OperatorArrows.size() > Limit) {
7819
// Produce Limit-1 normal notes and one 'skipping' note.
7820
SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
7821
SkipCount = OperatorArrows.size() - (Limit - 1);
7822
}
7823
7824
for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
7825
if (I == SkipStart) {
7826
S.Diag(OperatorArrows[I]->getLocation(),
7827
diag::note_operator_arrows_suppressed)
7828
<< SkipCount;
7829
I += SkipCount;
7830
} else {
7831
S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
7832
<< OperatorArrows[I]->getCallResultType();
7833
++I;
7834
}
7835
}
7836
}
7837
7838
ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
7839
SourceLocation OpLoc,
7840
tok::TokenKind OpKind,
7841
ParsedType &ObjectType,
7842
bool &MayBePseudoDestructor) {
7843
// Since this might be a postfix expression, get rid of ParenListExprs.
7844
ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
7845
if (Result.isInvalid()) return ExprError();
7846
Base = Result.get();
7847
7848
Result = CheckPlaceholderExpr(Base);
7849
if (Result.isInvalid()) return ExprError();
7850
Base = Result.get();
7851
7852
QualType BaseType = Base->getType();
7853
MayBePseudoDestructor = false;
7854
if (BaseType->isDependentType()) {
7855
// If we have a pointer to a dependent type and are using the -> operator,
7856
// the object type is the type that the pointer points to. We might still
7857
// have enough information about that type to do something useful.
7858
if (OpKind == tok::arrow)
7859
if (const PointerType *Ptr = BaseType->getAs<PointerType>())
7860
BaseType = Ptr->getPointeeType();
7861
7862
ObjectType = ParsedType::make(BaseType);
7863
MayBePseudoDestructor = true;
7864
return Base;
7865
}
7866
7867
// C++ [over.match.oper]p8:
7868
// [...] When operator->returns, the operator-> is applied to the value
7869
// returned, with the original second operand.
7870
if (OpKind == tok::arrow) {
7871
QualType StartingType = BaseType;
7872
bool NoArrowOperatorFound = false;
7873
bool FirstIteration = true;
7874
FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
7875
// The set of types we've considered so far.
7876
llvm::SmallPtrSet<CanQualType,8> CTypes;
7877
SmallVector<FunctionDecl*, 8> OperatorArrows;
7878
CTypes.insert(Context.getCanonicalType(BaseType));
7879
7880
while (BaseType->isRecordType()) {
7881
if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
7882
Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
7883
<< StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
7884
noteOperatorArrows(*this, OperatorArrows);
7885
Diag(OpLoc, diag::note_operator_arrow_depth)
7886
<< getLangOpts().ArrowDepth;
7887
return ExprError();
7888
}
7889
7890
Result = BuildOverloadedArrowExpr(
7891
S, Base, OpLoc,
7892
// When in a template specialization and on the first loop iteration,
7893
// potentially give the default diagnostic (with the fixit in a
7894
// separate note) instead of having the error reported back to here
7895
// and giving a diagnostic with a fixit attached to the error itself.
7896
(FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
7897
? nullptr
7898
: &NoArrowOperatorFound);
7899
if (Result.isInvalid()) {
7900
if (NoArrowOperatorFound) {
7901
if (FirstIteration) {
7902
Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7903
<< BaseType << 1 << Base->getSourceRange()
7904
<< FixItHint::CreateReplacement(OpLoc, ".");
7905
OpKind = tok::period;
7906
break;
7907
}
7908
Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7909
<< BaseType << Base->getSourceRange();
7910
CallExpr *CE = dyn_cast<CallExpr>(Base);
7911
if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7912
Diag(CD->getBeginLoc(),
7913
diag::note_member_reference_arrow_from_operator_arrow);
7914
}
7915
}
7916
return ExprError();
7917
}
7918
Base = Result.get();
7919
if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
7920
OperatorArrows.push_back(OpCall->getDirectCallee());
7921
BaseType = Base->getType();
7922
CanQualType CBaseType = Context.getCanonicalType(BaseType);
7923
if (!CTypes.insert(CBaseType).second) {
7924
Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7925
noteOperatorArrows(*this, OperatorArrows);
7926
return ExprError();
7927
}
7928
FirstIteration = false;
7929
}
7930
7931
if (OpKind == tok::arrow) {
7932
if (BaseType->isPointerType())
7933
BaseType = BaseType->getPointeeType();
7934
else if (auto *AT = Context.getAsArrayType(BaseType))
7935
BaseType = AT->getElementType();
7936
}
7937
}
7938
7939
// Objective-C properties allow "." access on Objective-C pointer types,
7940
// so adjust the base type to the object type itself.
7941
if (BaseType->isObjCObjectPointerType())
7942
BaseType = BaseType->getPointeeType();
7943
7944
// C++ [basic.lookup.classref]p2:
7945
// [...] If the type of the object expression is of pointer to scalar
7946
// type, the unqualified-id is looked up in the context of the complete
7947
// postfix-expression.
7948
//
7949
// This also indicates that we could be parsing a pseudo-destructor-name.
7950
// Note that Objective-C class and object types can be pseudo-destructor
7951
// expressions or normal member (ivar or property) access expressions, and
7952
// it's legal for the type to be incomplete if this is a pseudo-destructor
7953
// call. We'll do more incomplete-type checks later in the lookup process,
7954
// so just skip this check for ObjC types.
7955
if (!BaseType->isRecordType()) {
7956
ObjectType = ParsedType::make(BaseType);
7957
MayBePseudoDestructor = true;
7958
return Base;
7959
}
7960
7961
// The object type must be complete (or dependent), or
7962
// C++11 [expr.prim.general]p3:
7963
// Unlike the object expression in other contexts, *this is not required to
7964
// be of complete type for purposes of class member access (5.2.5) outside
7965
// the member function body.
7966
if (!BaseType->isDependentType() &&
7967
!isThisOutsideMemberFunctionBody(BaseType) &&
7968
RequireCompleteType(OpLoc, BaseType,
7969
diag::err_incomplete_member_access)) {
7970
return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
7971
}
7972
7973
// C++ [basic.lookup.classref]p2:
7974
// If the id-expression in a class member access (5.2.5) is an
7975
// unqualified-id, and the type of the object expression is of a class
7976
// type C (or of pointer to a class type C), the unqualified-id is looked
7977
// up in the scope of class C. [...]
7978
ObjectType = ParsedType::make(BaseType);
7979
return Base;
7980
}
7981
7982
static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
7983
tok::TokenKind &OpKind, SourceLocation OpLoc) {
7984
if (Base->hasPlaceholderType()) {
7985
ExprResult result = S.CheckPlaceholderExpr(Base);
7986
if (result.isInvalid()) return true;
7987
Base = result.get();
7988
}
7989
ObjectType = Base->getType();
7990
7991
// C++ [expr.pseudo]p2:
7992
// The left-hand side of the dot operator shall be of scalar type. The
7993
// left-hand side of the arrow operator shall be of pointer to scalar type.
7994
// This scalar type is the object type.
7995
// Note that this is rather different from the normal handling for the
7996
// arrow operator.
7997
if (OpKind == tok::arrow) {
7998
// The operator requires a prvalue, so perform lvalue conversions.
7999
// Only do this if we might plausibly end with a pointer, as otherwise
8000
// this was likely to be intended to be a '.'.
8001
if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
8002
ObjectType->isFunctionType()) {
8003
ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base);
8004
if (BaseResult.isInvalid())
8005
return true;
8006
Base = BaseResult.get();
8007
ObjectType = Base->getType();
8008
}
8009
8010
if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
8011
ObjectType = Ptr->getPointeeType();
8012
} else if (!Base->isTypeDependent()) {
8013
// The user wrote "p->" when they probably meant "p."; fix it.
8014
S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
8015
<< ObjectType << true
8016
<< FixItHint::CreateReplacement(OpLoc, ".");
8017
if (S.isSFINAEContext())
8018
return true;
8019
8020
OpKind = tok::period;
8021
}
8022
}
8023
8024
return false;
8025
}
8026
8027
/// Check if it's ok to try and recover dot pseudo destructor calls on
8028
/// pointer objects.
8029
static bool
8030
canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
8031
QualType DestructedType) {
8032
// If this is a record type, check if its destructor is callable.
8033
if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
8034
if (RD->hasDefinition())
8035
if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
8036
return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
8037
return false;
8038
}
8039
8040
// Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
8041
return DestructedType->isDependentType() || DestructedType->isScalarType() ||
8042
DestructedType->isVectorType();
8043
}
8044
8045
ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
8046
SourceLocation OpLoc,
8047
tok::TokenKind OpKind,
8048
const CXXScopeSpec &SS,
8049
TypeSourceInfo *ScopeTypeInfo,
8050
SourceLocation CCLoc,
8051
SourceLocation TildeLoc,
8052
PseudoDestructorTypeStorage Destructed) {
8053
TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
8054
8055
QualType ObjectType;
8056
if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8057
return ExprError();
8058
8059
if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
8060
!ObjectType->isVectorType()) {
8061
if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
8062
Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
8063
else {
8064
Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
8065
<< ObjectType << Base->getSourceRange();
8066
return ExprError();
8067
}
8068
}
8069
8070
// C++ [expr.pseudo]p2:
8071
// [...] The cv-unqualified versions of the object type and of the type
8072
// designated by the pseudo-destructor-name shall be the same type.
8073
if (DestructedTypeInfo) {
8074
QualType DestructedType = DestructedTypeInfo->getType();
8075
SourceLocation DestructedTypeStart =
8076
DestructedTypeInfo->getTypeLoc().getBeginLoc();
8077
if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
8078
if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
8079
// Detect dot pseudo destructor calls on pointer objects, e.g.:
8080
// Foo *foo;
8081
// foo.~Foo();
8082
if (OpKind == tok::period && ObjectType->isPointerType() &&
8083
Context.hasSameUnqualifiedType(DestructedType,
8084
ObjectType->getPointeeType())) {
8085
auto Diagnostic =
8086
Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
8087
<< ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
8088
8089
// Issue a fixit only when the destructor is valid.
8090
if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
8091
*this, DestructedType))
8092
Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
8093
8094
// Recover by setting the object type to the destructed type and the
8095
// operator to '->'.
8096
ObjectType = DestructedType;
8097
OpKind = tok::arrow;
8098
} else {
8099
Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
8100
<< ObjectType << DestructedType << Base->getSourceRange()
8101
<< DestructedTypeInfo->getTypeLoc().getSourceRange();
8102
8103
// Recover by setting the destructed type to the object type.
8104
DestructedType = ObjectType;
8105
DestructedTypeInfo =
8106
Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
8107
Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8108
}
8109
} else if (DestructedType.getObjCLifetime() !=
8110
ObjectType.getObjCLifetime()) {
8111
8112
if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
8113
// Okay: just pretend that the user provided the correctly-qualified
8114
// type.
8115
} else {
8116
Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
8117
<< ObjectType << DestructedType << Base->getSourceRange()
8118
<< DestructedTypeInfo->getTypeLoc().getSourceRange();
8119
}
8120
8121
// Recover by setting the destructed type to the object type.
8122
DestructedType = ObjectType;
8123
DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
8124
DestructedTypeStart);
8125
Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8126
}
8127
}
8128
}
8129
8130
// C++ [expr.pseudo]p2:
8131
// [...] Furthermore, the two type-names in a pseudo-destructor-name of the
8132
// form
8133
//
8134
// ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
8135
//
8136
// shall designate the same scalar type.
8137
if (ScopeTypeInfo) {
8138
QualType ScopeType = ScopeTypeInfo->getType();
8139
if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
8140
!Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
8141
8142
Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
8143
diag::err_pseudo_dtor_type_mismatch)
8144
<< ObjectType << ScopeType << Base->getSourceRange()
8145
<< ScopeTypeInfo->getTypeLoc().getSourceRange();
8146
8147
ScopeType = QualType();
8148
ScopeTypeInfo = nullptr;
8149
}
8150
}
8151
8152
Expr *Result
8153
= new (Context) CXXPseudoDestructorExpr(Context, Base,
8154
OpKind == tok::arrow, OpLoc,
8155
SS.getWithLocInContext(Context),
8156
ScopeTypeInfo,
8157
CCLoc,
8158
TildeLoc,
8159
Destructed);
8160
8161
return Result;
8162
}
8163
8164
ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
8165
SourceLocation OpLoc,
8166
tok::TokenKind OpKind,
8167
CXXScopeSpec &SS,
8168
UnqualifiedId &FirstTypeName,
8169
SourceLocation CCLoc,
8170
SourceLocation TildeLoc,
8171
UnqualifiedId &SecondTypeName) {
8172
assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8173
FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
8174
"Invalid first type name in pseudo-destructor");
8175
assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8176
SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
8177
"Invalid second type name in pseudo-destructor");
8178
8179
QualType ObjectType;
8180
if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8181
return ExprError();
8182
8183
// Compute the object type that we should use for name lookup purposes. Only
8184
// record types and dependent types matter.
8185
ParsedType ObjectTypePtrForLookup;
8186
if (!SS.isSet()) {
8187
if (ObjectType->isRecordType())
8188
ObjectTypePtrForLookup = ParsedType::make(ObjectType);
8189
else if (ObjectType->isDependentType())
8190
ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
8191
}
8192
8193
// Convert the name of the type being destructed (following the ~) into a
8194
// type (with source-location information).
8195
QualType DestructedType;
8196
TypeSourceInfo *DestructedTypeInfo = nullptr;
8197
PseudoDestructorTypeStorage Destructed;
8198
if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
8199
ParsedType T = getTypeName(*SecondTypeName.Identifier,
8200
SecondTypeName.StartLocation,
8201
S, &SS, true, false, ObjectTypePtrForLookup,
8202
/*IsCtorOrDtorName*/true);
8203
if (!T &&
8204
((SS.isSet() && !computeDeclContext(SS, false)) ||
8205
(!SS.isSet() && ObjectType->isDependentType()))) {
8206
// The name of the type being destroyed is a dependent name, and we
8207
// couldn't find anything useful in scope. Just store the identifier and
8208
// it's location, and we'll perform (qualified) name lookup again at
8209
// template instantiation time.
8210
Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
8211
SecondTypeName.StartLocation);
8212
} else if (!T) {
8213
Diag(SecondTypeName.StartLocation,
8214
diag::err_pseudo_dtor_destructor_non_type)
8215
<< SecondTypeName.Identifier << ObjectType;
8216
if (isSFINAEContext())
8217
return ExprError();
8218
8219
// Recover by assuming we had the right type all along.
8220
DestructedType = ObjectType;
8221
} else
8222
DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
8223
} else {
8224
// Resolve the template-id to a type.
8225
TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
8226
ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8227
TemplateId->NumArgs);
8228
TypeResult T = ActOnTemplateIdType(S,
8229
SS,
8230
TemplateId->TemplateKWLoc,
8231
TemplateId->Template,
8232
TemplateId->Name,
8233
TemplateId->TemplateNameLoc,
8234
TemplateId->LAngleLoc,
8235
TemplateArgsPtr,
8236
TemplateId->RAngleLoc,
8237
/*IsCtorOrDtorName*/true);
8238
if (T.isInvalid() || !T.get()) {
8239
// Recover by assuming we had the right type all along.
8240
DestructedType = ObjectType;
8241
} else
8242
DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
8243
}
8244
8245
// If we've performed some kind of recovery, (re-)build the type source
8246
// information.
8247
if (!DestructedType.isNull()) {
8248
if (!DestructedTypeInfo)
8249
DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
8250
SecondTypeName.StartLocation);
8251
Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8252
}
8253
8254
// Convert the name of the scope type (the type prior to '::') into a type.
8255
TypeSourceInfo *ScopeTypeInfo = nullptr;
8256
QualType ScopeType;
8257
if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8258
FirstTypeName.Identifier) {
8259
if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
8260
ParsedType T = getTypeName(*FirstTypeName.Identifier,
8261
FirstTypeName.StartLocation,
8262
S, &SS, true, false, ObjectTypePtrForLookup,
8263
/*IsCtorOrDtorName*/true);
8264
if (!T) {
8265
Diag(FirstTypeName.StartLocation,
8266
diag::err_pseudo_dtor_destructor_non_type)
8267
<< FirstTypeName.Identifier << ObjectType;
8268
8269
if (isSFINAEContext())
8270
return ExprError();
8271
8272
// Just drop this type. It's unnecessary anyway.
8273
ScopeType = QualType();
8274
} else
8275
ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
8276
} else {
8277
// Resolve the template-id to a type.
8278
TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
8279
ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8280
TemplateId->NumArgs);
8281
TypeResult T = ActOnTemplateIdType(S,
8282
SS,
8283
TemplateId->TemplateKWLoc,
8284
TemplateId->Template,
8285
TemplateId->Name,
8286
TemplateId->TemplateNameLoc,
8287
TemplateId->LAngleLoc,
8288
TemplateArgsPtr,
8289
TemplateId->RAngleLoc,
8290
/*IsCtorOrDtorName*/true);
8291
if (T.isInvalid() || !T.get()) {
8292
// Recover by dropping this type.
8293
ScopeType = QualType();
8294
} else
8295
ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
8296
}
8297
}
8298
8299
if (!ScopeType.isNull() && !ScopeTypeInfo)
8300
ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
8301
FirstTypeName.StartLocation);
8302
8303
8304
return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
8305
ScopeTypeInfo, CCLoc, TildeLoc,
8306
Destructed);
8307
}
8308
8309
ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
8310
SourceLocation OpLoc,
8311
tok::TokenKind OpKind,
8312
SourceLocation TildeLoc,
8313
const DeclSpec& DS) {
8314
QualType ObjectType;
8315
QualType T;
8316
TypeLocBuilder TLB;
8317
if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8318
return ExprError();
8319
8320
switch (DS.getTypeSpecType()) {
8321
case DeclSpec::TST_decltype_auto: {
8322
Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
8323
return true;
8324
}
8325
case DeclSpec::TST_decltype: {
8326
T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
8327
DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
8328
DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
8329
DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
8330
break;
8331
}
8332
case DeclSpec::TST_typename_pack_indexing: {
8333
T = ActOnPackIndexingType(DS.getRepAsType().get(), DS.getPackIndexingExpr(),
8334
DS.getBeginLoc(), DS.getEllipsisLoc());
8335
TLB.pushTrivial(getASTContext(),
8336
cast<PackIndexingType>(T.getTypePtr())->getPattern(),
8337
DS.getBeginLoc());
8338
PackIndexingTypeLoc PITL = TLB.push<PackIndexingTypeLoc>(T);
8339
PITL.setEllipsisLoc(DS.getEllipsisLoc());
8340
break;
8341
}
8342
default:
8343
llvm_unreachable("Unsupported type in pseudo destructor");
8344
}
8345
TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
8346
PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
8347
8348
return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
8349
nullptr, SourceLocation(), TildeLoc,
8350
Destructed);
8351
}
8352
8353
ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
8354
SourceLocation RParen) {
8355
// If the operand is an unresolved lookup expression, the expression is ill-
8356
// formed per [over.over]p1, because overloaded function names cannot be used
8357
// without arguments except in explicit contexts.
8358
ExprResult R = CheckPlaceholderExpr(Operand);
8359
if (R.isInvalid())
8360
return R;
8361
8362
R = CheckUnevaluatedOperand(R.get());
8363
if (R.isInvalid())
8364
return ExprError();
8365
8366
Operand = R.get();
8367
8368
if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
8369
Operand->HasSideEffects(Context, false)) {
8370
// The expression operand for noexcept is in an unevaluated expression
8371
// context, so side effects could result in unintended consequences.
8372
Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8373
}
8374
8375
CanThrowResult CanThrow = canThrow(Operand);
8376
return new (Context)
8377
CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
8378
}
8379
8380
ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
8381
Expr *Operand, SourceLocation RParen) {
8382
return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
8383
}
8384
8385
static void MaybeDecrementCount(
8386
Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
8387
DeclRefExpr *LHS = nullptr;
8388
bool IsCompoundAssign = false;
8389
bool isIncrementDecrementUnaryOp = false;
8390
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8391
if (BO->getLHS()->getType()->isDependentType() ||
8392
BO->getRHS()->getType()->isDependentType()) {
8393
if (BO->getOpcode() != BO_Assign)
8394
return;
8395
} else if (!BO->isAssignmentOp())
8396
return;
8397
else
8398
IsCompoundAssign = BO->isCompoundAssignmentOp();
8399
LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
8400
} else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
8401
if (COCE->getOperator() != OO_Equal)
8402
return;
8403
LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
8404
} else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8405
if (!UO->isIncrementDecrementOp())
8406
return;
8407
isIncrementDecrementUnaryOp = true;
8408
LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());
8409
}
8410
if (!LHS)
8411
return;
8412
VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
8413
if (!VD)
8414
return;
8415
// Don't decrement RefsMinusAssignments if volatile variable with compound
8416
// assignment (+=, ...) or increment/decrement unary operator to avoid
8417
// potential unused-but-set-variable warning.
8418
if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&
8419
VD->getType().isVolatileQualified())
8420
return;
8421
auto iter = RefsMinusAssignments.find(VD);
8422
if (iter == RefsMinusAssignments.end())
8423
return;
8424
iter->getSecond()--;
8425
}
8426
8427
/// Perform the conversions required for an expression used in a
8428
/// context that ignores the result.
8429
ExprResult Sema::IgnoredValueConversions(Expr *E) {
8430
MaybeDecrementCount(E, RefsMinusAssignments);
8431
8432
if (E->hasPlaceholderType()) {
8433
ExprResult result = CheckPlaceholderExpr(E);
8434
if (result.isInvalid()) return E;
8435
E = result.get();
8436
}
8437
8438
if (getLangOpts().CPlusPlus) {
8439
// The C++11 standard defines the notion of a discarded-value expression;
8440
// normally, we don't need to do anything to handle it, but if it is a
8441
// volatile lvalue with a special form, we perform an lvalue-to-rvalue
8442
// conversion.
8443
if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) {
8444
ExprResult Res = DefaultLvalueConversion(E);
8445
if (Res.isInvalid())
8446
return E;
8447
E = Res.get();
8448
} else {
8449
// Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8450
// it occurs as a discarded-value expression.
8451
CheckUnusedVolatileAssignment(E);
8452
}
8453
8454
// C++1z:
8455
// If the expression is a prvalue after this optional conversion, the
8456
// temporary materialization conversion is applied.
8457
//
8458
// We do not materialize temporaries by default in order to avoid creating
8459
// unnecessary temporary objects. If we skip this step, IR generation is
8460
// able to synthesize the storage for itself in the aggregate case, and
8461
// adding the extra node to the AST is just clutter.
8462
if (isInLifetimeExtendingContext() && getLangOpts().CPlusPlus17 &&
8463
E->isPRValue() && !E->getType()->isVoidType()) {
8464
ExprResult Res = TemporaryMaterializationConversion(E);
8465
if (Res.isInvalid())
8466
return E;
8467
E = Res.get();
8468
}
8469
return E;
8470
}
8471
8472
// C99 6.3.2.1:
8473
// [Except in specific positions,] an lvalue that does not have
8474
// array type is converted to the value stored in the
8475
// designated object (and is no longer an lvalue).
8476
if (E->isPRValue()) {
8477
// In C, function designators (i.e. expressions of function type)
8478
// are r-values, but we still want to do function-to-pointer decay
8479
// on them. This is both technically correct and convenient for
8480
// some clients.
8481
if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
8482
return DefaultFunctionArrayConversion(E);
8483
8484
return E;
8485
}
8486
8487
// GCC seems to also exclude expressions of incomplete enum type.
8488
if (const EnumType *T = E->getType()->getAs<EnumType>()) {
8489
if (!T->getDecl()->isComplete()) {
8490
// FIXME: stupid workaround for a codegen bug!
8491
E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
8492
return E;
8493
}
8494
}
8495
8496
ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
8497
if (Res.isInvalid())
8498
return E;
8499
E = Res.get();
8500
8501
if (!E->getType()->isVoidType())
8502
RequireCompleteType(E->getExprLoc(), E->getType(),
8503
diag::err_incomplete_type);
8504
return E;
8505
}
8506
8507
ExprResult Sema::CheckUnevaluatedOperand(Expr *E) {
8508
// Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8509
// it occurs as an unevaluated operand.
8510
CheckUnusedVolatileAssignment(E);
8511
8512
return E;
8513
}
8514
8515
// If we can unambiguously determine whether Var can never be used
8516
// in a constant expression, return true.
8517
// - if the variable and its initializer are non-dependent, then
8518
// we can unambiguously check if the variable is a constant expression.
8519
// - if the initializer is not value dependent - we can determine whether
8520
// it can be used to initialize a constant expression. If Init can not
8521
// be used to initialize a constant expression we conclude that Var can
8522
// never be a constant expression.
8523
// - FXIME: if the initializer is dependent, we can still do some analysis and
8524
// identify certain cases unambiguously as non-const by using a Visitor:
8525
// - such as those that involve odr-use of a ParmVarDecl, involve a new
8526
// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
8527
static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
8528
ASTContext &Context) {
8529
if (isa<ParmVarDecl>(Var)) return true;
8530
const VarDecl *DefVD = nullptr;
8531
8532
// If there is no initializer - this can not be a constant expression.
8533
const Expr *Init = Var->getAnyInitializer(DefVD);
8534
if (!Init)
8535
return true;
8536
assert(DefVD);
8537
if (DefVD->isWeak())
8538
return false;
8539
8540
if (Var->getType()->isDependentType() || Init->isValueDependent()) {
8541
// FIXME: Teach the constant evaluator to deal with the non-dependent parts
8542
// of value-dependent expressions, and use it here to determine whether the
8543
// initializer is a potential constant expression.
8544
return false;
8545
}
8546
8547
return !Var->isUsableInConstantExpressions(Context);
8548
}
8549
8550
/// Check if the current lambda has any potential captures
8551
/// that must be captured by any of its enclosing lambdas that are ready to
8552
/// capture. If there is a lambda that can capture a nested
8553
/// potential-capture, go ahead and do so. Also, check to see if any
8554
/// variables are uncaptureable or do not involve an odr-use so do not
8555
/// need to be captured.
8556
8557
static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
8558
Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
8559
8560
assert(!S.isUnevaluatedContext());
8561
assert(S.CurContext->isDependentContext());
8562
#ifndef NDEBUG
8563
DeclContext *DC = S.CurContext;
8564
while (isa_and_nonnull<CapturedDecl>(DC))
8565
DC = DC->getParent();
8566
assert(
8567
CurrentLSI->CallOperator == DC &&
8568
"The current call operator must be synchronized with Sema's CurContext");
8569
#endif // NDEBUG
8570
8571
const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
8572
8573
// All the potentially captureable variables in the current nested
8574
// lambda (within a generic outer lambda), must be captured by an
8575
// outer lambda that is enclosed within a non-dependent context.
8576
CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) {
8577
// If the variable is clearly identified as non-odr-used and the full
8578
// expression is not instantiation dependent, only then do we not
8579
// need to check enclosing lambda's for speculative captures.
8580
// For e.g.:
8581
// Even though 'x' is not odr-used, it should be captured.
8582
// int test() {
8583
// const int x = 10;
8584
// auto L = [=](auto a) {
8585
// (void) +x + a;
8586
// };
8587
// }
8588
if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
8589
!IsFullExprInstantiationDependent)
8590
return;
8591
8592
VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();
8593
if (!UnderlyingVar)
8594
return;
8595
8596
// If we have a capture-capable lambda for the variable, go ahead and
8597
// capture the variable in that lambda (and all its enclosing lambdas).
8598
if (const std::optional<unsigned> Index =
8599
getStackIndexOfNearestEnclosingCaptureCapableLambda(
8600
S.FunctionScopes, Var, S))
8601
S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);
8602
const bool IsVarNeverAConstantExpression =
8603
VariableCanNeverBeAConstantExpression(UnderlyingVar, S.Context);
8604
if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
8605
// This full expression is not instantiation dependent or the variable
8606
// can not be used in a constant expression - which means
8607
// this variable must be odr-used here, so diagnose a
8608
// capture violation early, if the variable is un-captureable.
8609
// This is purely for diagnosing errors early. Otherwise, this
8610
// error would get diagnosed when the lambda becomes capture ready.
8611
QualType CaptureType, DeclRefType;
8612
SourceLocation ExprLoc = VarExpr->getExprLoc();
8613
if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8614
/*EllipsisLoc*/ SourceLocation(),
8615
/*BuildAndDiagnose*/false, CaptureType,
8616
DeclRefType, nullptr)) {
8617
// We will never be able to capture this variable, and we need
8618
// to be able to in any and all instantiations, so diagnose it.
8619
S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8620
/*EllipsisLoc*/ SourceLocation(),
8621
/*BuildAndDiagnose*/true, CaptureType,
8622
DeclRefType, nullptr);
8623
}
8624
}
8625
});
8626
8627
// Check if 'this' needs to be captured.
8628
if (CurrentLSI->hasPotentialThisCapture()) {
8629
// If we have a capture-capable lambda for 'this', go ahead and capture
8630
// 'this' in that lambda (and all its enclosing lambdas).
8631
if (const std::optional<unsigned> Index =
8632
getStackIndexOfNearestEnclosingCaptureCapableLambda(
8633
S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
8634
const unsigned FunctionScopeIndexOfCapturableLambda = *Index;
8635
S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
8636
/*Explicit*/ false, /*BuildAndDiagnose*/ true,
8637
&FunctionScopeIndexOfCapturableLambda);
8638
}
8639
}
8640
8641
// Reset all the potential captures at the end of each full-expression.
8642
CurrentLSI->clearPotentialCaptures();
8643
}
8644
8645
static ExprResult attemptRecovery(Sema &SemaRef,
8646
const TypoCorrectionConsumer &Consumer,
8647
const TypoCorrection &TC) {
8648
LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
8649
Consumer.getLookupResult().getLookupKind());
8650
const CXXScopeSpec *SS = Consumer.getSS();
8651
CXXScopeSpec NewSS;
8652
8653
// Use an approprate CXXScopeSpec for building the expr.
8654
if (auto *NNS = TC.getCorrectionSpecifier())
8655
NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
8656
else if (SS && !TC.WillReplaceSpecifier())
8657
NewSS = *SS;
8658
8659
if (auto *ND = TC.getFoundDecl()) {
8660
R.setLookupName(ND->getDeclName());
8661
R.addDecl(ND);
8662
if (ND->isCXXClassMember()) {
8663
// Figure out the correct naming class to add to the LookupResult.
8664
CXXRecordDecl *Record = nullptr;
8665
if (auto *NNS = TC.getCorrectionSpecifier())
8666
Record = NNS->getAsType()->getAsCXXRecordDecl();
8667
if (!Record)
8668
Record =
8669
dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
8670
if (Record)
8671
R.setNamingClass(Record);
8672
8673
// Detect and handle the case where the decl might be an implicit
8674
// member.
8675
if (SemaRef.isPotentialImplicitMemberAccess(
8676
NewSS, R, Consumer.isAddressOfOperand()))
8677
return SemaRef.BuildPossibleImplicitMemberExpr(
8678
NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
8679
/*TemplateArgs*/ nullptr, /*S*/ nullptr);
8680
} else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
8681
return SemaRef.ObjC().LookupInObjCMethod(R, Consumer.getScope(),
8682
Ivar->getIdentifier());
8683
}
8684
}
8685
8686
return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
8687
/*AcceptInvalidDecl*/ true);
8688
}
8689
8690
namespace {
8691
class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
8692
llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
8693
8694
public:
8695
explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
8696
: TypoExprs(TypoExprs) {}
8697
bool VisitTypoExpr(TypoExpr *TE) {
8698
TypoExprs.insert(TE);
8699
return true;
8700
}
8701
};
8702
8703
class TransformTypos : public TreeTransform<TransformTypos> {
8704
typedef TreeTransform<TransformTypos> BaseTransform;
8705
8706
VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
8707
// process of being initialized.
8708
llvm::function_ref<ExprResult(Expr *)> ExprFilter;
8709
llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
8710
llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
8711
llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
8712
8713
/// Emit diagnostics for all of the TypoExprs encountered.
8714
///
8715
/// If the TypoExprs were successfully corrected, then the diagnostics should
8716
/// suggest the corrections. Otherwise the diagnostics will not suggest
8717
/// anything (having been passed an empty TypoCorrection).
8718
///
8719
/// If we've failed to correct due to ambiguous corrections, we need to
8720
/// be sure to pass empty corrections and replacements. Otherwise it's
8721
/// possible that the Consumer has a TypoCorrection that failed to ambiguity
8722
/// and we don't want to report those diagnostics.
8723
void EmitAllDiagnostics(bool IsAmbiguous) {
8724
for (TypoExpr *TE : TypoExprs) {
8725
auto &State = SemaRef.getTypoExprState(TE);
8726
if (State.DiagHandler) {
8727
TypoCorrection TC = IsAmbiguous
8728
? TypoCorrection() : State.Consumer->getCurrentCorrection();
8729
ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
8730
8731
// Extract the NamedDecl from the transformed TypoExpr and add it to the
8732
// TypoCorrection, replacing the existing decls. This ensures the right
8733
// NamedDecl is used in diagnostics e.g. in the case where overload
8734
// resolution was used to select one from several possible decls that
8735
// had been stored in the TypoCorrection.
8736
if (auto *ND = getDeclFromExpr(
8737
Replacement.isInvalid() ? nullptr : Replacement.get()))
8738
TC.setCorrectionDecl(ND);
8739
8740
State.DiagHandler(TC);
8741
}
8742
SemaRef.clearDelayedTypo(TE);
8743
}
8744
}
8745
8746
/// Try to advance the typo correction state of the first unfinished TypoExpr.
8747
/// We allow advancement of the correction stream by removing it from the
8748
/// TransformCache which allows `TransformTypoExpr` to advance during the
8749
/// next transformation attempt.
8750
///
8751
/// Any substitution attempts for the previous TypoExprs (which must have been
8752
/// finished) will need to be retried since it's possible that they will now
8753
/// be invalid given the latest advancement.
8754
///
8755
/// We need to be sure that we're making progress - it's possible that the
8756
/// tree is so malformed that the transform never makes it to the
8757
/// `TransformTypoExpr`.
8758
///
8759
/// Returns true if there are any untried correction combinations.
8760
bool CheckAndAdvanceTypoExprCorrectionStreams() {
8761
for (auto *TE : TypoExprs) {
8762
auto &State = SemaRef.getTypoExprState(TE);
8763
TransformCache.erase(TE);
8764
if (!State.Consumer->hasMadeAnyCorrectionProgress())
8765
return false;
8766
if (!State.Consumer->finished())
8767
return true;
8768
State.Consumer->resetCorrectionStream();
8769
}
8770
return false;
8771
}
8772
8773
NamedDecl *getDeclFromExpr(Expr *E) {
8774
if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
8775
E = OverloadResolution[OE];
8776
8777
if (!E)
8778
return nullptr;
8779
if (auto *DRE = dyn_cast<DeclRefExpr>(E))
8780
return DRE->getFoundDecl();
8781
if (auto *ME = dyn_cast<MemberExpr>(E))
8782
return ME->getFoundDecl();
8783
// FIXME: Add any other expr types that could be seen by the delayed typo
8784
// correction TreeTransform for which the corresponding TypoCorrection could
8785
// contain multiple decls.
8786
return nullptr;
8787
}
8788
8789
ExprResult TryTransform(Expr *E) {
8790
Sema::SFINAETrap Trap(SemaRef);
8791
ExprResult Res = TransformExpr(E);
8792
if (Trap.hasErrorOccurred() || Res.isInvalid())
8793
return ExprError();
8794
8795
return ExprFilter(Res.get());
8796
}
8797
8798
// Since correcting typos may intoduce new TypoExprs, this function
8799
// checks for new TypoExprs and recurses if it finds any. Note that it will
8800
// only succeed if it is able to correct all typos in the given expression.
8801
ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
8802
if (Res.isInvalid()) {
8803
return Res;
8804
}
8805
// Check to see if any new TypoExprs were created. If so, we need to recurse
8806
// to check their validity.
8807
Expr *FixedExpr = Res.get();
8808
8809
auto SavedTypoExprs = std::move(TypoExprs);
8810
auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
8811
TypoExprs.clear();
8812
AmbiguousTypoExprs.clear();
8813
8814
FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
8815
if (!TypoExprs.empty()) {
8816
// Recurse to handle newly created TypoExprs. If we're not able to
8817
// handle them, discard these TypoExprs.
8818
ExprResult RecurResult =
8819
RecursiveTransformLoop(FixedExpr, IsAmbiguous);
8820
if (RecurResult.isInvalid()) {
8821
Res = ExprError();
8822
// Recursive corrections didn't work, wipe them away and don't add
8823
// them to the TypoExprs set. Remove them from Sema's TypoExpr list
8824
// since we don't want to clear them twice. Note: it's possible the
8825
// TypoExprs were created recursively and thus won't be in our
8826
// Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8827
auto &SemaTypoExprs = SemaRef.TypoExprs;
8828
for (auto *TE : TypoExprs) {
8829
TransformCache.erase(TE);
8830
SemaRef.clearDelayedTypo(TE);
8831
8832
auto SI = find(SemaTypoExprs, TE);
8833
if (SI != SemaTypoExprs.end()) {
8834
SemaTypoExprs.erase(SI);
8835
}
8836
}
8837
} else {
8838
// TypoExpr is valid: add newly created TypoExprs since we were
8839
// able to correct them.
8840
Res = RecurResult;
8841
SavedTypoExprs.set_union(TypoExprs);
8842
}
8843
}
8844
8845
TypoExprs = std::move(SavedTypoExprs);
8846
AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
8847
8848
return Res;
8849
}
8850
8851
// Try to transform the given expression, looping through the correction
8852
// candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8853
//
8854
// If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
8855
// true and this method immediately will return an `ExprError`.
8856
ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
8857
ExprResult Res;
8858
auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8859
SemaRef.TypoExprs.clear();
8860
8861
while (true) {
8862
Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8863
8864
// Recursion encountered an ambiguous correction. This means that our
8865
// correction itself is ambiguous, so stop now.
8866
if (IsAmbiguous)
8867
break;
8868
8869
// If the transform is still valid after checking for any new typos,
8870
// it's good to go.
8871
if (!Res.isInvalid())
8872
break;
8873
8874
// The transform was invalid, see if we have any TypoExprs with untried
8875
// correction candidates.
8876
if (!CheckAndAdvanceTypoExprCorrectionStreams())
8877
break;
8878
}
8879
8880
// If we found a valid result, double check to make sure it's not ambiguous.
8881
if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
8882
auto SavedTransformCache =
8883
llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8884
8885
// Ensure none of the TypoExprs have multiple typo correction candidates
8886
// with the same edit length that pass all the checks and filters.
8887
while (!AmbiguousTypoExprs.empty()) {
8888
auto TE = AmbiguousTypoExprs.back();
8889
8890
// TryTransform itself can create new Typos, adding them to the TypoExpr map
8891
// and invalidating our TypoExprState, so always fetch it instead of storing.
8892
SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8893
8894
TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8895
TypoCorrection Next;
8896
do {
8897
// Fetch the next correction by erasing the typo from the cache and calling
8898
// `TryTransform` which will iterate through corrections in
8899
// `TransformTypoExpr`.
8900
TransformCache.erase(TE);
8901
ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8902
8903
if (!AmbigRes.isInvalid() || IsAmbiguous) {
8904
SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8905
SavedTransformCache.erase(TE);
8906
Res = ExprError();
8907
IsAmbiguous = true;
8908
break;
8909
}
8910
} while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8911
Next.getEditDistance(false) == TC.getEditDistance(false));
8912
8913
if (IsAmbiguous)
8914
break;
8915
8916
AmbiguousTypoExprs.remove(TE);
8917
SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
8918
TransformCache[TE] = SavedTransformCache[TE];
8919
}
8920
TransformCache = std::move(SavedTransformCache);
8921
}
8922
8923
// Wipe away any newly created TypoExprs that we don't know about. Since we
8924
// clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8925
// possible if a `TypoExpr` is created during a transformation but then
8926
// fails before we can discover it.
8927
auto &SemaTypoExprs = SemaRef.TypoExprs;
8928
for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
8929
auto TE = *Iterator;
8930
auto FI = find(TypoExprs, TE);
8931
if (FI != TypoExprs.end()) {
8932
Iterator++;
8933
continue;
8934
}
8935
SemaRef.clearDelayedTypo(TE);
8936
Iterator = SemaTypoExprs.erase(Iterator);
8937
}
8938
SemaRef.TypoExprs = std::move(SavedTypoExprs);
8939
8940
return Res;
8941
}
8942
8943
public:
8944
TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
8945
: BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
8946
8947
ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
8948
MultiExprArg Args,
8949
SourceLocation RParenLoc,
8950
Expr *ExecConfig = nullptr) {
8951
auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
8952
RParenLoc, ExecConfig);
8953
if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
8954
if (Result.isUsable()) {
8955
Expr *ResultCall = Result.get();
8956
if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
8957
ResultCall = BE->getSubExpr();
8958
if (auto *CE = dyn_cast<CallExpr>(ResultCall))
8959
OverloadResolution[OE] = CE->getCallee();
8960
}
8961
}
8962
return Result;
8963
}
8964
8965
ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
8966
8967
ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
8968
8969
ExprResult Transform(Expr *E) {
8970
bool IsAmbiguous = false;
8971
ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
8972
8973
if (!Res.isUsable())
8974
FindTypoExprs(TypoExprs).TraverseStmt(E);
8975
8976
EmitAllDiagnostics(IsAmbiguous);
8977
8978
return Res;
8979
}
8980
8981
ExprResult TransformTypoExpr(TypoExpr *E) {
8982
// If the TypoExpr hasn't been seen before, record it. Otherwise, return the
8983
// cached transformation result if there is one and the TypoExpr isn't the
8984
// first one that was encountered.
8985
auto &CacheEntry = TransformCache[E];
8986
if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
8987
return CacheEntry;
8988
}
8989
8990
auto &State = SemaRef.getTypoExprState(E);
8991
assert(State.Consumer && "Cannot transform a cleared TypoExpr");
8992
8993
// For the first TypoExpr and an uncached TypoExpr, find the next likely
8994
// typo correction and return it.
8995
while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
8996
if (InitDecl && TC.getFoundDecl() == InitDecl)
8997
continue;
8998
// FIXME: If we would typo-correct to an invalid declaration, it's
8999
// probably best to just suppress all errors from this typo correction.
9000
ExprResult NE = State.RecoveryHandler ?
9001
State.RecoveryHandler(SemaRef, E, TC) :
9002
attemptRecovery(SemaRef, *State.Consumer, TC);
9003
if (!NE.isInvalid()) {
9004
// Check whether there may be a second viable correction with the same
9005
// edit distance; if so, remember this TypoExpr may have an ambiguous
9006
// correction so it can be more thoroughly vetted later.
9007
TypoCorrection Next;
9008
if ((Next = State.Consumer->peekNextCorrection()) &&
9009
Next.getEditDistance(false) == TC.getEditDistance(false)) {
9010
AmbiguousTypoExprs.insert(E);
9011
} else {
9012
AmbiguousTypoExprs.remove(E);
9013
}
9014
assert(!NE.isUnset() &&
9015
"Typo was transformed into a valid-but-null ExprResult");
9016
return CacheEntry = NE;
9017
}
9018
}
9019
return CacheEntry = ExprError();
9020
}
9021
};
9022
}
9023
9024
ExprResult
9025
Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
9026
bool RecoverUncorrectedTypos,
9027
llvm::function_ref<ExprResult(Expr *)> Filter) {
9028
// If the current evaluation context indicates there are uncorrected typos
9029
// and the current expression isn't guaranteed to not have typos, try to
9030
// resolve any TypoExpr nodes that might be in the expression.
9031
if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
9032
(E->isTypeDependent() || E->isValueDependent() ||
9033
E->isInstantiationDependent())) {
9034
auto TyposResolved = DelayedTypos.size();
9035
auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
9036
TyposResolved -= DelayedTypos.size();
9037
if (Result.isInvalid() || Result.get() != E) {
9038
ExprEvalContexts.back().NumTypos -= TyposResolved;
9039
if (Result.isInvalid() && RecoverUncorrectedTypos) {
9040
struct TyposReplace : TreeTransform<TyposReplace> {
9041
TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {}
9042
ExprResult TransformTypoExpr(clang::TypoExpr *E) {
9043
return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(),
9044
E->getEndLoc(), {});
9045
}
9046
} TT(*this);
9047
return TT.TransformExpr(E);
9048
}
9049
return Result;
9050
}
9051
assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
9052
}
9053
return E;
9054
}
9055
9056
ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
9057
bool DiscardedValue, bool IsConstexpr,
9058
bool IsTemplateArgument) {
9059
ExprResult FullExpr = FE;
9060
9061
if (!FullExpr.get())
9062
return ExprError();
9063
9064
if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get()))
9065
return ExprError();
9066
9067
if (DiscardedValue) {
9068
// Top-level expressions default to 'id' when we're in a debugger.
9069
if (getLangOpts().DebuggerCastResultToId &&
9070
FullExpr.get()->getType() == Context.UnknownAnyTy) {
9071
FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
9072
if (FullExpr.isInvalid())
9073
return ExprError();
9074
}
9075
9076
FullExpr = CheckPlaceholderExpr(FullExpr.get());
9077
if (FullExpr.isInvalid())
9078
return ExprError();
9079
9080
FullExpr = IgnoredValueConversions(FullExpr.get());
9081
if (FullExpr.isInvalid())
9082
return ExprError();
9083
9084
DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
9085
}
9086
9087
FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr,
9088
/*RecoverUncorrectedTypos=*/true);
9089
if (FullExpr.isInvalid())
9090
return ExprError();
9091
9092
CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
9093
9094
// At the end of this full expression (which could be a deeply nested
9095
// lambda), if there is a potential capture within the nested lambda,
9096
// have the outer capture-able lambda try and capture it.
9097
// Consider the following code:
9098
// void f(int, int);
9099
// void f(const int&, double);
9100
// void foo() {
9101
// const int x = 10, y = 20;
9102
// auto L = [=](auto a) {
9103
// auto M = [=](auto b) {
9104
// f(x, b); <-- requires x to be captured by L and M
9105
// f(y, a); <-- requires y to be captured by L, but not all Ms
9106
// };
9107
// };
9108
// }
9109
9110
// FIXME: Also consider what happens for something like this that involves
9111
// the gnu-extension statement-expressions or even lambda-init-captures:
9112
// void f() {
9113
// const int n = 0;
9114
// auto L = [&](auto a) {
9115
// +n + ({ 0; a; });
9116
// };
9117
// }
9118
//
9119
// Here, we see +n, and then the full-expression 0; ends, so we don't
9120
// capture n (and instead remove it from our list of potential captures),
9121
// and then the full-expression +n + ({ 0; }); ends, but it's too late
9122
// for us to see that we need to capture n after all.
9123
9124
LambdaScopeInfo *const CurrentLSI =
9125
getCurLambda(/*IgnoreCapturedRegions=*/true);
9126
// FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
9127
// even if CurContext is not a lambda call operator. Refer to that Bug Report
9128
// for an example of the code that might cause this asynchrony.
9129
// By ensuring we are in the context of a lambda's call operator
9130
// we can fix the bug (we only need to check whether we need to capture
9131
// if we are within a lambda's body); but per the comments in that
9132
// PR, a proper fix would entail :
9133
// "Alternative suggestion:
9134
// - Add to Sema an integer holding the smallest (outermost) scope
9135
// index that we are *lexically* within, and save/restore/set to
9136
// FunctionScopes.size() in InstantiatingTemplate's
9137
// constructor/destructor.
9138
// - Teach the handful of places that iterate over FunctionScopes to
9139
// stop at the outermost enclosing lexical scope."
9140
DeclContext *DC = CurContext;
9141
while (isa_and_nonnull<CapturedDecl>(DC))
9142
DC = DC->getParent();
9143
const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
9144
if (IsInLambdaDeclContext && CurrentLSI &&
9145
CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
9146
CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
9147
*this);
9148
return MaybeCreateExprWithCleanups(FullExpr);
9149
}
9150
9151
StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
9152
if (!FullStmt) return StmtError();
9153
9154
return MaybeCreateStmtWithCleanups(FullStmt);
9155
}
9156
9157
Sema::IfExistsResult
9158
Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
9159
CXXScopeSpec &SS,
9160
const DeclarationNameInfo &TargetNameInfo) {
9161
DeclarationName TargetName = TargetNameInfo.getName();
9162
if (!TargetName)
9163
return IER_DoesNotExist;
9164
9165
// If the name itself is dependent, then the result is dependent.
9166
if (TargetName.isDependentName())
9167
return IER_Dependent;
9168
9169
// Do the redeclaration lookup in the current scope.
9170
LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
9171
RedeclarationKind::NotForRedeclaration);
9172
LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
9173
R.suppressDiagnostics();
9174
9175
switch (R.getResultKind()) {
9176
case LookupResult::Found:
9177
case LookupResult::FoundOverloaded:
9178
case LookupResult::FoundUnresolvedValue:
9179
case LookupResult::Ambiguous:
9180
return IER_Exists;
9181
9182
case LookupResult::NotFound:
9183
return IER_DoesNotExist;
9184
9185
case LookupResult::NotFoundInCurrentInstantiation:
9186
return IER_Dependent;
9187
}
9188
9189
llvm_unreachable("Invalid LookupResult Kind!");
9190
}
9191
9192
Sema::IfExistsResult
9193
Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
9194
bool IsIfExists, CXXScopeSpec &SS,
9195
UnqualifiedId &Name) {
9196
DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9197
9198
// Check for an unexpanded parameter pack.
9199
auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
9200
if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
9201
DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
9202
return IER_Error;
9203
9204
return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
9205
}
9206
9207
concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) {
9208
return BuildExprRequirement(E, /*IsSimple=*/true,
9209
/*NoexceptLoc=*/SourceLocation(),
9210
/*ReturnTypeRequirement=*/{});
9211
}
9212
9213
concepts::Requirement *Sema::ActOnTypeRequirement(
9214
SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
9215
const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) {
9216
assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
9217
"Exactly one of TypeName and TemplateId must be specified.");
9218
TypeSourceInfo *TSI = nullptr;
9219
if (TypeName) {
9220
QualType T =
9221
CheckTypenameType(ElaboratedTypeKeyword::Typename, TypenameKWLoc,
9222
SS.getWithLocInContext(Context), *TypeName, NameLoc,
9223
&TSI, /*DeducedTSTContext=*/false);
9224
if (T.isNull())
9225
return nullptr;
9226
} else {
9227
ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
9228
TemplateId->NumArgs);
9229
TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
9230
TemplateId->TemplateKWLoc,
9231
TemplateId->Template, TemplateId->Name,
9232
TemplateId->TemplateNameLoc,
9233
TemplateId->LAngleLoc, ArgsPtr,
9234
TemplateId->RAngleLoc);
9235
if (T.isInvalid())
9236
return nullptr;
9237
if (GetTypeFromParser(T.get(), &TSI).isNull())
9238
return nullptr;
9239
}
9240
return BuildTypeRequirement(TSI);
9241
}
9242
9243
concepts::Requirement *
9244
Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) {
9245
return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
9246
/*ReturnTypeRequirement=*/{});
9247
}
9248
9249
concepts::Requirement *
9250
Sema::ActOnCompoundRequirement(
9251
Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
9252
TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
9253
// C++2a [expr.prim.req.compound] p1.3.3
9254
// [..] the expression is deduced against an invented function template
9255
// F [...] F is a void function template with a single type template
9256
// parameter T declared with the constrained-parameter. Form a new
9257
// cv-qualifier-seq cv by taking the union of const and volatile specifiers
9258
// around the constrained-parameter. F has a single parameter whose
9259
// type-specifier is cv T followed by the abstract-declarator. [...]
9260
//
9261
// The cv part is done in the calling function - we get the concept with
9262
// arguments and the abstract declarator with the correct CV qualification and
9263
// have to synthesize T and the single parameter of F.
9264
auto &II = Context.Idents.get("expr-type");
9265
auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext,
9266
SourceLocation(),
9267
SourceLocation(), Depth,
9268
/*Index=*/0, &II,
9269
/*Typename=*/true,
9270
/*ParameterPack=*/false,
9271
/*HasTypeConstraint=*/true);
9272
9273
if (BuildTypeConstraint(SS, TypeConstraint, TParam,
9274
/*EllipsisLoc=*/SourceLocation(),
9275
/*AllowUnexpandedPack=*/true))
9276
// Just produce a requirement with no type requirements.
9277
return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
9278
9279
auto *TPL = TemplateParameterList::Create(Context, SourceLocation(),
9280
SourceLocation(),
9281
ArrayRef<NamedDecl *>(TParam),
9282
SourceLocation(),
9283
/*RequiresClause=*/nullptr);
9284
return BuildExprRequirement(
9285
E, /*IsSimple=*/false, NoexceptLoc,
9286
concepts::ExprRequirement::ReturnTypeRequirement(TPL));
9287
}
9288
9289
concepts::ExprRequirement *
9290
Sema::BuildExprRequirement(
9291
Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
9292
concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
9293
auto Status = concepts::ExprRequirement::SS_Satisfied;
9294
ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
9295
if (E->isInstantiationDependent() || E->getType()->isPlaceholderType() ||
9296
ReturnTypeRequirement.isDependent())
9297
Status = concepts::ExprRequirement::SS_Dependent;
9298
else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
9299
Status = concepts::ExprRequirement::SS_NoexceptNotMet;
9300
else if (ReturnTypeRequirement.isSubstitutionFailure())
9301
Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure;
9302
else if (ReturnTypeRequirement.isTypeConstraint()) {
9303
// C++2a [expr.prim.req]p1.3.3
9304
// The immediately-declared constraint ([temp]) of decltype((E)) shall
9305
// be satisfied.
9306
TemplateParameterList *TPL =
9307
ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
9308
QualType MatchedType =
9309
Context.getReferenceQualifiedType(E).getCanonicalType();
9310
llvm::SmallVector<TemplateArgument, 1> Args;
9311
Args.push_back(TemplateArgument(MatchedType));
9312
9313
auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0));
9314
9315
MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/false);
9316
MLTAL.addOuterRetainedLevels(TPL->getDepth());
9317
const TypeConstraint *TC = Param->getTypeConstraint();
9318
assert(TC && "Type Constraint cannot be null here");
9319
auto *IDC = TC->getImmediatelyDeclaredConstraint();
9320
assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");
9321
ExprResult Constraint = SubstExpr(IDC, MLTAL);
9322
if (Constraint.isInvalid()) {
9323
return new (Context) concepts::ExprRequirement(
9324
concepts::createSubstDiagAt(*this, IDC->getExprLoc(),
9325
[&](llvm::raw_ostream &OS) {
9326
IDC->printPretty(OS, /*Helper=*/nullptr,
9327
getPrintingPolicy());
9328
}),
9329
IsSimple, NoexceptLoc, ReturnTypeRequirement);
9330
}
9331
SubstitutedConstraintExpr =
9332
cast<ConceptSpecializationExpr>(Constraint.get());
9333
if (!SubstitutedConstraintExpr->isSatisfied())
9334
Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
9335
}
9336
return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
9337
ReturnTypeRequirement, Status,
9338
SubstitutedConstraintExpr);
9339
}
9340
9341
concepts::ExprRequirement *
9342
Sema::BuildExprRequirement(
9343
concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
9344
bool IsSimple, SourceLocation NoexceptLoc,
9345
concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
9346
return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
9347
IsSimple, NoexceptLoc,
9348
ReturnTypeRequirement);
9349
}
9350
9351
concepts::TypeRequirement *
9352
Sema::BuildTypeRequirement(TypeSourceInfo *Type) {
9353
return new (Context) concepts::TypeRequirement(Type);
9354
}
9355
9356
concepts::TypeRequirement *
9357
Sema::BuildTypeRequirement(
9358
concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
9359
return new (Context) concepts::TypeRequirement(SubstDiag);
9360
}
9361
9362
concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) {
9363
return BuildNestedRequirement(Constraint);
9364
}
9365
9366
concepts::NestedRequirement *
9367
Sema::BuildNestedRequirement(Expr *Constraint) {
9368
ConstraintSatisfaction Satisfaction;
9369
if (!Constraint->isInstantiationDependent() &&
9370
CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
9371
Constraint->getSourceRange(), Satisfaction))
9372
return nullptr;
9373
return new (Context) concepts::NestedRequirement(Context, Constraint,
9374
Satisfaction);
9375
}
9376
9377
concepts::NestedRequirement *
9378
Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,
9379
const ASTConstraintSatisfaction &Satisfaction) {
9380
return new (Context) concepts::NestedRequirement(
9381
InvalidConstraintEntity,
9382
ASTConstraintSatisfaction::Rebuild(Context, Satisfaction));
9383
}
9384
9385
RequiresExprBodyDecl *
9386
Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
9387
ArrayRef<ParmVarDecl *> LocalParameters,
9388
Scope *BodyScope) {
9389
assert(BodyScope);
9390
9391
RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext,
9392
RequiresKWLoc);
9393
9394
PushDeclContext(BodyScope, Body);
9395
9396
for (ParmVarDecl *Param : LocalParameters) {
9397
if (Param->hasDefaultArg())
9398
// C++2a [expr.prim.req] p4
9399
// [...] A local parameter of a requires-expression shall not have a
9400
// default argument. [...]
9401
Diag(Param->getDefaultArgRange().getBegin(),
9402
diag::err_requires_expr_local_parameter_default_argument);
9403
// Ignore default argument and move on
9404
9405
Param->setDeclContext(Body);
9406
// If this has an identifier, add it to the scope stack.
9407
if (Param->getIdentifier()) {
9408
CheckShadow(BodyScope, Param);
9409
PushOnScopeChains(Param, BodyScope);
9410
}
9411
}
9412
return Body;
9413
}
9414
9415
void Sema::ActOnFinishRequiresExpr() {
9416
assert(CurContext && "DeclContext imbalance!");
9417
CurContext = CurContext->getLexicalParent();
9418
assert(CurContext && "Popped translation unit!");
9419
}
9420
9421
ExprResult Sema::ActOnRequiresExpr(
9422
SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body,
9423
SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters,
9424
SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements,
9425
SourceLocation ClosingBraceLoc) {
9426
auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LParenLoc,
9427
LocalParameters, RParenLoc, Requirements,
9428
ClosingBraceLoc);
9429
if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE))
9430
return ExprError();
9431
return RE;
9432
}
9433
9434