Skip to content

Commit cfee056

Browse files
authored
[clang] NFC: introduce UnsignedOrNone as a replacement for std::optional<unsigned> (#134142)
This introduces a new class 'UnsignedOrNone', which models a lite version of `std::optional<unsigned>`, but has the same size as 'unsigned'. This replaces most uses of `std::optional<unsigned>`, and similar schemes utilizing 'int' and '-1' as sentinel. Besides the smaller size advantage, this is simpler to serialize, as its internal representation is a single unsigned int as well.
1 parent 262b9b5 commit cfee056

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

60 files changed

+509
-507
lines changed

clang/include/clang/AST/ASTConcept.h

+5-7
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
#include "clang/AST/NestedNameSpecifier.h"
1919
#include "clang/AST/TemplateBase.h"
2020
#include "clang/Basic/SourceLocation.h"
21+
#include "clang/Basic/UnsignedOrNone.h"
2122
#include "llvm/ADT/FoldingSet.h"
2223
#include "llvm/ADT/PointerUnion.h"
2324
#include "llvm/ADT/SmallVector.h"
@@ -229,15 +230,14 @@ class TypeConstraint {
229230
/// type-constraint.
230231
Expr *ImmediatelyDeclaredConstraint = nullptr;
231232
ConceptReference *ConceptRef;
232-
int ArgumentPackSubstitutionIndex;
233+
UnsignedOrNone ArgPackSubstIndex;
233234

234235
public:
235236
TypeConstraint(ConceptReference *ConceptRef,
236237
Expr *ImmediatelyDeclaredConstraint,
237-
int ArgumentPackSubstitutionIndex)
238+
UnsignedOrNone ArgPackSubstIndex)
238239
: ImmediatelyDeclaredConstraint(ImmediatelyDeclaredConstraint),
239-
ConceptRef(ConceptRef),
240-
ArgumentPackSubstitutionIndex(ArgumentPackSubstitutionIndex) {}
240+
ConceptRef(ConceptRef), ArgPackSubstIndex(ArgPackSubstIndex) {}
241241

242242
/// \brief Get the immediately-declared constraint expression introduced by
243243
/// this type-constraint, that is - the constraint expression that is added to
@@ -248,9 +248,7 @@ class TypeConstraint {
248248

249249
ConceptReference *getConceptReference() const { return ConceptRef; }
250250

251-
int getArgumentPackSubstitutionIndex() const {
252-
return ArgumentPackSubstitutionIndex;
253-
}
251+
UnsignedOrNone getArgPackSubstIndex() const { return ArgPackSubstIndex; }
254252

255253
// FIXME: Instead of using these concept related functions the callers should
256254
// directly work with the corresponding ConceptReference.

clang/include/clang/AST/ASTContext.h

+4-5
Original file line numberDiff line numberDiff line change
@@ -1797,7 +1797,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
17971797

17981798
QualType getSubstTemplateTypeParmType(QualType Replacement,
17991799
Decl *AssociatedDecl, unsigned Index,
1800-
std::optional<unsigned> PackIndex,
1800+
UnsignedOrNone PackIndex,
18011801
bool Final) const;
18021802
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
18031803
unsigned Index, bool Final,
@@ -1853,8 +1853,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
18531853
/// expansion is used in a context where the arity is inferred from
18541854
/// elsewhere, such as if the pattern contains a placeholder type or
18551855
/// if this is the canonical type of another pack expansion type.
1856-
QualType getPackExpansionType(QualType Pattern,
1857-
std::optional<unsigned> NumExpansions,
1856+
QualType getPackExpansionType(QualType Pattern, UnsignedOrNone NumExpansions,
18581857
bool ExpectPackInType = true) const;
18591858

18601859
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
@@ -1898,7 +1897,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
18981897
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr,
18991898
bool FullySubstituted = false,
19001899
ArrayRef<QualType> Expansions = {},
1901-
int Index = -1) const;
1900+
UnsignedOrNone Index = std::nullopt) const;
19021901

19031902
/// Unary type transforms
19041903
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
@@ -2396,7 +2395,7 @@ class ASTContext : public RefCountedBase<ASTContext> {
23962395
TemplateName getSubstTemplateTemplateParm(TemplateName replacement,
23972396
Decl *AssociatedDecl,
23982397
unsigned Index,
2399-
std::optional<unsigned> PackIndex,
2398+
UnsignedOrNone PackIndex,
24002399
bool Final) const;
24012400
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
24022401
Decl *AssociatedDecl,

clang/include/clang/AST/ASTImporter.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -592,7 +592,7 @@ class TypeSourceInfo;
592592
/// F should be a field (or indirect field) declaration.
593593
/// \returns The index of the field in its parent context (starting from 0).
594594
/// On error `std::nullopt` is returned (parent context is non-record).
595-
static std::optional<unsigned> getFieldIndex(Decl *F);
595+
static UnsignedOrNone getFieldIndex(Decl *F);
596596
};
597597

598598
} // namespace clang

