xref: /llvm-project/llvm/lib/Support/SmallVector.cpp (revision 2582d11f1a8a5783828156d3ced354727f422885)
1 //===- llvm/ADT/SmallVector.cpp - 'Normally small' vectors ----------------===//
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 // This file implements the SmallVector class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/Support/MemAlloc.h"
16 #include <cstdint>
17 #ifdef LLVM_ENABLE_EXCEPTIONS
18 #include <stdexcept>
19 #endif
20 using namespace llvm;
21 
22 // Check that no bytes are wasted and everything is well-aligned.
23 namespace {
24 // These structures may cause binary compat warnings on AIX. Suppress the
25 // warning since we are only using these types for the static assertions below.
26 #if defined(_AIX)
27 #pragma GCC diagnostic push
28 #pragma GCC diagnostic ignored "-Waix-compat"
29 #endif
30 struct Struct16B {
31   alignas(16) void *X;
32 };
33 struct Struct32B {
34   alignas(32) void *X;
35 };
36 #if defined(_AIX)
37 #pragma GCC diagnostic pop
38 #endif
39 }
40 
41 static_assert(alignof(SmallVector<Struct16B, 0>) >= alignof(Struct16B),
42               "wrong alignment for 16-byte aligned T");
43 static_assert(alignof(SmallVector<Struct32B, 0>) >= alignof(Struct32B),
44               "wrong alignment for 32-byte aligned T");
45 static_assert(sizeof(SmallVector<Struct16B, 0>) >= alignof(Struct16B),
46               "missing padding for 16-byte aligned T");
47 static_assert(sizeof(SmallVector<Struct32B, 0>) >= alignof(Struct32B),
48               "missing padding for 32-byte aligned T");
49 
50 static_assert(sizeof(SmallVector<void *, 0>) ==
51                   sizeof(unsigned) * 2 + sizeof(void *),
52               "wasted space in SmallVector size 0");
53 static_assert(sizeof(SmallVector<void *, 1>) ==
54                   sizeof(unsigned) * 2 + sizeof(void *) * 2,
55               "wasted space in SmallVector size 1");
56 static_assert(sizeof(SmallVector<char, 0>) ==
57                   sizeof(void *) * 2 + sizeof(void *),
58               "1 byte elements have word-sized type for size and capacity");
59 static_assert(sizeof(SmallVector<int16_t, 0>) ==
60                   sizeof(unsigned) * 2 + sizeof(void *),
61               "2 byte elements have 32-bit type for size and capacity");
62 
63 /// Report that MinSize doesn't fit into this vector's size type. Throws
64 /// std::length_error or calls report_fatal_error.
65 [[noreturn]] static void report_size_overflow(size_t MinSize, size_t MaxSize);
66 static void report_size_overflow(size_t MinSize, size_t MaxSize) {
67   std::string Reason = "SmallVector unable to grow. Requested capacity (" +
68                        std::to_string(MinSize) +
69                        ") is larger than maximum value for size type (" +
70                        std::to_string(MaxSize) + ")";
71 #ifdef LLVM_ENABLE_EXCEPTIONS
72   throw std::length_error(Reason);
73 #else
74   report_fatal_error(Twine(Reason));
75 #endif
76 }
77 
78 /// Report that this vector is already at maximum capacity. Throws
79 /// std::length_error or calls report_fatal_error.
80 [[noreturn]] static void report_at_maximum_capacity(size_t MaxSize);
81 static void report_at_maximum_capacity(size_t MaxSize) {
82   std::string Reason =
83       "SmallVector capacity unable to grow. Already at maximum size " +
84       std::to_string(MaxSize);
85 #ifdef LLVM_ENABLE_EXCEPTIONS
86   throw std::length_error(Reason);
87 #else
88   report_fatal_error(Twine(Reason));
89 #endif
90 }
91 
92 // Note: Moving this function into the header may cause performance regression.
93 template <class Size_T>
94 static size_t getNewCapacity(size_t MinSize, size_t TSize, size_t OldCapacity) {
95   constexpr size_t MaxSize = std::numeric_limits<Size_T>::max();
96 
97   // Ensure we can fit the new capacity.
98   // This is only going to be applicable when the capacity is 32 bit.
99   if (MinSize > MaxSize)
100     report_size_overflow(MinSize, MaxSize);
101 
102   // Ensure we can meet the guarantee of space for at least one more element.
103   // The above check alone will not catch the case where grow is called with a
104   // default MinSize of 0, but the current capacity cannot be increased.
105   // This is only going to be applicable when the capacity is 32 bit.
106   if (OldCapacity == MaxSize)
107     report_at_maximum_capacity(MaxSize);
108 
109   // In theory 2*capacity can overflow if the capacity is 64 bit, but the
110   // original capacity would never be large enough for this to be a problem.
111   size_t NewCapacity = 2 * OldCapacity + 1; // Always grow.
112   return std::clamp(NewCapacity, MinSize, MaxSize);
113 }
114 
115 template <class Size_T>
116 void *SmallVectorBase<Size_T>::replaceAllocation(void *NewElts, size_t TSize,
117                                                  size_t NewCapacity,
118                                                  size_t VSize) {
119   void *NewEltsReplace = llvm::safe_malloc(NewCapacity * TSize);
120   if (VSize)
121     memcpy(NewEltsReplace, NewElts, VSize * TSize);
122   free(NewElts);
123   return NewEltsReplace;
124 }
125 
126 // Note: Moving this function into the header may cause performance regression.
127 template <class Size_T>
128 void *SmallVectorBase<Size_T>::mallocForGrow(void *FirstEl, size_t MinSize,
129                                              size_t TSize,
130                                              size_t &NewCapacity) {
131   NewCapacity = getNewCapacity<Size_T>(MinSize, TSize, this->capacity());
132   // Even if capacity is not 0 now, if the vector was originally created with
133   // capacity 0, it's possible for the malloc to return FirstEl.
134   void *NewElts = llvm::safe_malloc(NewCapacity * TSize);
135   if (NewElts == FirstEl)
136     NewElts = replaceAllocation(NewElts, TSize, NewCapacity);
137   return NewElts;
138 }
139 
140 // Note: Moving this function into the header may cause performance regression.
141 template <class Size_T>
142 void SmallVectorBase<Size_T>::grow_pod(void *FirstEl, size_t MinSize,
143                                        size_t TSize) {
144   size_t NewCapacity = getNewCapacity<Size_T>(MinSize, TSize, this->capacity());
145   void *NewElts;
146   if (BeginX == FirstEl) {
147     NewElts = llvm::safe_malloc(NewCapacity * TSize);
148     if (NewElts == FirstEl)
149       NewElts = replaceAllocation(NewElts, TSize, NewCapacity);
150 
151     // Copy the elements over.  No need to run dtors on PODs.
152     memcpy(NewElts, this->BeginX, size() * TSize);
153   } else {
154     // If this wasn't grown from the inline copy, grow the allocated space.
155     NewElts = llvm::safe_realloc(this->BeginX, NewCapacity * TSize);
156     if (NewElts == FirstEl)
157       NewElts = replaceAllocation(NewElts, TSize, NewCapacity, size());
158   }
159 
160   this->set_allocation_range(NewElts, NewCapacity);
161 }
162 
163 template class llvm::SmallVectorBase<uint32_t>;
164 
165 // Disable the uint64_t instantiation for 32-bit builds.
166 // Both uint32_t and uint64_t instantiations are needed for 64-bit builds.
167 // This instantiation will never be used in 32-bit builds, and will cause
168 // warnings when sizeof(Size_T) > sizeof(size_t).
169 #if SIZE_MAX > UINT32_MAX
170 template class llvm::SmallVectorBase<uint64_t>;
171 
172 // Assertions to ensure this #if stays in sync with SmallVectorSizeType.
173 static_assert(sizeof(SmallVectorSizeType<char>) == sizeof(uint64_t),
174               "Expected SmallVectorBase<uint64_t> variant to be in use.");
175 #else
176 static_assert(sizeof(SmallVectorSizeType<char>) == sizeof(uint32_t),
177               "Expected SmallVectorBase<uint32_t> variant to be in use.");
178 #endif
179