Skip to content

Commit 5fb39ef

Browse files
[LLVM][ADT] Explicitly convert size_t values to SmallVector's size type (#77939)
Multiple places rely on implicit conversion when assigning 'size_t' values to the member fields (size or capacity) of SmallVector. Depending on the platform / compiler configuration, this may result in narrowing conversion warnings (especially given that the size type of SmallVector's member fields is determined based on type T - in SmallVector<T>). To avoid the problem altogether, make the conversions explicit. Co-authored-by: Orest Chura <[email protected]>
1 parent f36845d commit 5fb39ef

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

llvm/include/llvm/ADT/SmallVector.h

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ template <class Size_T> class SmallVectorBase {
6161

6262
SmallVectorBase() = delete;
6363
SmallVectorBase(void *FirstEl, size_t TotalCapacity)
64-
: BeginX(FirstEl), Capacity(TotalCapacity) {}
64+
: BeginX(FirstEl), Capacity(static_cast<Size_T>(TotalCapacity)) {}
6565

6666
/// This is a helper for \a grow() that's out of line to reduce code
6767
/// duplication. This function will report a fatal error if it can't grow at
@@ -99,8 +99,18 @@ template <class Size_T> class SmallVectorBase {
9999
///
100100
/// This does not construct or destroy any elements in the vector.
101101
void set_size(size_t N) {
102-
assert(N <= capacity());
103-
Size = N;
102+
assert(N <= capacity()); // implies no overflow in assignment
103+
Size = static_cast<Size_T>(N);
104+
}
105+
106+
/// Set the array data pointer to \p Begin and capacity to \p N.
107+
///
108+
/// This does not construct or destroy any elements in the vector.
109+
// This does not clean up any existing allocation.
110+
void set_allocation_range(void *Begin, size_t N) {
111+
assert(N <= SizeTypeMax());
112+
BeginX = Begin;
113+
Capacity = static_cast<Size_T>(N);
104114
}
105115
};
106116

@@ -467,8 +477,7 @@ void SmallVectorTemplateBase<T, TriviallyCopyable>::takeAllocationForGrow(
467477
if (!this->isSmall())
468478
free(this->begin());
469479

470-
this->BeginX = NewElts;
471-
this->Capacity = NewCapacity;
480+
this->set_allocation_range(NewElts, NewCapacity);
472481
}
473482

474483
/// SmallVectorTemplateBase<TriviallyCopyable = true> - This is where we put

llvm/lib/Support/SmallVector.cpp

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,8 +153,7 @@ void SmallVectorBase<Size_T>::grow_pod(void *FirstEl, size_t MinSize,
153153
NewElts = replaceAllocation(NewElts, TSize, NewCapacity, size());
154154
}
155155

156-
this->BeginX = NewElts;
157-
this->Capacity = NewCapacity;
156+
this->set_allocation_range(NewElts, NewCapacity);
158157
}
159158

160159
template class llvm::SmallVectorBase<uint32_t>;

0 commit comments

Comments
 (0)