clang/include/clang/AST/ASTStructuralEquivalence.h

+1-2
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,7 @@ struct StructuralEquivalenceContext {
123123
///
124124
/// FIXME: This is needed by ASTImporter and ASTStructureEquivalence. It
125125
/// probably makes more sense in some other common place then here.
126-
static std::optional<unsigned>
127-
findUntaggedStructOrUnionIndex(RecordDecl *Anon);
126+
static UnsignedOrNone findUntaggedStructOrUnionIndex(RecordDecl *Anon);
128127

129128
// If ErrorOnTagTypeMismatch is set, return the error, otherwise get the
130129
// relevant warning for the input error diagnostic.

clang/include/clang/AST/Decl.h

+5-5
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
#include "clang/Basic/PragmaKinds.h"
3434
#include "clang/Basic/SourceLocation.h"
3535
#include "clang/Basic/Specifiers.h"
36+
#include "clang/Basic/UnsignedOrNone.h"
3637
#include "clang/Basic/Visibility.h"
3738
#include "llvm/ADT/APSInt.h"
3839
#include "llvm/ADT/ArrayRef.h"
@@ -82,14 +83,13 @@ enum class ImplicitParamKind;
8283
// expanded.
8384
struct AssociatedConstraint {
8485
const Expr *ConstraintExpr = nullptr;
85-
int ArgumentPackSubstitutionIndex = -1;
86+
UnsignedOrNone ArgPackSubstIndex = std::nullopt;
8687

8788
constexpr AssociatedConstraint() = default;
8889

8990
explicit AssociatedConstraint(const Expr *ConstraintExpr,
90-
int ArgumentPackSubstitutionIndex = -1)
91-
: ConstraintExpr(ConstraintExpr),
92-
ArgumentPackSubstitutionIndex(ArgumentPackSubstitutionIndex) {}
91+
UnsignedOrNone ArgPackSubstIndex = std::nullopt)
92+
: ConstraintExpr(ConstraintExpr), ArgPackSubstIndex(ArgPackSubstIndex) {}
9393

9494
explicit operator bool() const { return ConstraintExpr != nullptr; }
9595

@@ -2540,7 +2540,7 @@ class FunctionDecl : public DeclaratorDecl,
25402540
/// If this function is an allocation/deallocation function that takes
25412541
/// the `std::nothrow_t` tag, return true through IsNothrow,
25422542
bool isReplaceableGlobalAllocationFunction(
2543-
std::optional<unsigned> *AlignmentParam = nullptr,
2543+
UnsignedOrNone *AlignmentParam = nullptr,
25442544
bool *IsNothrow = nullptr) const;
25452545

25462546
/// Determine if this function provides an inline implementation of a builtin.

clang/include/clang/AST/DeclTemplate.h

+12-24
Original file line numberDiff line numberDiff line change
@@ -1198,13 +1198,8 @@ class TemplateTypeParmDecl final : public TypeDecl,
11981198
/// type constraint.
11991199
bool TypeConstraintInitialized : 1;
12001200

1201-
/// Whether this type template parameter is an "expanded"
1202-
/// parameter pack, meaning that its type is a pack expansion and we
1203-
/// already know the set of types that expansion expands to.
1204-
bool ExpandedParameterPack : 1;
1205-
1206-
/// The number of type parameters in an expanded parameter pack.
1207-
unsigned NumExpanded = 0;
1201+
/// The number of type parameters in an expanded parameter pack, if any.
1202+
UnsignedOrNone NumExpanded = std::nullopt;
12081203

12091204
/// The default template argument, if any.
12101205
using DefArgStorage =
@@ -1213,19 +1208,17 @@ class TemplateTypeParmDecl final : public TypeDecl,
12131208

12141209
TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
12151210
SourceLocation IdLoc, IdentifierInfo *Id, bool Typename,
1216-
bool HasTypeConstraint,
1217-
std::optional<unsigned> NumExpanded)
1211+
bool HasTypeConstraint, UnsignedOrNone NumExpanded)
12181212
: TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename),
12191213
HasTypeConstraint(HasTypeConstraint), TypeConstraintInitialized(false),
1220-
ExpandedParameterPack(NumExpanded),
1221-
NumExpanded(NumExpanded.value_or(0)) {}
1214+
NumExpanded(NumExpanded) {}
12221215

