SmallVector.h 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// This file defines the SmallVector class.
  16. ///
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_ADT_SMALLVECTOR_H
  19. #define LLVM_ADT_SMALLVECTOR_H
  20. #include "llvm/Support/Compiler.h"
  21. #include "llvm/Support/type_traits.h"
  22. #include <algorithm>
  23. #include <cassert>
  24. #include <cstddef>
  25. #include <cstdlib>
  26. #include <cstring>
  27. #include <functional>
  28. #include <initializer_list>
  29. #include <iterator>
  30. #include <limits>
  31. #include <memory>
  32. #include <new>
  33. #include <type_traits>
  34. #include <utility>
  35. namespace llvm {
  36. template <typename T> class ArrayRef;
  37. template <typename IteratorT> class iterator_range;
  38. template <class Iterator>
  39. using EnableIfConvertibleToInputIterator = std::enable_if_t<std::is_convertible<
  40. typename std::iterator_traits<Iterator>::iterator_category,
  41. std::input_iterator_tag>::value>;
  42. /// This is all the stuff common to all SmallVectors.
  43. ///
  44. /// The template parameter specifies the type which should be used to hold the
  45. /// Size and Capacity of the SmallVector, so it can be adjusted.
  46. /// Using 32 bit size is desirable to shrink the size of the SmallVector.
  47. /// Using 64 bit size is desirable for cases like SmallVector<char>, where a
  48. /// 32 bit size would limit the vector to ~4GB. SmallVectors are used for
  49. /// buffering bitcode output - which can exceed 4GB.
  50. template <class Size_T> class SmallVectorBase {
  51. protected:
  52. void *BeginX;
  53. Size_T Size = 0, Capacity;
  54. /// The maximum value of the Size_T used.
  55. static constexpr size_t SizeTypeMax() {
  56. return std::numeric_limits<Size_T>::max();
  57. }
  58. SmallVectorBase() = delete;
  59. SmallVectorBase(void *FirstEl, size_t TotalCapacity)
  60. : BeginX(FirstEl), Capacity(TotalCapacity) {}
  61. /// This is a helper for \a grow() that's out of line to reduce code
  62. /// duplication. This function will report a fatal error if it can't grow at
  63. /// least to \p MinSize.
  64. void *mallocForGrow(void *FirstEl, size_t MinSize, size_t TSize,
  65. size_t &NewCapacity);
  66. /// This is an implementation of the grow() method which only works
  67. /// on POD-like data types and is out of line to reduce code duplication.
  68. /// This function will report a fatal error if it cannot increase capacity.
  69. void grow_pod(void *FirstEl, size_t MinSize, size_t TSize);
  70. /// If vector was first created with capacity 0, getFirstEl() points to the
  71. /// memory right after, an area unallocated. If a subsequent allocation,
  72. /// that grows the vector, happens to return the same pointer as getFirstEl(),
  73. /// get a new allocation, otherwise isSmall() will falsely return that no
  74. /// allocation was done (true) and the memory will not be freed in the
  75. /// destructor. If a VSize is given (vector size), also copy that many
  76. /// elements to the new allocation - used if realloca fails to increase
  77. /// space, and happens to allocate precisely at BeginX.
  78. /// This is unlikely to be called often, but resolves a memory leak when the
  79. /// situation does occur.
  80. void *replaceAllocation(void *NewElts, size_t TSize, size_t NewCapacity,
  81. size_t VSize = 0);
  82. public:
  83. size_t size() const { return Size; }
  84. size_t capacity() const { return Capacity; }
  85. [[nodiscard]] bool empty() const { return !Size; }
  86. protected:
  87. /// Set the array size to \p N, which the current array must have enough
  88. /// capacity for.
  89. ///
  90. /// This does not construct or destroy any elements in the vector.
  91. void set_size(size_t N) {
  92. assert(N <= capacity());
  93. Size = N;
  94. }
  95. };
  96. template <class T>
  97. using SmallVectorSizeType =
  98. std::conditional_t<sizeof(T) < 4 && sizeof(void *) >= 8, uint64_t,
  99. uint32_t>;
  100. /// Figure out the offset of the first element.
  101. template <class T, typename = void> struct SmallVectorAlignmentAndSize {
  102. alignas(SmallVectorBase<SmallVectorSizeType<T>>) char Base[sizeof(
  103. SmallVectorBase<SmallVectorSizeType<T>>)];
  104. alignas(T) char FirstEl[sizeof(T)];
  105. };
  106. /// This is the part of SmallVectorTemplateBase which does not depend on whether
  107. /// the type T is a POD. The extra dummy template argument is used by ArrayRef
  108. /// to avoid unnecessarily requiring T to be complete.
  109. template <typename T, typename = void>
  110. class SmallVectorTemplateCommon
  111. : public SmallVectorBase<SmallVectorSizeType<T>> {
  112. using Base = SmallVectorBase<SmallVectorSizeType<T>>;
  113. protected:
  114. /// Find the address of the first element. For this pointer math to be valid
  115. /// with small-size of 0 for T with lots of alignment, it's important that
  116. /// SmallVectorStorage is properly-aligned even for small-size of 0.
  117. void *getFirstEl() const {
  118. return const_cast<void *>(reinterpret_cast<const void *>(
  119. reinterpret_cast<const char *>(this) +
  120. offsetof(SmallVectorAlignmentAndSize<T>, FirstEl)));
  121. }
  122. // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
  123. SmallVectorTemplateCommon(size_t Size) : Base(getFirstEl(), Size) {}
  124. void grow_pod(size_t MinSize, size_t TSize) {
  125. Base::grow_pod(getFirstEl(), MinSize, TSize);
  126. }
  127. /// Return true if this is a smallvector which has not had dynamic
  128. /// memory allocated for it.
  129. bool isSmall() const { return this->BeginX == getFirstEl(); }
  130. /// Put this vector in a state of being small.
  131. void resetToSmall() {
  132. this->BeginX = getFirstEl();
  133. this->Size = this->Capacity = 0; // FIXME: Setting Capacity to 0 is suspect.
  134. }
  135. /// Return true if V is an internal reference to the given range.
  136. bool isReferenceToRange(const void *V, const void *First, const void *Last) const {
  137. // Use std::less to avoid UB.
  138. std::less<> LessThan;
  139. return !LessThan(V, First) && LessThan(V, Last);
  140. }
  141. /// Return true if V is an internal reference to this vector.
  142. bool isReferenceToStorage(const void *V) const {
  143. return isReferenceToRange(V, this->begin(), this->end());
  144. }
  145. /// Return true if First and Last form a valid (possibly empty) range in this
  146. /// vector's storage.
  147. bool isRangeInStorage(const void *First, const void *Last) const {
  148. // Use std::less to avoid UB.
  149. std::less<> LessThan;
  150. return !LessThan(First, this->begin()) && !LessThan(Last, First) &&
  151. !LessThan(this->end(), Last);
  152. }
  153. /// Return true unless Elt will be invalidated by resizing the vector to
  154. /// NewSize.
  155. bool isSafeToReferenceAfterResize(const void *Elt, size_t NewSize) {
  156. // Past the end.
  157. if (LLVM_LIKELY(!isReferenceToStorage(Elt)))
  158. return true;
  159. // Return false if Elt will be destroyed by shrinking.
  160. if (NewSize <= this->size())
  161. return Elt < this->begin() + NewSize;
  162. // Return false if we need to grow.
  163. return NewSize <= this->capacity();
  164. }
  165. /// Check whether Elt will be invalidated by resizing the vector to NewSize.
  166. void assertSafeToReferenceAfterResize(const void *Elt, size_t NewSize) {
  167. assert(isSafeToReferenceAfterResize(Elt, NewSize) &&
  168. "Attempting to reference an element of the vector in an operation "
  169. "that invalidates it");
  170. }
  171. /// Check whether Elt will be invalidated by increasing the size of the
  172. /// vector by N.
  173. void assertSafeToAdd(const void *Elt, size_t N = 1) {
  174. this->assertSafeToReferenceAfterResize(Elt, this->size() + N);
  175. }
  176. /// Check whether any part of the range will be invalidated by clearing.
  177. void assertSafeToReferenceAfterClear(const T *From, const T *To) {
  178. if (From == To)
  179. return;
  180. this->assertSafeToReferenceAfterResize(From, 0);
  181. this->assertSafeToReferenceAfterResize(To - 1, 0);
  182. }
  183. template <
  184. class ItTy,
  185. std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value,
  186. bool> = false>
  187. void assertSafeToReferenceAfterClear(ItTy, ItTy) {}
  188. /// Check whether any part of the range will be invalidated by growing.
  189. void assertSafeToAddRange(const T *From, const T *To) {
  190. if (From == To)
  191. return;
  192. this->assertSafeToAdd(From, To - From);
  193. this->assertSafeToAdd(To - 1, To - From);
  194. }
  195. template <
  196. class ItTy,
  197. std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value,
  198. bool> = false>
  199. void assertSafeToAddRange(ItTy, ItTy) {}
  200. /// Reserve enough space to add one element, and return the updated element
  201. /// pointer in case it was a reference to the storage.
  202. template <class U>
  203. static const T *reserveForParamAndGetAddressImpl(U *This, const T &Elt,
  204. size_t N) {
  205. size_t NewSize = This->size() + N;
  206. if (LLVM_LIKELY(NewSize <= This->capacity()))
  207. return &Elt;
  208. bool ReferencesStorage = false;
  209. int64_t Index = -1;
  210. if (!U::TakesParamByValue) {
  211. if (LLVM_UNLIKELY(This->isReferenceToStorage(&Elt))) {
  212. ReferencesStorage = true;
  213. Index = &Elt - This->begin();
  214. }
  215. }
  216. This->grow(NewSize);
  217. return ReferencesStorage ? This->begin() + Index : &Elt;
  218. }
  219. public:
  220. using size_type = size_t;
  221. using difference_type = ptrdiff_t;
  222. using value_type = T;
  223. using iterator = T *;
  224. using const_iterator = const T *;
  225. using const_reverse_iterator = std::reverse_iterator<const_iterator>;
  226. using reverse_iterator = std::reverse_iterator<iterator>;
  227. using reference = T &;
  228. using const_reference = const T &;
  229. using pointer = T *;
  230. using const_pointer = const T *;
  231. using Base::capacity;
  232. using Base::empty;
  233. using Base::size;
  234. // forward iterator creation methods.
  235. iterator begin() { return (iterator)this->BeginX; }
  236. const_iterator begin() const { return (const_iterator)this->BeginX; }
  237. iterator end() { return begin() + size(); }
  238. const_iterator end() const { return begin() + size(); }
  239. // reverse iterator creation methods.
  240. reverse_iterator rbegin() { return reverse_iterator(end()); }
  241. const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
  242. reverse_iterator rend() { return reverse_iterator(begin()); }
  243. const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
  244. size_type size_in_bytes() const { return size() * sizeof(T); }
  245. size_type max_size() const {
  246. return std::min(this->SizeTypeMax(), size_type(-1) / sizeof(T));
  247. }
  248. size_t capacity_in_bytes() const { return capacity() * sizeof(T); }
  249. /// Return a pointer to the vector's buffer, even if empty().
  250. pointer data() { return pointer(begin()); }
  251. /// Return a pointer to the vector's buffer, even if empty().
  252. const_pointer data() const { return const_pointer(begin()); }
  253. reference operator[](size_type idx) {
  254. assert(idx < size());
  255. return begin()[idx];
  256. }
  257. const_reference operator[](size_type idx) const {
  258. assert(idx < size());
  259. return begin()[idx];
  260. }
  261. reference front() {
  262. assert(!empty());
  263. return begin()[0];
  264. }
  265. const_reference front() const {
  266. assert(!empty());
  267. return begin()[0];
  268. }
  269. reference back() {
  270. assert(!empty());
  271. return end()[-1];
  272. }
  273. const_reference back() const {
  274. assert(!empty());
  275. return end()[-1];
  276. }
  277. };
  278. /// SmallVectorTemplateBase<TriviallyCopyable = false> - This is where we put
  279. /// method implementations that are designed to work with non-trivial T's.
  280. ///
  281. /// We approximate is_trivially_copyable with trivial move/copy construction and
  282. /// trivial destruction. While the standard doesn't specify that you're allowed
  283. /// copy these types with memcpy, there is no way for the type to observe this.
  284. /// This catches the important case of std::pair<POD, POD>, which is not
  285. /// trivially assignable.
  286. template <typename T, bool = (is_trivially_copy_constructible<T>::value) &&
  287. (is_trivially_move_constructible<T>::value) &&
  288. std::is_trivially_destructible<T>::value>
  289. class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
  290. friend class SmallVectorTemplateCommon<T>;
  291. protected:
  292. static constexpr bool TakesParamByValue = false;
  293. using ValueParamT = const T &;
  294. SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
  295. static void destroy_range(T *S, T *E) {
  296. while (S != E) {
  297. --E;
  298. E->~T();
  299. }
  300. }
  301. /// Move the range [I, E) into the uninitialized memory starting with "Dest",
  302. /// constructing elements as needed.
  303. template<typename It1, typename It2>
  304. static void uninitialized_move(It1 I, It1 E, It2 Dest) {
  305. std::uninitialized_move(I, E, Dest);
  306. }
  307. /// Copy the range [I, E) onto the uninitialized memory starting with "Dest",
  308. /// constructing elements as needed.
  309. template<typename It1, typename It2>
  310. static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
  311. std::uninitialized_copy(I, E, Dest);
  312. }
  313. /// Grow the allocated memory (without initializing new elements), doubling
  314. /// the size of the allocated memory. Guarantees space for at least one more
  315. /// element, or MinSize more elements if specified.
  316. void grow(size_t MinSize = 0);
  317. /// Create a new allocation big enough for \p MinSize and pass back its size
  318. /// in \p NewCapacity. This is the first section of \a grow().
  319. T *mallocForGrow(size_t MinSize, size_t &NewCapacity);
  320. /// Move existing elements over to the new allocation \p NewElts, the middle
  321. /// section of \a grow().
  322. void moveElementsForGrow(T *NewElts);
  323. /// Transfer ownership of the allocation, finishing up \a grow().
  324. void takeAllocationForGrow(T *NewElts, size_t NewCapacity);
  325. /// Reserve enough space to add one element, and return the updated element
  326. /// pointer in case it was a reference to the storage.
  327. const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) {
  328. return this->reserveForParamAndGetAddressImpl(this, Elt, N);
  329. }
  330. /// Reserve enough space to add one element, and return the updated element
  331. /// pointer in case it was a reference to the storage.
  332. T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) {
  333. return const_cast<T *>(
  334. this->reserveForParamAndGetAddressImpl(this, Elt, N));
  335. }
  336. static T &&forward_value_param(T &&V) { return std::move(V); }
  337. static const T &forward_value_param(const T &V) { return V; }
  338. void growAndAssign(size_t NumElts, const T &Elt) {
  339. // Grow manually in case Elt is an internal reference.
  340. size_t NewCapacity;
  341. T *NewElts = mallocForGrow(NumElts, NewCapacity);
  342. std::uninitialized_fill_n(NewElts, NumElts, Elt);
  343. this->destroy_range(this->begin(), this->end());
  344. takeAllocationForGrow(NewElts, NewCapacity);
  345. this->set_size(NumElts);
  346. }
  347. template <typename... ArgTypes> T &growAndEmplaceBack(ArgTypes &&... Args) {
  348. // Grow manually in case one of Args is an internal reference.
  349. size_t NewCapacity;
  350. T *NewElts = mallocForGrow(0, NewCapacity);
  351. ::new ((void *)(NewElts + this->size())) T(std::forward<ArgTypes>(Args)...);
  352. moveElementsForGrow(NewElts);
  353. takeAllocationForGrow(NewElts, NewCapacity);
  354. this->set_size(this->size() + 1);
  355. return this->back();
  356. }
  357. public:
  358. void push_back(const T &Elt) {
  359. const T *EltPtr = reserveForParamAndGetAddress(Elt);
  360. ::new ((void *)this->end()) T(*EltPtr);
  361. this->set_size(this->size() + 1);
  362. }
  363. void push_back(T &&Elt) {
  364. T *EltPtr = reserveForParamAndGetAddress(Elt);
  365. ::new ((void *)this->end()) T(::std::move(*EltPtr));
  366. this->set_size(this->size() + 1);
  367. }
  368. void pop_back() {
  369. this->set_size(this->size() - 1);
  370. this->end()->~T();
  371. }
  372. };
  373. // Define this out-of-line to dissuade the C++ compiler from inlining it.
  374. template <typename T, bool TriviallyCopyable>
  375. void SmallVectorTemplateBase<T, TriviallyCopyable>::grow(size_t MinSize) {
  376. size_t NewCapacity;
  377. T *NewElts = mallocForGrow(MinSize, NewCapacity);
  378. moveElementsForGrow(NewElts);
  379. takeAllocationForGrow(NewElts, NewCapacity);
  380. }
  381. template <typename T, bool TriviallyCopyable>
  382. T *SmallVectorTemplateBase<T, TriviallyCopyable>::mallocForGrow(
  383. size_t MinSize, size_t &NewCapacity) {
  384. return static_cast<T *>(
  385. SmallVectorBase<SmallVectorSizeType<T>>::mallocForGrow(
  386. this->getFirstEl(), MinSize, sizeof(T), NewCapacity));
  387. }
  388. // Define this out-of-line to dissuade the C++ compiler from inlining it.
  389. template <typename T, bool TriviallyCopyable>
  390. void SmallVectorTemplateBase<T, TriviallyCopyable>::moveElementsForGrow(
  391. T *NewElts) {
  392. // Move the elements over.
  393. this->uninitialized_move(this->begin(), this->end(), NewElts);
  394. // Destroy the original elements.
  395. destroy_range(this->begin(), this->end());
  396. }
  397. // Define this out-of-line to dissuade the C++ compiler from inlining it.
  398. template <typename T, bool TriviallyCopyable>
  399. void SmallVectorTemplateBase<T, TriviallyCopyable>::takeAllocationForGrow(
  400. T *NewElts, size_t NewCapacity) {
  401. // If this wasn't grown from the inline copy, deallocate the old space.
  402. if (!this->isSmall())
  403. free(this->begin());
  404. this->BeginX = NewElts;
  405. this->Capacity = NewCapacity;
  406. }
  407. /// SmallVectorTemplateBase<TriviallyCopyable = true> - This is where we put
  408. /// method implementations that are designed to work with trivially copyable
  409. /// T's. This allows using memcpy in place of copy/move construction and
  410. /// skipping destruction.
  411. template <typename T>
  412. class SmallVectorTemplateBase<T, true> : public SmallVectorTemplateCommon<T> {
  413. friend class SmallVectorTemplateCommon<T>;
  414. protected:
  415. /// True if it's cheap enough to take parameters by value. Doing so avoids
  416. /// overhead related to mitigations for reference invalidation.
  417. static constexpr bool TakesParamByValue = sizeof(T) <= 2 * sizeof(void *);
  418. /// Either const T& or T, depending on whether it's cheap enough to take
  419. /// parameters by value.
  420. using ValueParamT = std::conditional_t<TakesParamByValue, T, const T &>;
  421. SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
  422. // No need to do a destroy loop for POD's.
  423. static void destroy_range(T *, T *) {}
  424. /// Move the range [I, E) onto the uninitialized memory
  425. /// starting with "Dest", constructing elements into it as needed.
  426. template<typename It1, typename It2>
  427. static void uninitialized_move(It1 I, It1 E, It2 Dest) {
  428. // Just do a copy.
  429. uninitialized_copy(I, E, Dest);
  430. }
  431. /// Copy the range [I, E) onto the uninitialized memory
  432. /// starting with "Dest", constructing elements into it as needed.
  433. template<typename It1, typename It2>
  434. static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
  435. // Arbitrary iterator types; just use the basic implementation.
  436. std::uninitialized_copy(I, E, Dest);
  437. }
  438. /// Copy the range [I, E) onto the uninitialized memory
  439. /// starting with "Dest", constructing elements into it as needed.
  440. template <typename T1, typename T2>
  441. static void uninitialized_copy(
  442. T1 *I, T1 *E, T2 *Dest,
  443. std::enable_if_t<std::is_same<std::remove_const_t<T1>, T2>::value> * =
  444. nullptr) {
  445. // Use memcpy for PODs iterated by pointers (which includes SmallVector
  446. // iterators): std::uninitialized_copy optimizes to memmove, but we can
  447. // use memcpy here. Note that I and E are iterators and thus might be
  448. // invalid for memcpy if they are equal.
  449. if (I != E)
  450. memcpy(reinterpret_cast<void *>(Dest), I, (E - I) * sizeof(T));
  451. }
  452. /// Double the size of the allocated memory, guaranteeing space for at
  453. /// least one more element or MinSize if specified.
  454. void grow(size_t MinSize = 0) { this->grow_pod(MinSize, sizeof(T)); }
  455. /// Reserve enough space to add one element, and return the updated element
  456. /// pointer in case it was a reference to the storage.
  457. const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) {
  458. return this->reserveForParamAndGetAddressImpl(this, Elt, N);
  459. }
  460. /// Reserve enough space to add one element, and return the updated element
  461. /// pointer in case it was a reference to the storage.
  462. T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) {
  463. return const_cast<T *>(
  464. this->reserveForParamAndGetAddressImpl(this, Elt, N));
  465. }
  466. /// Copy \p V or return a reference, depending on \a ValueParamT.
  467. static ValueParamT forward_value_param(ValueParamT V) { return V; }
  468. void growAndAssign(size_t NumElts, T Elt) {
  469. // Elt has been copied in case it's an internal reference, side-stepping
  470. // reference invalidation problems without losing the realloc optimization.
  471. this->set_size(0);
  472. this->grow(NumElts);
  473. std::uninitialized_fill_n(this->begin(), NumElts, Elt);
  474. this->set_size(NumElts);
  475. }
  476. template <typename... ArgTypes> T &growAndEmplaceBack(ArgTypes &&... Args) {
  477. // Use push_back with a copy in case Args has an internal reference,
  478. // side-stepping reference invalidation problems without losing the realloc
  479. // optimization.
  480. push_back(T(std::forward<ArgTypes>(Args)...));
  481. return this->back();
  482. }
  483. public:
  484. void push_back(ValueParamT Elt) {
  485. const T *EltPtr = reserveForParamAndGetAddress(Elt);
  486. memcpy(reinterpret_cast<void *>(this->end()), EltPtr, sizeof(T));
  487. this->set_size(this->size() + 1);
  488. }
  489. void pop_back() { this->set_size(this->size() - 1); }
  490. };
  491. /// This class consists of common code factored out of the SmallVector class to
  492. /// reduce code duplication based on the SmallVector 'N' template parameter.
  493. template <typename T>
  494. class SmallVectorImpl : public SmallVectorTemplateBase<T> {
  495. using SuperClass = SmallVectorTemplateBase<T>;
  496. public:
  497. using iterator = typename SuperClass::iterator;
  498. using const_iterator = typename SuperClass::const_iterator;
  499. using reference = typename SuperClass::reference;
  500. using size_type = typename SuperClass::size_type;
  501. protected:
  502. using SmallVectorTemplateBase<T>::TakesParamByValue;
  503. using ValueParamT = typename SuperClass::ValueParamT;
  504. // Default ctor - Initialize to empty.
  505. explicit SmallVectorImpl(unsigned N)
  506. : SmallVectorTemplateBase<T>(N) {}
  507. void assignRemote(SmallVectorImpl &&RHS) {
  508. this->destroy_range(this->begin(), this->end());
  509. if (!this->isSmall())
  510. free(this->begin());
  511. this->BeginX = RHS.BeginX;
  512. this->Size = RHS.Size;
  513. this->Capacity = RHS.Capacity;
  514. RHS.resetToSmall();
  515. }
  516. public:
  517. SmallVectorImpl(const SmallVectorImpl &) = delete;
  518. ~SmallVectorImpl() {
  519. // Subclass has already destructed this vector's elements.
  520. // If this wasn't grown from the inline copy, deallocate the old space.
  521. if (!this->isSmall())
  522. free(this->begin());
  523. }
  524. void clear() {
  525. this->destroy_range(this->begin(), this->end());
  526. this->Size = 0;
  527. }
  528. private:
  529. // Make set_size() private to avoid misuse in subclasses.
  530. using SuperClass::set_size;
  531. template <bool ForOverwrite> void resizeImpl(size_type N) {
  532. if (N == this->size())
  533. return;
  534. if (N < this->size()) {
  535. this->truncate(N);
  536. return;
  537. }
  538. this->reserve(N);
  539. for (auto I = this->end(), E = this->begin() + N; I != E; ++I)
  540. if (ForOverwrite)
  541. new (&*I) T;
  542. else
  543. new (&*I) T();
  544. this->set_size(N);
  545. }
  546. public:
  547. void resize(size_type N) { resizeImpl<false>(N); }
  548. /// Like resize, but \ref T is POD, the new values won't be initialized.
  549. void resize_for_overwrite(size_type N) { resizeImpl<true>(N); }
  550. /// Like resize, but requires that \p N is less than \a size().
  551. void truncate(size_type N) {
  552. assert(this->size() >= N && "Cannot increase size with truncate");
  553. this->destroy_range(this->begin() + N, this->end());
  554. this->set_size(N);
  555. }
  556. void resize(size_type N, ValueParamT NV) {
  557. if (N == this->size())
  558. return;
  559. if (N < this->size()) {
  560. this->truncate(N);
  561. return;
  562. }
  563. // N > this->size(). Defer to append.
  564. this->append(N - this->size(), NV);
  565. }
  566. void reserve(size_type N) {
  567. if (this->capacity() < N)
  568. this->grow(N);
  569. }
  570. void pop_back_n(size_type NumItems) {
  571. assert(this->size() >= NumItems);
  572. truncate(this->size() - NumItems);
  573. }
  574. [[nodiscard]] T pop_back_val() {
  575. T Result = ::std::move(this->back());
  576. this->pop_back();
  577. return Result;
  578. }
  579. void swap(SmallVectorImpl &RHS);
  580. /// Add the specified range to the end of the SmallVector.
  581. template <typename ItTy, typename = EnableIfConvertibleToInputIterator<ItTy>>
  582. void append(ItTy in_start, ItTy in_end) {
  583. this->assertSafeToAddRange(in_start, in_end);
  584. size_type NumInputs = std::distance(in_start, in_end);
  585. this->reserve(this->size() + NumInputs);
  586. this->uninitialized_copy(in_start, in_end, this->end());
  587. this->set_size(this->size() + NumInputs);
  588. }
  589. /// Append \p NumInputs copies of \p Elt to the end.
  590. void append(size_type NumInputs, ValueParamT Elt) {
  591. const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumInputs);
  592. std::uninitialized_fill_n(this->end(), NumInputs, *EltPtr);
  593. this->set_size(this->size() + NumInputs);
  594. }
  595. void append(std::initializer_list<T> IL) {
  596. append(IL.begin(), IL.end());
  597. }
  598. void append(const SmallVectorImpl &RHS) { append(RHS.begin(), RHS.end()); }
  599. void assign(size_type NumElts, ValueParamT Elt) {
  600. // Note that Elt could be an internal reference.
  601. if (NumElts > this->capacity()) {
  602. this->growAndAssign(NumElts, Elt);
  603. return;
  604. }
  605. // Assign over existing elements.
  606. std::fill_n(this->begin(), std::min(NumElts, this->size()), Elt);
  607. if (NumElts > this->size())
  608. std::uninitialized_fill_n(this->end(), NumElts - this->size(), Elt);
  609. else if (NumElts < this->size())
  610. this->destroy_range(this->begin() + NumElts, this->end());
  611. this->set_size(NumElts);
  612. }
  613. // FIXME: Consider assigning over existing elements, rather than clearing &
  614. // re-initializing them - for all assign(...) variants.
  615. template <typename ItTy, typename = EnableIfConvertibleToInputIterator<ItTy>>
  616. void assign(ItTy in_start, ItTy in_end) {
  617. this->assertSafeToReferenceAfterClear(in_start, in_end);
  618. clear();
  619. append(in_start, in_end);
  620. }
  621. void assign(std::initializer_list<T> IL) {
  622. clear();
  623. append(IL);
  624. }
  625. void assign(const SmallVectorImpl &RHS) { assign(RHS.begin(), RHS.end()); }
  626. iterator erase(const_iterator CI) {
  627. // Just cast away constness because this is a non-const member function.
  628. iterator I = const_cast<iterator>(CI);
  629. assert(this->isReferenceToStorage(CI) && "Iterator to erase is out of bounds.");
  630. iterator N = I;
  631. // Shift all elts down one.
  632. std::move(I+1, this->end(), I);
  633. // Drop the last elt.
  634. this->pop_back();
  635. return(N);
  636. }
  637. iterator erase(const_iterator CS, const_iterator CE) {
  638. // Just cast away constness because this is a non-const member function.
  639. iterator S = const_cast<iterator>(CS);
  640. iterator E = const_cast<iterator>(CE);
  641. assert(this->isRangeInStorage(S, E) && "Range to erase is out of bounds.");
  642. iterator N = S;
  643. // Shift all elts down.
  644. iterator I = std::move(E, this->end(), S);
  645. // Drop the last elts.
  646. this->destroy_range(I, this->end());
  647. this->set_size(I - this->begin());
  648. return(N);
  649. }
  650. private:
  651. template <class ArgType> iterator insert_one_impl(iterator I, ArgType &&Elt) {
  652. // Callers ensure that ArgType is derived from T.
  653. static_assert(
  654. std::is_same<std::remove_const_t<std::remove_reference_t<ArgType>>,
  655. T>::value,
  656. "ArgType must be derived from T!");
  657. if (I == this->end()) { // Important special case for empty vector.
  658. this->push_back(::std::forward<ArgType>(Elt));
  659. return this->end()-1;
  660. }
  661. assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.");
  662. // Grow if necessary.
  663. size_t Index = I - this->begin();
  664. std::remove_reference_t<ArgType> *EltPtr =
  665. this->reserveForParamAndGetAddress(Elt);
  666. I = this->begin() + Index;
  667. ::new ((void*) this->end()) T(::std::move(this->back()));
  668. // Push everything else over.
  669. std::move_backward(I, this->end()-1, this->end());
  670. this->set_size(this->size() + 1);
  671. // If we just moved the element we're inserting, be sure to update
  672. // the reference (never happens if TakesParamByValue).
  673. static_assert(!TakesParamByValue || std::is_same<ArgType, T>::value,
  674. "ArgType must be 'T' when taking by value!");
  675. if (!TakesParamByValue && this->isReferenceToRange(EltPtr, I, this->end()))
  676. ++EltPtr;
  677. *I = ::std::forward<ArgType>(*EltPtr);
  678. return I;
  679. }
  680. public:
  681. iterator insert(iterator I, T &&Elt) {
  682. return insert_one_impl(I, this->forward_value_param(std::move(Elt)));
  683. }
  684. iterator insert(iterator I, const T &Elt) {
  685. return insert_one_impl(I, this->forward_value_param(Elt));
  686. }
  687. iterator insert(iterator I, size_type NumToInsert, ValueParamT Elt) {
  688. // Convert iterator to elt# to avoid invalidating iterator when we reserve()
  689. size_t InsertElt = I - this->begin();
  690. if (I == this->end()) { // Important special case for empty vector.
  691. append(NumToInsert, Elt);
  692. return this->begin()+InsertElt;
  693. }
  694. assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.");
  695. // Ensure there is enough space, and get the (maybe updated) address of
  696. // Elt.
  697. const T *EltPtr = this->reserveForParamAndGetAddress(Elt, NumToInsert);
  698. // Uninvalidate the iterator.
  699. I = this->begin()+InsertElt;
  700. // If there are more elements between the insertion point and the end of the
  701. // range than there are being inserted, we can use a simple approach to
  702. // insertion. Since we already reserved space, we know that this won't
  703. // reallocate the vector.
  704. if (size_t(this->end()-I) >= NumToInsert) {
  705. T *OldEnd = this->end();
  706. append(std::move_iterator<iterator>(this->end() - NumToInsert),
  707. std::move_iterator<iterator>(this->end()));
  708. // Copy the existing elements that get replaced.
  709. std::move_backward(I, OldEnd-NumToInsert, OldEnd);
  710. // If we just moved the element we're inserting, be sure to update
  711. // the reference (never happens if TakesParamByValue).
  712. if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end())
  713. EltPtr += NumToInsert;
  714. std::fill_n(I, NumToInsert, *EltPtr);
  715. return I;
  716. }
  717. // Otherwise, we're inserting more elements than exist already, and we're
  718. // not inserting at the end.
  719. // Move over the elements that we're about to overwrite.
  720. T *OldEnd = this->end();
  721. this->set_size(this->size() + NumToInsert);
  722. size_t NumOverwritten = OldEnd-I;
  723. this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
  724. // If we just moved the element we're inserting, be sure to update
  725. // the reference (never happens if TakesParamByValue).
  726. if (!TakesParamByValue && I <= EltPtr && EltPtr < this->end())
  727. EltPtr += NumToInsert;
  728. // Replace the overwritten part.
  729. std::fill_n(I, NumOverwritten, *EltPtr);
  730. // Insert the non-overwritten middle part.
  731. std::uninitialized_fill_n(OldEnd, NumToInsert - NumOverwritten, *EltPtr);
  732. return I;
  733. }
  734. template <typename ItTy, typename = EnableIfConvertibleToInputIterator<ItTy>>
  735. iterator insert(iterator I, ItTy From, ItTy To) {
  736. // Convert iterator to elt# to avoid invalidating iterator when we reserve()
  737. size_t InsertElt = I - this->begin();
  738. if (I == this->end()) { // Important special case for empty vector.
  739. append(From, To);
  740. return this->begin()+InsertElt;
  741. }
  742. assert(this->isReferenceToStorage(I) && "Insertion iterator is out of bounds.");
  743. // Check that the reserve that follows doesn't invalidate the iterators.
  744. this->assertSafeToAddRange(From, To);
  745. size_t NumToInsert = std::distance(From, To);
  746. // Ensure there is enough space.
  747. reserve(this->size() + NumToInsert);
  748. // Uninvalidate the iterator.
  749. I = this->begin()+InsertElt;
  750. // If there are more elements between the insertion point and the end of the
  751. // range than there are being inserted, we can use a simple approach to
  752. // insertion. Since we already reserved space, we know that this won't
  753. // reallocate the vector.
  754. if (size_t(this->end()-I) >= NumToInsert) {
  755. T *OldEnd = this->end();
  756. append(std::move_iterator<iterator>(this->end() - NumToInsert),
  757. std::move_iterator<iterator>(this->end()));
  758. // Copy the existing elements that get replaced.
  759. std::move_backward(I, OldEnd-NumToInsert, OldEnd);
  760. std::copy(From, To, I);
  761. return I;
  762. }
  763. // Otherwise, we're inserting more elements than exist already, and we're
  764. // not inserting at the end.
  765. // Move over the elements that we're about to overwrite.
  766. T *OldEnd = this->end();
  767. this->set_size(this->size() + NumToInsert);
  768. size_t NumOverwritten = OldEnd-I;
  769. this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten);
  770. // Replace the overwritten part.
  771. for (T *J = I; NumOverwritten > 0; --NumOverwritten) {
  772. *J = *From;
  773. ++J; ++From;
  774. }
  775. // Insert the non-overwritten middle part.
  776. this->uninitialized_copy(From, To, OldEnd);
  777. return I;
  778. }
  779. void insert(iterator I, std::initializer_list<T> IL) {
  780. insert(I, IL.begin(), IL.end());
  781. }
  782. template <typename... ArgTypes> reference emplace_back(ArgTypes &&... Args) {
  783. if (LLVM_UNLIKELY(this->size() >= this->capacity()))
  784. return this->growAndEmplaceBack(std::forward<ArgTypes>(Args)...);
  785. ::new ((void *)this->end()) T(std::forward<ArgTypes>(Args)...);
  786. this->set_size(this->size() + 1);
  787. return this->back();
  788. }
  789. SmallVectorImpl &operator=(const SmallVectorImpl &RHS);
  790. SmallVectorImpl &operator=(SmallVectorImpl &&RHS);
  791. bool operator==(const SmallVectorImpl &RHS) const {
  792. if (this->size() != RHS.size()) return false;
  793. return std::equal(this->begin(), this->end(), RHS.begin());
  794. }
  795. bool operator!=(const SmallVectorImpl &RHS) const {
  796. return !(*this == RHS);
  797. }
  798. bool operator<(const SmallVectorImpl &RHS) const {
  799. return std::lexicographical_compare(this->begin(), this->end(),
  800. RHS.begin(), RHS.end());
  801. }
  802. bool operator>(const SmallVectorImpl &RHS) const { return RHS < *this; }
  803. bool operator<=(const SmallVectorImpl &RHS) const { return !(*this > RHS); }
  804. bool operator>=(const SmallVectorImpl &RHS) const { return !(*this < RHS); }
  805. };
  806. template <typename T>
  807. void SmallVectorImpl<T>::swap(SmallVectorImpl<T> &RHS) {
  808. if (this == &RHS) return;
  809. // We can only avoid copying elements if neither vector is small.
  810. if (!this->isSmall() && !RHS.isSmall()) {
  811. std::swap(this->BeginX, RHS.BeginX);
  812. std::swap(this->Size, RHS.Size);
  813. std::swap(this->Capacity, RHS.Capacity);
  814. return;
  815. }
  816. this->reserve(RHS.size());
  817. RHS.reserve(this->size());
  818. // Swap the shared elements.
  819. size_t NumShared = this->size();
  820. if (NumShared > RHS.size()) NumShared = RHS.size();
  821. for (size_type i = 0; i != NumShared; ++i)
  822. std::swap((*this)[i], RHS[i]);
  823. // Copy over the extra elts.
  824. if (this->size() > RHS.size()) {
  825. size_t EltDiff = this->size() - RHS.size();
  826. this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end());
  827. RHS.set_size(RHS.size() + EltDiff);
  828. this->destroy_range(this->begin()+NumShared, this->end());
  829. this->set_size(NumShared);
  830. } else if (RHS.size() > this->size()) {
  831. size_t EltDiff = RHS.size() - this->size();
  832. this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end());
  833. this->set_size(this->size() + EltDiff);
  834. this->destroy_range(RHS.begin()+NumShared, RHS.end());
  835. RHS.set_size(NumShared);
  836. }
  837. }
  838. template <typename T>
  839. SmallVectorImpl<T> &SmallVectorImpl<T>::
  840. operator=(const SmallVectorImpl<T> &RHS) {
  841. // Avoid self-assignment.
  842. if (this == &RHS) return *this;
  843. // If we already have sufficient space, assign the common elements, then
  844. // destroy any excess.
  845. size_t RHSSize = RHS.size();
  846. size_t CurSize = this->size();
  847. if (CurSize >= RHSSize) {
  848. // Assign common elements.
  849. iterator NewEnd;
  850. if (RHSSize)
  851. NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin());
  852. else
  853. NewEnd = this->begin();
  854. // Destroy excess elements.
  855. this->destroy_range(NewEnd, this->end());
  856. // Trim.
  857. this->set_size(RHSSize);
  858. return *this;
  859. }
  860. // If we have to grow to have enough elements, destroy the current elements.
  861. // This allows us to avoid copying them during the grow.
  862. // FIXME: don't do this if they're efficiently moveable.
  863. if (this->capacity() < RHSSize) {
  864. // Destroy current elements.
  865. this->clear();
  866. CurSize = 0;
  867. this->grow(RHSSize);
  868. } else if (CurSize) {
  869. // Otherwise, use assignment for the already-constructed elements.
  870. std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin());
  871. }
  872. // Copy construct the new elements in place.
  873. this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(),
  874. this->begin()+CurSize);
  875. // Set end.
  876. this->set_size(RHSSize);
  877. return *this;
  878. }
  879. template <typename T>
  880. SmallVectorImpl<T> &SmallVectorImpl<T>::operator=(SmallVectorImpl<T> &&RHS) {
  881. // Avoid self-assignment.
  882. if (this == &RHS) return *this;
  883. // If the RHS isn't small, clear this vector and then steal its buffer.
  884. if (!RHS.isSmall()) {
  885. this->assignRemote(std::move(RHS));
  886. return *this;
  887. }
  888. // If we already have sufficient space, assign the common elements, then
  889. // destroy any excess.
  890. size_t RHSSize = RHS.size();
  891. size_t CurSize = this->size();
  892. if (CurSize >= RHSSize) {
  893. // Assign common elements.
  894. iterator NewEnd = this->begin();
  895. if (RHSSize)
  896. NewEnd = std::move(RHS.begin(), RHS.end(), NewEnd);
  897. // Destroy excess elements and trim the bounds.
  898. this->destroy_range(NewEnd, this->end());
  899. this->set_size(RHSSize);
  900. // Clear the RHS.
  901. RHS.clear();
  902. return *this;
  903. }
  904. // If we have to grow to have enough elements, destroy the current elements.
  905. // This allows us to avoid copying them during the grow.
  906. // FIXME: this may not actually make any sense if we can efficiently move
  907. // elements.
  908. if (this->capacity() < RHSSize) {
  909. // Destroy current elements.
  910. this->clear();
  911. CurSize = 0;
  912. this->grow(RHSSize);
  913. } else if (CurSize) {
  914. // Otherwise, use assignment for the already-constructed elements.
  915. std::move(RHS.begin(), RHS.begin()+CurSize, this->begin());
  916. }
  917. // Move-construct the new elements in place.
  918. this->uninitialized_move(RHS.begin()+CurSize, RHS.end(),
  919. this->begin()+CurSize);
  920. // Set end.
  921. this->set_size(RHSSize);
  922. RHS.clear();
  923. return *this;
  924. }
  925. /// Storage for the SmallVector elements. This is specialized for the N=0 case
  926. /// to avoid allocating unnecessary storage.
  927. template <typename T, unsigned N>
  928. struct SmallVectorStorage {
  929. alignas(T) char InlineElts[N * sizeof(T)];
  930. };
  931. /// We need the storage to be properly aligned even for small-size of 0 so that
  932. /// the pointer math in \a SmallVectorTemplateCommon::getFirstEl() is
  933. /// well-defined.
  934. template <typename T> struct alignas(T) SmallVectorStorage<T, 0> {};
  935. /// Forward declaration of SmallVector so that
  936. /// calculateSmallVectorDefaultInlinedElements can reference
  937. /// `sizeof(SmallVector<T, 0>)`.
  938. template <typename T, unsigned N> class LLVM_GSL_OWNER SmallVector;
  939. /// Helper class for calculating the default number of inline elements for
  940. /// `SmallVector<T>`.
  941. ///
  942. /// This should be migrated to a constexpr function when our minimum
  943. /// compiler support is enough for multi-statement constexpr functions.
  944. template <typename T> struct CalculateSmallVectorDefaultInlinedElements {
  945. // Parameter controlling the default number of inlined elements
  946. // for `SmallVector<T>`.
  947. //
  948. // The default number of inlined elements ensures that
  949. // 1. There is at least one inlined element.
  950. // 2. `sizeof(SmallVector<T>) <= kPreferredSmallVectorSizeof` unless
  951. // it contradicts 1.
  952. static constexpr size_t kPreferredSmallVectorSizeof = 64;
  953. // static_assert that sizeof(T) is not "too big".
  954. //
  955. // Because our policy guarantees at least one inlined element, it is possible
  956. // for an arbitrarily large inlined element to allocate an arbitrarily large
  957. // amount of inline storage. We generally consider it an antipattern for a
  958. // SmallVector to allocate an excessive amount of inline storage, so we want
  959. // to call attention to these cases and make sure that users are making an
  960. // intentional decision if they request a lot of inline storage.
  961. //
  962. // We want this assertion to trigger in pathological cases, but otherwise
  963. // not be too easy to hit. To accomplish that, the cutoff is actually somewhat
  964. // larger than kPreferredSmallVectorSizeof (otherwise,
  965. // `SmallVector<SmallVector<T>>` would be one easy way to trip it, and that
  966. // pattern seems useful in practice).
  967. //
  968. // One wrinkle is that this assertion is in theory non-portable, since
  969. // sizeof(T) is in general platform-dependent. However, we don't expect this
  970. // to be much of an issue, because most LLVM development happens on 64-bit
  971. // hosts, and therefore sizeof(T) is expected to *decrease* when compiled for
  972. // 32-bit hosts, dodging the issue. The reverse situation, where development
  973. // happens on a 32-bit host and then fails due to sizeof(T) *increasing* on a
  974. // 64-bit host, is expected to be very rare.
  975. static_assert(
  976. sizeof(T) <= 256,
  977. "You are trying to use a default number of inlined elements for "
  978. "`SmallVector<T>` but `sizeof(T)` is really big! Please use an "
  979. "explicit number of inlined elements with `SmallVector<T, N>` to make "
  980. "sure you really want that much inline storage.");
  981. // Discount the size of the header itself when calculating the maximum inline
  982. // bytes.
  983. static constexpr size_t PreferredInlineBytes =
  984. kPreferredSmallVectorSizeof - sizeof(SmallVector<T, 0>);
  985. static constexpr size_t NumElementsThatFit = PreferredInlineBytes / sizeof(T);
  986. static constexpr size_t value =
  987. NumElementsThatFit == 0 ? 1 : NumElementsThatFit;
  988. };
  989. /// This is a 'vector' (really, a variable-sized array), optimized
  990. /// for the case when the array is small. It contains some number of elements
  991. /// in-place, which allows it to avoid heap allocation when the actual number of
  992. /// elements is below that threshold. This allows normal "small" cases to be
  993. /// fast without losing generality for large inputs.
  994. ///
  995. /// \note
  996. /// In the absence of a well-motivated choice for the number of inlined
  997. /// elements \p N, it is recommended to use \c SmallVector<T> (that is,
  998. /// omitting the \p N). This will choose a default number of inlined elements
  999. /// reasonable for allocation on the stack (for example, trying to keep \c
  1000. /// sizeof(SmallVector<T>) around 64 bytes).
  1001. ///
  1002. /// \warning This does not attempt to be exception safe.
  1003. ///
  1004. /// \see https://llvm.org/docs/ProgrammersManual.html#llvm-adt-smallvector-h
  1005. template <typename T,
  1006. unsigned N = CalculateSmallVectorDefaultInlinedElements<T>::value>
  1007. class LLVM_GSL_OWNER SmallVector : public SmallVectorImpl<T>,
  1008. SmallVectorStorage<T, N> {
  1009. public:
  1010. SmallVector() : SmallVectorImpl<T>(N) {}
  1011. ~SmallVector() {
  1012. // Destroy the constructed elements in the vector.
  1013. this->destroy_range(this->begin(), this->end());
  1014. }
  1015. explicit SmallVector(size_t Size, const T &Value = T())
  1016. : SmallVectorImpl<T>(N) {
  1017. this->assign(Size, Value);
  1018. }
  1019. template <typename ItTy, typename = EnableIfConvertibleToInputIterator<ItTy>>
  1020. SmallVector(ItTy S, ItTy E) : SmallVectorImpl<T>(N) {
  1021. this->append(S, E);
  1022. }
  1023. template <typename RangeTy>
  1024. explicit SmallVector(const iterator_range<RangeTy> &R)
  1025. : SmallVectorImpl<T>(N) {
  1026. this->append(R.begin(), R.end());
  1027. }
  1028. SmallVector(std::initializer_list<T> IL) : SmallVectorImpl<T>(N) {
  1029. this->append(IL);
  1030. }
  1031. template <typename U,
  1032. typename = std::enable_if_t<std::is_convertible<U, T>::value>>
  1033. explicit SmallVector(ArrayRef<U> A) : SmallVectorImpl<T>(N) {
  1034. this->append(A.begin(), A.end());
  1035. }
  1036. SmallVector(const SmallVector &RHS) : SmallVectorImpl<T>(N) {
  1037. if (!RHS.empty())
  1038. SmallVectorImpl<T>::operator=(RHS);
  1039. }
  1040. SmallVector &operator=(const SmallVector &RHS) {
  1041. SmallVectorImpl<T>::operator=(RHS);
  1042. return *this;
  1043. }
  1044. SmallVector(SmallVector &&RHS) : SmallVectorImpl<T>(N) {
  1045. if (!RHS.empty())
  1046. SmallVectorImpl<T>::operator=(::std::move(RHS));
  1047. }
  1048. SmallVector(SmallVectorImpl<T> &&RHS) : SmallVectorImpl<T>(N) {
  1049. if (!RHS.empty())
  1050. SmallVectorImpl<T>::operator=(::std::move(RHS));
  1051. }
  1052. SmallVector &operator=(SmallVector &&RHS) {
  1053. if (N) {
  1054. SmallVectorImpl<T>::operator=(::std::move(RHS));
  1055. return *this;
  1056. }
  1057. // SmallVectorImpl<T>::operator= does not leverage N==0. Optimize the
  1058. // case.
  1059. if (this == &RHS)
  1060. return *this;
  1061. if (RHS.empty()) {
  1062. this->destroy_range(this->begin(), this->end());
  1063. this->Size = 0;
  1064. } else {
  1065. this->assignRemote(std::move(RHS));
  1066. }
  1067. return *this;
  1068. }
  1069. SmallVector &operator=(SmallVectorImpl<T> &&RHS) {
  1070. SmallVectorImpl<T>::operator=(::std::move(RHS));
  1071. return *this;
  1072. }
  1073. SmallVector &operator=(std::initializer_list<T> IL) {
  1074. this->assign(IL);
  1075. return *this;
  1076. }
  1077. };
  1078. template <typename T, unsigned N>
  1079. inline size_t capacity_in_bytes(const SmallVector<T, N> &X) {
  1080. return X.capacity_in_bytes();
  1081. }
  1082. template <typename RangeType>
  1083. using ValueTypeFromRangeType =
  1084. std::remove_const_t<std::remove_reference_t<decltype(*std::begin(
  1085. std::declval<RangeType &>()))>>;
  1086. /// Given a range of type R, iterate the entire range and return a
  1087. /// SmallVector with elements of the vector. This is useful, for example,
  1088. /// when you want to iterate a range and then sort the results.
  1089. template <unsigned Size, typename R>
  1090. SmallVector<ValueTypeFromRangeType<R>, Size> to_vector(R &&Range) {
  1091. return {std::begin(Range), std::end(Range)};
  1092. }
  1093. template <typename R>
  1094. SmallVector<ValueTypeFromRangeType<R>> to_vector(R &&Range) {
  1095. return {std::begin(Range), std::end(Range)};
  1096. }
  1097. template <typename Out, unsigned Size, typename R>
  1098. SmallVector<Out, Size> to_vector_of(R &&Range) {
  1099. return {std::begin(Range), std::end(Range)};
  1100. }
  1101. template <typename Out, typename R> SmallVector<Out> to_vector_of(R &&Range) {
  1102. return {std::begin(Range), std::end(Range)};
  1103. }
  1104. // Explicit instantiations
  1105. extern template class llvm::SmallVectorBase<uint32_t>;
  1106. #if SIZE_MAX > UINT32_MAX
  1107. extern template class llvm::SmallVectorBase<uint64_t>;
  1108. #endif
  1109. } // end namespace llvm
  1110. namespace std {
  1111. /// Implement std::swap in terms of SmallVector swap.
  1112. template<typename T>
  1113. inline void
  1114. swap(llvm::SmallVectorImpl<T> &LHS, llvm::SmallVectorImpl<T> &RHS) {
  1115. LHS.swap(RHS);
  1116. }
  1117. /// Implement std::swap in terms of SmallVector swap.
  1118. template<typename T, unsigned N>
  1119. inline void
  1120. swap(llvm::SmallVector<T, N> &LHS, llvm::SmallVector<T, N> &RHS) {
  1121. LHS.swap(RHS);
  1122. }
  1123. } // end namespace std
  1124. #endif // LLVM_ADT_SMALLVECTOR_H
  1125. #ifdef __GNUC__
  1126. #pragma GCC diagnostic pop
  1127. #endif