[PATCH] D107308: [scudo] Make Vector() constexpr

Kostya Kortchinsky via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Mon Aug 2 13:40:28 PDT 2021


cryptoad created this revision.
cryptoad added reviewers: hctim, cferris, vitalybuka, pcc.
cryptoad requested review of this revision.
Herald added a project: Sanitizers.
Herald added a subscriber: Sanitizers.

A `Vector` that doesn't require an initial `reserve()` (eg: with a
default, or small enough capacity) can have a constant initializer.

This changes the code in a few places to make that possible:

- mark a few other functions as `constexpr`
- do without any `reinterpret_cast`
- allow to skip `reserve` from `init`


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D107308

Files:
  compiler-rt/lib/scudo/standalone/vector.h


Index: compiler-rt/lib/scudo/standalone/vector.h
===================================================================
--- compiler-rt/lib/scudo/standalone/vector.h
+++ compiler-rt/lib/scudo/standalone/vector.h
@@ -19,13 +19,14 @@
 // small vectors. The current implementation supports only POD types.
 template <typename T> class VectorNoCtor {
 public:
-  void init(uptr InitialCapacity = 0) {
-    Data = reinterpret_cast<T *>(&LocalData[0]);
+  constexpr void init(uptr InitialCapacity = 0) {
+    Data = &LocalData[0];
     CapacityBytes = sizeof(LocalData);
-    reserve(InitialCapacity);
+    if (InitialCapacity > capacity())
+      reserve(InitialCapacity);
   }
   void destroy() {
-    if (Data != reinterpret_cast<T *>(&LocalData[0]))
+    if (Data != &LocalData[0])
       unmap(Data, CapacityBytes);
   }
   T &operator[](uptr I) {
@@ -55,7 +56,7 @@
   uptr size() const { return Size; }
   const T *data() const { return Data; }
   T *data() { return Data; }
-  uptr capacity() const { return CapacityBytes / sizeof(T); }
+  constexpr uptr capacity() const { return CapacityBytes / sizeof(T); }
   void reserve(uptr NewSize) {
     // Never downsize internal buffer.
     if (NewSize > capacity())
@@ -91,14 +92,14 @@
   }
 
   T *Data = nullptr;
-  u8 LocalData[256] = {};
+  T LocalData[256 / sizeof(T)] = {};
   uptr CapacityBytes = 0;
   uptr Size = 0;
 };
 
 template <typename T> class Vector : public VectorNoCtor<T> {
 public:
-  Vector() { VectorNoCtor<T>::init(); }
+  constexpr Vector() { VectorNoCtor<T>::init(); }
   explicit Vector(uptr Count) {
     VectorNoCtor<T>::init(Count);
     this->resize(Count);


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D107308.363564.patch
Type: text/x-patch
Size: 1634 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20210802/ef505ae3/attachment.bin>


More information about the llvm-commits mailing list