12231216
public:
12241217
static TemplateTypeParmDecl *
12251218
Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc,
12261219
SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id,
12271220
bool Typename, bool ParameterPack, bool HasTypeConstraint = false,
1228-
std::optional<unsigned> NumExpanded = std::nullopt);
1221+
UnsignedOrNone NumExpanded = std::nullopt);
12291222
static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
12301223
GlobalDeclID ID);
12311224
static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
@@ -1327,13 +1320,8 @@ class TemplateTypeParmDecl final : public TypeDecl,
13271320
/// expanded parameter pack. For example, instantiating
13281321
/// \c X<int, unsigned int> results in \c Convertibles being an expanded
13291322
/// parameter pack of size 2 (use getNumExpansionTypes() to get this number).
1330-
bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1331-
1332-
/// Retrieves the number of parameters in an expanded parameter pack.
1333-
unsigned getNumExpansionParameters() const {
1334-
assert(ExpandedParameterPack && "Not an expansion parameter pack");
1335-
return NumExpanded;
1336-
}
1323+
/// Retrieves the number of parameters in an expanded parameter pack, if any.
1324+
UnsignedOrNone getNumExpansionParameters() const { return NumExpanded; }
13371325

13381326
/// Returns the type constraint associated with this template parameter (if
13391327
/// any).
@@ -1344,7 +1332,7 @@ class TemplateTypeParmDecl final : public TypeDecl,
13441332

13451333
void setTypeConstraint(ConceptReference *CR,
13461334
Expr *ImmediatelyDeclaredConstraint,
1347-
int ArgumentPackSubstitutionIndex);
1335+
UnsignedOrNone ArgPackSubstIndex);
13481336

13491337
/// Determine whether this template parameter has a type-constraint.
13501338
bool hasTypeConstraint() const {
@@ -1360,7 +1348,7 @@ class TemplateTypeParmDecl final : public TypeDecl,
13601348
llvm::SmallVectorImpl<AssociatedConstraint> &AC) const {
13611349
if (HasTypeConstraint)
13621350
AC.emplace_back(getTypeConstraint()->getImmediatelyDeclaredConstraint(),
1363-
getTypeConstraint()->getArgumentPackSubstitutionIndex());
1351+
getTypeConstraint()->getArgPackSubstIndex());
13641352
}
13651353

13661354
SourceRange getSourceRange() const override LLVM_READONLY;
@@ -3379,10 +3367,10 @@ inline TemplateDecl *getAsTypeTemplateDecl(Decl *D) {
33793367
///
33803368
/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
33813369
/// is not a pack expansion, so returns an empty Optional.
3382-
inline std::optional<unsigned> getExpandedPackSize(const NamedDecl *Param) {
3370+
inline UnsignedOrNone getExpandedPackSize(const NamedDecl *Param) {
33833371
if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3384-
if (TTP->isExpandedParameterPack())
3385-
return TTP->getNumExpansionParameters();
3372+
if (UnsignedOrNone Num = TTP->getNumExpansionParameters())
3373+
return Num;
33863374
}
33873375

33883376
if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {

clang/include/clang/AST/ExprCXX.h

+13-20
Original file line numberDiff line numberDiff line change
@@ -4210,7 +4210,7 @@ class PackExpansionExpr : public Expr {
42104210

42114211
public:
42124212
PackExpansionExpr(QualType T, Expr *Pattern, SourceLocation EllipsisLoc,
4213-
std::optional<unsigned> NumExpansions)
4213+
UnsignedOrNone NumExpansions)
42144214
: Expr(PackExpansionExprClass, T, Pattern->getValueKind(),
42154215
Pattern->getObjectKind()),
42164216
EllipsisLoc(EllipsisLoc),
@@ -4233,7 +4233,7 @@ class PackExpansionExpr : public Expr {
42334233

42344234
/// Determine the number of expansions that will be produced when
42354235
/// this pack expansion is instantiated, if already known.
4236-
std::optional<unsigned> getNumExpansions() const {
4236+
UnsignedOrNone getNumExpansions() const {
42374237
if (NumExpansions)
42384238
return NumExpansions - 1;
42394239

@@ -4304,8 +4304,7 @@ class SizeOfPackExpr final
43044304
/// the given parameter pack.
43054305
SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack,
43064306
SourceLocation PackLoc, SourceLocation RParenLoc,
4307-
std::optional<unsigned> Length,
4308-
ArrayRef<TemplateArgument> PartialArgs)
4307+
UnsignedOrNone Length, ArrayRef<TemplateArgument> PartialArgs)
43094308
: Expr(SizeOfPackExprClass, SizeType, VK_PRValue, OK_Ordinary),
43104309
OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc),
43114310
Length(Length ? *Length : PartialArgs.size()), Pack(Pack) {
@@ -4325,7 +4324,7 @@ class SizeOfPackExpr final
43254324
static SizeOfPackExpr *Create(ASTContext &Context, SourceLocation OperatorLoc,
43264325
NamedDecl *Pack, SourceLocation PackLoc,
43274326
SourceLocation RParenLoc,
4328-
std::optional<unsigned> Length = std::nullopt,
4327+
UnsignedOrNone Length = std::nullopt,
43294328
ArrayRef<TemplateArgument> PartialArgs = {});
43304329
static SizeOfPackExpr *CreateDeserialized(ASTContext &Context,
43314330
unsigned NumPartialArgs);
@@ -4467,7 +4466,7 @@ class PackIndexingExpr final
44674466

44684467
Expr *getIndexExpr() const { return cast<Expr>(SubExprs[1]); }
44694468

4470-
std::optional<unsigned> getSelectedIndex() const {
4469+
UnsignedOrNone getSelectedIndex() const {
44714470
if (isInstantiationDependent())
44724471
return std::nullopt;
44734472
ConstantExpr *CE = cast<ConstantExpr>(getIndexExpr());
@@ -4477,7 +4476,7 @@ class PackIndexingExpr final
44774476
}
44784477

44794478
Expr *getSelectedExpr() const {
4480-
std::optional<unsigned> Index = getSelectedIndex();
4479+
UnsignedOrNone Index = getSelectedIndex();
44814480
assert(Index && "extracting the indexed expression of a dependant pack");
44824481
return getTrailingObjects<Expr *>()[*Index];
44834482
}
@@ -4525,12 +4524,12 @@ class SubstNonTypeTemplateParmExpr : public Expr {
45254524
SubstNonTypeTemplateParmExpr(QualType Ty, ExprValueKind ValueKind,
45264525
SourceLocation Loc, Expr *Replacement,
45274526
Decl *AssociatedDecl, unsigned Index,
4528-
std::optional<unsigned> PackIndex, bool RefParam,
4527+
UnsignedOrNone PackIndex, bool RefParam,
45294528
bool Final)
45304529
: Expr(SubstNonTypeTemplateParmExprClass, Ty, ValueKind, OK_Ordinary),
45314530
Replacement(Replacement),
45324531
AssociatedDeclAndRef(AssociatedDecl, RefParam), Index(Index),
4533-
PackIndex(PackIndex ? *PackIndex + 1 : 0), Final(Final) {
4532+
PackIndex(PackIndex.toInternalRepresentation()), Final(Final) {
45344533
assert(AssociatedDecl != nullptr);
45354534
SubstNonTypeTemplateParmExprBits.NameLoc = Loc;
45364535
setDependence(computeDependence(this));
@@ -4552,10 +4551,8 @@ class SubstNonTypeTemplateParmExpr : public Expr {
45524551
/// This should match the result of `getParameter()->getIndex()`.
45534552
unsigned getIndex() const { return Index; }
45544553

4555-
std::optional<unsigned> getPackIndex() const {
4556-
if (PackIndex == 0)
4557-
return std::nullopt;
4558-
return PackIndex - 1;
4554+
UnsignedOrNone getPackIndex() const {
4555+
return UnsignedOrNone::fromInternalRepresentation(PackIndex);
45594556
}
45604557

45614558
// This substitution is Final, which means the substitution is fully
@@ -4882,15 +4879,15 @@ class CXXFoldExpr : public Expr {
48824879
SourceLocation RParenLoc;
48834880
// When 0, the number of expansions is not known. Otherwise, this is one more
48844881
// than the number of expansions.
4885-
unsigned NumExpansions;
4882+
UnsignedOrNone NumExpansions = std::nullopt;
48864883
Stmt *SubExprs[SubExpr::Count];
48874884
BinaryOperatorKind Opcode;
48884885

48894886
public:
48904887
CXXFoldExpr(QualType T, UnresolvedLookupExpr *Callee,
48914888
SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Opcode,
48924889
SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc,
4893-
std::optional<unsigned> NumExpansions);
4890+
UnsignedOrNone NumExpansions);
48944891

48954892
CXXFoldExpr(EmptyShell Empty) : Expr(CXXFoldExprClass, Empty) {}
48964893

@@ -4919,11 +4916,7 @@ class CXXFoldExpr : public Expr {
49194916
SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
49204917
BinaryOperatorKind getOperator() const { return Opcode; }
49214918

4922-
std::optional<unsigned> getNumExpansions() const {
4923-
if (NumExpansions)
4924-
return NumExpansions - 1;
4925-
return std::nullopt;
4926-
}
4919+
UnsignedOrNone getNumExpansions() const { return NumExpansions; }
49274920

49284921
SourceLocation getBeginLoc() const LLVM_READONLY {
49294922
if (LParenLoc.isValid())

clang/include/clang/AST/ExprObjC.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ struct ObjCDictionaryElement {
271271

272272
/// The number of elements this pack expansion will expand to, if
273273
/// this is a pack expansion and is known.
274-
std::optional<unsigned> NumExpansions;
274+
UnsignedOrNone NumExpansions;
275275

276276
/// Determines whether this dictionary element is a pack expansion.
277277
bool isPackExpansion() const { return EllipsisLoc.isValid(); }

clang/include/clang/AST/Mangle.h

+2-2
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,8 @@ class MangleContext {
182182

183183
class ItaniumMangleContext : public MangleContext {
184184
public:
185-
using DiscriminatorOverrideTy =
186-
std::optional<unsigned> (*)(ASTContext &, const NamedDecl *);
185+
using DiscriminatorOverrideTy = UnsignedOrNone (*)(ASTContext &,
186+
const NamedDecl *);
187187
explicit ItaniumMangleContext(ASTContext &C, DiagnosticsEngine &D,
188188
bool IsAux = false)
189189
: MangleContext(C, D, MK_Itanium, IsAux) {}

clang/include/clang/AST/PropertiesBase.td

+5-9
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ def TemplateNameKind : EnumPropertyType<"TemplateName::NameKind">;
144144
def TypeOfKind : EnumPropertyType<"TypeOfKind">;
145145
def UInt32 : CountPropertyType<"uint32_t">;
146146
def UInt64 : CountPropertyType<"uint64_t">;
147+
def UnsignedOrNone : PropertyType;
147148
def UnaryTypeTransformKind : EnumPropertyType<"UnaryTransformType::UTTKind">;
148149
def VectorKind : EnumPropertyType<"VectorKind">;
149150
def TypeCoupledDeclRefInfo : PropertyType;
@@ -727,7 +728,7 @@ let Class = PropertyTypeCase<TemplateName, "SubstTemplateTemplateParm"> in {
727728
def : Property<"index", UInt32> {
728729
let Read = [{ parm->getIndex() }];
729730
}
730-
def : Property<"packIndex", Optional<UInt32>> {
731+
def : Property<"packIndex", UnsignedOrNone> {
731732
let Read = [{ parm->getPackIndex() }];
732733
}
733734
def : Property<"final", Bool> { let Read = [{ parm->getFinal() }]; }
@@ -860,21 +861,16 @@ let Class = PropertyTypeCase<TemplateArgument, "TemplateExpansion"> in {
860861
def : Property<"name", TemplateName> {
861862
let Read = [{ node.getAsTemplateOrTemplatePattern() }];
862863
}
863-
def : Property<"numExpansions", Optional<UInt32>> {
864+
def : Property<"numExpansions", UnsignedOrNone> {
864865
let Read = [{
865-
// Translate unsigned -> uint32_t just in case.
866-
llvm::transformOptional(node.getNumTemplateExpansions(),
867-
[](unsigned i) { return uint32_t(i); })
866+
node.getNumTemplateExpansions()
868867
}];
869868
}
870869
def : Property<"isDefaulted", Bool> {
871870
let Read = [{ node.getIsDefaulted() }];
872871
}
873872
def : Creator<[{
874-
auto numExpansionsUnsigned = llvm::transformOptional(
875-
numExpansions, [](uint32_t i) { return unsigned(i); });
876-
877-
return TemplateArgument(name, numExpansionsUnsigned, isDefaulted);
873+
return TemplateArgument(name, numExpansions, isDefaulted);
878874
}]>;
879875
}
880876
let Class = PropertyTypeCase<TemplateArgument, "Expression"> in {

0 commit comments

Comments
 (0)