-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
container.h
1575 lines (1419 loc) · 47.6 KB
/
container.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file tvm/runtime/container.h
* \brief Common POD(plain old data) container types.
*/
#ifndef TVM_RUNTIME_CONTAINER_H_
#define TVM_RUNTIME_CONTAINER_H_
#include <dmlc/logging.h>
#include <tvm/runtime/memory.h>
#include <tvm/runtime/object.h>
#include <tvm/runtime/packed_func.h>
#include <algorithm>
#include <cstring>
#include <initializer_list>
#include <memory>
#include <string>
// We use c++14 std::experimental::string_view for optimizing hash computation
// only right now, its usage is limited in this file. Any broader usage of
// std::experiment in our core codebase is discouraged and needs community
// discussion for each use case. Reference for feature test macros of
// string_view:
// https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
// https://en.cppreference.com/w/User:D41D8CD98F/feature_testing_macros
#if defined(__cpp_lib_experimental_string_view) && __cpp_lib_experimental_string_view >= 201411
#define TVM_USE_CXX14_STRING_VIEW_HASH 1
#else
#define TVM_USE_CXX14_STRING_VIEW_HASH 0
#endif
// Tested with clang version 9.0.1 and c++17. It will detect string_view support
// correctly.
#if defined(__cpp_lib_string_view) && __cpp_lib_string_view >= 201606
#define TVM_USE_CXX17_STRING_VIEW_HASH 1
#else
#define TVM_USE_CXX17_STRING_VIEW_HASH 0
#endif
#if TVM_USE_CXX17_STRING_VIEW_HASH
#include <string_view>
#elif TVM_USE_CXX14_STRING_VIEW_HASH
#include <experimental/string_view>
#endif
#include <type_traits>
#include <utility>
#include <vector>
namespace tvm {
struct ObjectEqual;
namespace runtime {
/*!
* \brief Base template for classes with array like memory layout.
*
* It provides general methods to access the memory. The memory
* layout is ArrayType + [ElemType]. The alignment of ArrayType
* and ElemType is handled by the memory allocator.
*
* \tparam ArrayType The array header type, contains object specific metadata.
* \tparam ElemType The type of objects stored in the array right after
* ArrayType.
*
* \code
* // Example usage of the template to define a simple array wrapper
* class ArrayObj : public InplaceArrayBase<ArrayObj, Elem> {
* public:
* // Wrap EmplaceInit to initialize the elements
* template <typename Iterator>
* void Init(Iterator begin, Iterator end) {
* size_t num_elems = std::distance(begin, end);
* auto it = begin;
* this->size = 0;
* for (size_t i = 0; i < num_elems; ++i) {
* InplaceArrayBase::EmplaceInit(i, *it++);
* this->size++;
* }
* }
* }
*
* void test_function() {
* vector<Elem> fields;
* auto ptr = make_inplace_array_object<ArrayObj, Elem>(fields.size());
* ptr->Init(fields.begin(), fields.end());
*
* // Access the 0th element in the array.
* assert(ptr->operator[](0) == fields[0]);
* }
*
* \endcode
*/
template <typename ArrayType, typename ElemType>
class InplaceArrayBase {
public:
/*!
* \brief Access element at index
* \param idx The index of the element.
* \return Const reference to ElemType at the index.
*/
const ElemType& operator[](size_t idx) const {
size_t size = Self()->GetSize();
CHECK_LT(idx, size) << "Index " << idx << " out of bounds " << size << "\n";
return *(reinterpret_cast<ElemType*>(AddressOf(idx)));
}
/*!
* \brief Access element at index
* \param idx The index of the element.
* \return Reference to ElemType at the index.
*/
ElemType& operator[](size_t idx) {
size_t size = Self()->GetSize();
CHECK_LT(idx, size) << "Index " << idx << " out of bounds " << size << "\n";
return *(reinterpret_cast<ElemType*>(AddressOf(idx)));
}
/*!
* \brief Destroy the Inplace Array Base object
*/
~InplaceArrayBase() {
if (!(std::is_standard_layout<ElemType>::value && std::is_trivial<ElemType>::value)) {
size_t size = Self()->GetSize();
for (size_t i = 0; i < size; ++i) {
ElemType* fp = reinterpret_cast<ElemType*>(AddressOf(i));
fp->ElemType::~ElemType();
}
}
}
protected:
/*!
* \brief Construct a value in place with the arguments.
*
* \tparam Args Type parameters of the arguments.
* \param idx Index of the element.
* \param args Arguments to construct the new value.
*
* \note Please make sure ArrayType::GetSize returns 0 before first call of
* EmplaceInit, and increment GetSize by 1 each time EmplaceInit succeeds.
*/
template <typename... Args>
void EmplaceInit(size_t idx, Args&&... args) {
void* field_ptr = AddressOf(idx);
new (field_ptr) ElemType(std::forward<Args>(args)...);
}
/*!
* \brief Return the self object for the array.
*
* \return Pointer to ArrayType.
*/
inline ArrayType* Self() const {
return static_cast<ArrayType*>(const_cast<InplaceArrayBase*>(this));
}
/*!
* \brief Return the raw pointer to the element at idx.
*
* \param idx The index of the element.
* \return Raw pointer to the element.
*/
void* AddressOf(size_t idx) const {
static_assert(
alignof(ArrayType) % alignof(ElemType) == 0 && sizeof(ArrayType) % alignof(ElemType) == 0,
"The size and alignment of ArrayType should respect "
"ElemType's alignment.");
size_t kDataStart = sizeof(ArrayType);
ArrayType* self = Self();
char* data_start = reinterpret_cast<char*>(self) + kDataStart;
return data_start + idx * sizeof(ElemType);
}
};
/*!
* \brief iterator adapter that adapts TIter to return another type.
* \tparam Converter a struct that contains converting function
* \tparam TIter the content iterator type.
*/
template <typename Converter, typename TIter>
class IterAdapter {
public:
using difference_type = typename std::iterator_traits<TIter>::difference_type;
using value_type = typename Converter::ResultType;
using pointer = typename Converter::ResultType*;
using reference = typename Converter::ResultType&; // NOLINT(*)
using iterator_category = typename std::iterator_traits<TIter>::iterator_category;
explicit IterAdapter(TIter iter) : iter_(iter) {}
IterAdapter& operator++() {
++iter_;
return *this;
}
IterAdapter& operator--() {
--iter_;
return *this;
}
IterAdapter& operator++(int) {
IterAdapter copy = *this;
++iter_;
return copy;
}
IterAdapter& operator--(int) {
IterAdapter copy = *this;
--iter_;
return copy;
}
IterAdapter operator+(difference_type offset) const { return IterAdapter(iter_ + offset); }
template <typename T = IterAdapter>
typename std::enable_if<std::is_same<iterator_category, std::random_access_iterator_tag>::value,
typename T::difference_type>::type inline
operator-(const IterAdapter& rhs) const {
return iter_ - rhs.iter_;
}
bool operator==(IterAdapter other) const { return iter_ == other.iter_; }
bool operator!=(IterAdapter other) const { return !(*this == other); }
const value_type operator*() const { return Converter::convert(*iter_); }
private:
TIter iter_;
};
/*!
* \brief iterator adapter that adapts TIter to return another type.
* \tparam Converter a struct that contains converting function
* \tparam TIter the content iterator type.
*/
template <typename Converter, typename TIter>
class ReverseIterAdapter {
public:
using difference_type = typename std::iterator_traits<TIter>::difference_type;
using value_type = typename Converter::ResultType;
using pointer = typename Converter::ResultType*;
using reference = typename Converter::ResultType&; // NOLINT(*)
using iterator_category = typename std::iterator_traits<TIter>::iterator_category;
explicit ReverseIterAdapter(TIter iter) : iter_(iter) {}
ReverseIterAdapter& operator++() {
--iter_;
return *this;
}
ReverseIterAdapter& operator--() {
++iter_;
return *this;
}
ReverseIterAdapter& operator++(int) {
ReverseIterAdapter copy = *this;
--iter_;
return copy;
}
ReverseIterAdapter& operator--(int) {
ReverseIterAdapter copy = *this;
++iter_;
return copy;
}
ReverseIterAdapter operator+(difference_type offset) const {
return ReverseIterAdapter(iter_ - offset);
}
template <typename T = ReverseIterAdapter>
typename std::enable_if<std::is_same<iterator_category, std::random_access_iterator_tag>::value,
typename T::difference_type>::type inline
operator-(const ReverseIterAdapter& rhs) const {
return rhs.iter_ - iter_;
}
bool operator==(ReverseIterAdapter other) const { return iter_ == other.iter_; }
bool operator!=(ReverseIterAdapter other) const { return !(*this == other); }
const value_type operator*() const { return Converter::convert(*iter_); }
private:
TIter iter_;
};
/*! \brief array node content in array */
class ArrayNode : public Object, public InplaceArrayBase<ArrayNode, ObjectRef> {
public:
/*! \return The size of the array */
size_t size() const { return this->size_; }
/*!
* \brief Read i-th element from array.
* \param i The index
* \return the i-th element.
*/
const ObjectRef at(int64_t i) const { return this->operator[](i); }
/*! \return begin constant iterator */
const ObjectRef* begin() const { return static_cast<ObjectRef*>(InplaceArrayBase::AddressOf(0)); }
/*! \return end constant iterator */
const ObjectRef* end() const { return begin() + size_; }
/*! \brief Release reference to all the elements */
void clear() { ShrinkBy(size_); }
/*!
* \brief Set i-th element of the array in-place
* \param i The index
* \param item The value to be set
*/
void SetItem(int64_t i, ObjectRef item) { this->operator[](i) = std::move(item); }
/*!
* \brief Constructs a container and copy from another
* \param cap The capacity of the container
* \param from Source of the copy
* \return Ref-counted ArrayNode requested
*/
static ObjectPtr<ArrayNode> CopyFrom(int64_t cap, ArrayNode* from) {
int64_t size = from->size_;
CHECK_GE(cap, size) << "ValueError: not enough capacity";
ObjectPtr<ArrayNode> p = ArrayNode::Empty(cap);
ObjectRef* write = p->MutableBegin();
ObjectRef* read = from->MutableBegin();
// To ensure exception safety, size is only incremented after the initialization succeeds
for (int64_t& i = p->size_ = 0; i < size; ++i) {
new (write++) ObjectRef(*read++);
}
return p;
}
/*!
* \brief Constructs a container and move from another
* \param cap The capacity of the container
* \param from Source of the move
* \return Ref-counted ArrayNode requested
*/
static ObjectPtr<ArrayNode> MoveFrom(int64_t cap, ArrayNode* from) {
int64_t size = from->size_;
CHECK_GE(cap, size) << "ValueError: not enough capacity";
ObjectPtr<ArrayNode> p = ArrayNode::Empty(cap);
ObjectRef* write = p->MutableBegin();
ObjectRef* read = from->MutableBegin();
// To ensure exception safety, size is only incremented after the initialization succeeds
for (int64_t& i = p->size_ = 0; i < size; ++i) {
new (write++) ObjectRef(std::move(*read++));
}
from->size_ = 0;
return p;
}
/*!
* \brief Constructs a container with n elements. Each element is a copy of val
* \param n The size of the container
* \param val The init value
* \return Ref-counted ArrayNode requested
*/
static ObjectPtr<ArrayNode> CreateRepeated(int64_t n, const ObjectRef& val) {
ObjectPtr<ArrayNode> p = ArrayNode::Empty(n);
ObjectRef* itr = p->MutableBegin();
for (int64_t& i = p->size_ = 0; i < n; ++i) {
new (itr++) ObjectRef(val);
}
return p;
}
static constexpr const uint32_t _type_index = TypeIndex::kRuntimeArray;
static constexpr const char* _type_key = "Array";
TVM_DECLARE_FINAL_OBJECT_INFO(ArrayNode, Object);
private:
/*! \return Size of initialized memory, used by InplaceArrayBase. */
size_t GetSize() const { return this->size_; }
/*! \return begin mutable iterator */
ObjectRef* MutableBegin() const {
return static_cast<ObjectRef*>(InplaceArrayBase::AddressOf(0));
}
/*! \return end mutable iterator */
ObjectRef* MutableEnd() const { return MutableBegin() + size_; }
/*!
* \brief Create an ArrayNode with the given capacity.
* \param n Required capacity
* \return Ref-counted ArrayNode requested
*/
static ObjectPtr<ArrayNode> Empty(int64_t n = kInitSize) {
CHECK_GE(n, 0);
ObjectPtr<ArrayNode> p = make_inplace_array_object<ArrayNode, ObjectRef>(n);
p->capacity_ = n;
p->size_ = 0;
return p;
}
/*!
* \brief Inplace-initialize the elements starting idx from [first, last)
* \param idx The starting point
* \param first Begin of iterator
* \param last End of iterator
* \tparam IterType The type of iterator
* \return Self
*/
template <typename IterType>
ArrayNode* InitRange(int64_t idx, IterType first, IterType last) {
ObjectRef* itr = MutableBegin() + idx;
for (; first != last; ++first) {
ObjectRef ref = *first;
new (itr++) ObjectRef(std::move(ref));
}
return this;
}
/*!
* \brief Move elements from right to left, requires src_begin > dst
* \param dst Destination
* \param src_begin The start point of copy (inclusive)
* \param src_end The end point of copy (exclusive)
* \return Self
*/
ArrayNode* MoveElementsLeft(int64_t dst, int64_t src_begin, int64_t src_end) {
ObjectRef* from = MutableBegin() + src_begin;
ObjectRef* to = MutableBegin() + dst;
while (src_begin++ != src_end) {
*to++ = std::move(*from++);
}
return this;
}
/*!
* \brief Move elements from left to right, requires src_begin < dst
* \param dst Destination
* \param src_begin The start point of move (inclusive)
* \param src_end The end point of move (exclusive)
* \return Self
*/
ArrayNode* MoveElementsRight(int64_t dst, int64_t src_begin, int64_t src_end) {
ObjectRef* from = MutableBegin() + src_end;
ObjectRef* to = MutableBegin() + (src_end - src_begin + dst);
while (src_begin++ != src_end) {
*--to = std::move(*--from);
}
return this;
}
/*!
* \brief Enlarges the size of the array
* \param delta Size enlarged, should be positive
* \param val Default value
* \return Self
*/
ArrayNode* EnlargeBy(int64_t delta, const ObjectRef& val = ObjectRef(nullptr)) {
ObjectRef* itr = MutableEnd();
while (delta-- > 0) {
new (itr++) ObjectRef(val);
++size_;
}
return this;
}
/*!
* \brief Shrinks the size of the array
* \param delta Size shrinked, should be positive
* \return Self
*/
ArrayNode* ShrinkBy(int64_t delta) {
ObjectRef* itr = MutableEnd();
while (delta-- > 0) {
(--itr)->ObjectRef::~ObjectRef();
--size_;
}
return this;
}
/*! \brief Number of elements used */
int64_t size_;
/*! \brief Number of elements allocated */
int64_t capacity_;
/*! \brief Initial size of ArrayNode */
static constexpr int64_t kInitSize = 4;
/*! \brief Expansion factor of the Array */
static constexpr int64_t kIncFactor = 2;
// CRTP parent class
friend InplaceArrayBase<ArrayNode, ObjectRef>;
// Reference class
template <typename, typename>
friend class Array;
// To specialize make_object<ArrayNode>
friend ObjectPtr<ArrayNode> make_object<>();
};
/*!
* \brief Array container of ObjectRef in DSL graph.
* Array implements copy-on-write semantics, which means array is mutable
* but copy will happen when array is referenced in more than two places.
*
* operator[] only provide const access, use Set to mutate the content.
* \tparam T The content ObjectRef type.
*/
template <typename T,
typename = typename std::enable_if<std::is_base_of<ObjectRef, T>::value>::type>
class Array : public ObjectRef {
public:
// constructors
/*!
* \brief default constructor
*/
Array() { data_ = ArrayNode::Empty(); }
/*!
* \brief move constructor
* \param other source
*/
Array(Array<T>&& other) : ObjectRef() { // NOLINT(*)
data_ = std::move(other.data_);
}
/*!
* \brief copy constructor
* \param other source
*/
Array(const Array<T>& other) : ObjectRef() { // NOLINT(*)
data_ = other.data_;
}
/*!
* \brief constructor from pointer
* \param n the container pointer
*/
explicit Array(ObjectPtr<Object> n) : ObjectRef(n) {}
/*!
* \brief Constructor from iterator
* \param first begin of iterator
* \param last end of iterator
* \tparam IterType The type of iterator
*/
template <typename IterType>
Array(IterType first, IterType last) {
Assign(first, last);
}
/*!
* \brief constructor from initializer list
* \param init The initializer list
*/
Array(std::initializer_list<T> init) { // NOLINT(*)
Assign(init.begin(), init.end());
}
/*!
* \brief constructor from vector
* \param init The vector
*/
Array(const std::vector<T>& init) { // NOLINT(*)
Assign(init.begin(), init.end());
}
/*!
* \brief Constructs a container with n elements. Each element is a copy of val
* \param n The size of the container
* \param val The init value
*/
explicit Array(const size_t n, const T& val) { data_ = ArrayNode::CreateRepeated(n, val); }
/*!
* \brief move assign operator
* \param other The source of assignment
* \return reference to self.
*/
Array<T>& operator=(Array<T>&& other) {
data_ = std::move(other.data_);
return *this;
}
/*!
* \brief copy assign operator
* \param other The source of assignment
* \return reference to self.
*/
Array<T>& operator=(const Array<T>& other) {
data_ = other.data_;
return *this;
}
public:
// iterators
struct ValueConverter {
using ResultType = T;
static T convert(const ObjectRef& n) { return DowncastNoCheck<T>(n); }
};
using iterator = IterAdapter<ValueConverter, const ObjectRef*>;
using reverse_iterator = ReverseIterAdapter<ValueConverter, const ObjectRef*>;
/*! \return begin iterator */
iterator begin() const { return iterator(GetArrayNode()->begin()); }
/*! \return end iterator */
iterator end() const { return iterator(GetArrayNode()->end()); }
/*! \return rbegin iterator */
reverse_iterator rbegin() const {
// ArrayNode::end() is never nullptr
return reverse_iterator(GetArrayNode()->end() - 1);
}
/*! \return rend iterator */
reverse_iterator rend() const {
// ArrayNode::begin() is never nullptr
return reverse_iterator(GetArrayNode()->begin() - 1);
}
public:
// const methods in std::vector
/*!
* \brief Immutably read i-th element from array.
* \param i The index
* \return the i-th element.
*/
const T operator[](int64_t i) const {
ArrayNode* p = GetArrayNode();
CHECK(p != nullptr) << "ValueError: cannot index a null array";
CHECK(0 <= i && i < p->size_) << "IndexError: indexing " << i << " on an array of size "
<< p->size_;
return DowncastNoCheck<T>(*(p->begin() + i));
}
/*! \return The size of the array */
size_t size() const {
ArrayNode* p = GetArrayNode();
return p == nullptr ? 0 : GetArrayNode()->size_;
}
/*! \return The capacity of the array */
size_t capacity() const {
ArrayNode* p = GetArrayNode();
return p == nullptr ? 0 : GetArrayNode()->capacity_;
}
/*! \return Whether array is empty */
bool empty() const { return size() == 0; }
/*! \return The first element of the array */
const T front() const {
ArrayNode* p = GetArrayNode();
CHECK(p != nullptr) << "ValueError: cannot index a null array";
CHECK_GT(p->size_, 0) << "IndexError: cannot index an empty array";
return DowncastNoCheck<T>(*(p->begin()));
}
/*! \return The last element of the array */
const T back() const {
ArrayNode* p = GetArrayNode();
CHECK(p != nullptr) << "ValueError: cannot index a null array";
CHECK_GT(p->size_, 0) << "IndexError: cannot index an empty array";
return DowncastNoCheck<T>(*(p->end() - 1));
}
public:
// mutation in std::vector, implements copy-on-write
/*!
* \brief push a new item to the back of the list
* \param item The item to be pushed.
*/
void push_back(const T& item) {
ArrayNode* p = CopyOnWrite(1);
p->EmplaceInit(p->size_++, item);
}
/*!
* \brief Insert an element into the given position
* \param position An iterator pointing to the insertion point
* \param val The element to insert
*/
void insert(iterator position, const T& val) {
CHECK(data_ != nullptr) << "ValueError: cannot insert a null array";
int64_t idx = std::distance(begin(), position);
int64_t size = GetArrayNode()->size_;
auto addr = CopyOnWrite(1) //
->EnlargeBy(1) //
->MoveElementsRight(idx + 1, idx, size) //
->MutableBegin();
new (addr + idx) ObjectRef(val);
}
/*!
* \brief Insert a range of elements into the given position
* \param position An iterator pointing to the insertion point
* \param first The begin iterator of the range
* \param last The end iterator of the range
*/
template <typename IterType>
void insert(iterator position, IterType first, IterType last) {
if (first == last) {
return;
}
CHECK(data_ != nullptr) << "ValueError: cannot insert a null array";
int64_t idx = std::distance(begin(), position);
int64_t size = GetArrayNode()->size_;
int64_t numel = std::distance(first, last);
CopyOnWrite(numel)
->EnlargeBy(numel)
->MoveElementsRight(idx + numel, idx, size)
->InitRange(idx, first, last);
}
/*! \brief Remove the last item of the list */
void pop_back() {
CHECK(data_ != nullptr) << "ValueError: cannot pop_back because array is null";
int64_t size = GetArrayNode()->size_;
CHECK_GT(size, 0) << "ValueError: cannot pop_back because array is empty";
CopyOnWrite()->ShrinkBy(1);
}
/*!
* \brief Erase an element on the given position
* \param position An iterator pointing to the element to be erased
*/
void erase(iterator position) {
CHECK(data_ != nullptr) << "ValueError: cannot erase a null array";
int64_t st = std::distance(begin(), position);
int64_t size = GetArrayNode()->size_;
CHECK(0 <= st && st < size) << "ValueError: cannot erase at index " << st
<< ", because Array size is " << size;
CopyOnWrite() //
->MoveElementsLeft(st, st + 1, size) //
->ShrinkBy(1);
}
/*!
* \brief Erase a given range of elements
* \param first The begin iterator of the range
* \param last The end iterator of the range
*/
void erase(iterator first, iterator last) {
if (first == last) {
return;
}
CHECK(data_ != nullptr) << "ValueError: cannot erase a null array";
int64_t size = GetArrayNode()->size_;
int64_t st = std::distance(begin(), first);
int64_t ed = std::distance(begin(), last);
CHECK_LT(st, ed) << "ValueError: cannot erase array in range [" << st << ", " << ed << ")";
CHECK(0 <= st && st <= size && 0 <= ed && ed <= size)
<< "ValueError: cannot erase array in range [" << st << ", " << ed << ")"
<< ", because array size is " << size;
CopyOnWrite() //
->MoveElementsLeft(st, ed, size) //
->ShrinkBy(ed - st);
}
/*!
* \brief Resize the array.
* \param n The new size.
*/
void resize(int64_t n) {
CHECK_GE(n, 0) << "ValueError: cannot resize an Array to negative size";
if (data_ == nullptr) {
SwitchContainer(n);
return;
}
int64_t size = GetArrayNode()->size_;
if (size < n) {
CopyOnWrite(n - size)->EnlargeBy(n - size);
} else if (size > n) {
CopyOnWrite()->ShrinkBy(size - n);
}
}
/*!
* \brief Make sure the list has the capacity of at least n
* \param n lower bound of the capacity
*/
void reserve(int64_t n) {
if (data_ == nullptr || n > GetArrayNode()->capacity_) {
SwitchContainer(n);
}
}
/*! \brief Release reference to all the elements */
void clear() {
if (data_ != nullptr) {
ArrayNode* p = CopyOnWrite();
p->clear();
}
}
public:
// Array's own methods
/*!
* \brief set i-th element of the array.
* \param i The index
* \param value The value to be setted.
*/
void Set(int64_t i, T value) {
ArrayNode* p = this->CopyOnWrite();
CHECK(0 <= i && i < p->size_) << "IndexError: indexing " << i << " on an array of size "
<< p->size_;
*(p->MutableBegin() + i) = std::move(value);
}
/*! \return The underlying ArrayNode */
ArrayNode* GetArrayNode() const { return static_cast<ArrayNode*>(data_.get()); }
/*!
* \brief Helper function to apply fmutate to mutate an array.
* \param fmutate The transformation function T -> T.
* \tparam F the type of the mutation function.
* \note This function performs copy on write optimization.
*/
template <typename F>
void MutateByApply(F fmutate) {
if (data_ == nullptr) {
return;
}
struct StackFrame {
ArrayNode* p;
ObjectRef* itr;
int64_t i;
int64_t size;
};
std::unique_ptr<StackFrame> s = std::make_unique<StackFrame>();
s->p = GetArrayNode();
s->itr = s->p->MutableBegin();
s->i = 0;
s->size = s->p->size_;
if (!data_.unique()) {
// Loop invariant: keeps iterating when
// 1) data is not unique
// 2) no elements are actually mutated yet
for (; s->i < s->size; ++s->i, ++s->itr) {
T new_elem = fmutate(DowncastNoCheck<T>(*s->itr));
// do nothing when there is no mutation
if (new_elem.same_as(*s->itr)) {
continue;
}
// loop invariant breaks when the first real mutation happens
// we copy the elements into a new unique array
ObjectPtr<ArrayNode> copy = ArrayNode::CopyFrom(s->p->capacity_, s->p);
s->itr = copy->MutableBegin() + (s->i++);
*s->itr++ = std::move(new_elem);
data_ = std::move(copy);
// make sure `data_` is unique and break
break;
}
}
// when execution comes to this line, it is guaranteed that either
// 1) i == size
// or 2) data_.unique() is true
for (; s->i < s->size; ++s->i, ++s->itr) {
*s->itr = std::move(fmutate(std::move(DowncastNoCheck<T>(std::move(*s->itr)))));
}
}
/*!
* \brief reset the array to content from iterator.
* \param first begin of iterator
* \param last end of iterator
* \tparam IterType The type of iterator
*/
template <typename IterType>
void Assign(IterType first, IterType last) {
int64_t cap = std::distance(first, last);
CHECK_GE(cap, 0) << "ValueError: cannot construct an Array of negative size";
ArrayNode* p = GetArrayNode();
if (p != nullptr && data_.unique() && p->capacity_ >= cap) {
// do not have to make new space
p->clear();
} else {
// create new space
data_ = ArrayNode::Empty(cap);
p = GetArrayNode();
}
// To ensure exception safety, size is only incremented after the initialization succeeds
ObjectRef* itr = p->MutableBegin();
for (int64_t& i = p->size_ = 0; i < cap; ++i, ++first, ++itr) {
new (itr) ObjectRef(*first);
}
}
/*!
* \brief Copy on write semantics
* Do nothing if current handle is the unique copy of the array.
* Otherwise make a new copy of the array to ensure the current handle
* hold a unique copy.
*
* \return Handle to the internal node container(which ganrantees to be unique)
*/
ArrayNode* CopyOnWrite() {
if (data_ == nullptr) {
return SwitchContainer(ArrayNode::kInitSize);
}
if (!data_.unique()) {
return SwitchContainer(capacity());
}
return static_cast<ArrayNode*>(data_.get());
}
/*! \brief specify container node */
using ContainerType = ArrayNode;
private:
/*!
* \brief Implement copy-on-write semantics, and ensures capacity is enough for extra elements.
* \param reserve_extra Number of extra slots needed
* \return ArrayNode pointer to the unique copy
*/
ArrayNode* CopyOnWrite(int64_t reserve_extra) {
ArrayNode* p = GetArrayNode();
if (p == nullptr) {
// necessary to get around the constexpr address issue before c++17
const int64_t kInitSize = ArrayNode::kInitSize;
return SwitchContainer(std::max(kInitSize, reserve_extra));
}
if (p->capacity_ >= p->size_ + reserve_extra) {
return CopyOnWrite();
}
int64_t cap = p->capacity_ * ArrayNode::kIncFactor;
cap = std::max(cap, p->size_ + reserve_extra);
return SwitchContainer(cap);
}
/*!
* \brief Move or copy the ArrayNode to new address with the given capacity
* \param capacity The capacity requirement of the new address
*/
ArrayNode* SwitchContainer(int64_t capacity) {
if (data_ == nullptr) {
data_ = ArrayNode::Empty(capacity);
} else if (data_.unique()) {
data_ = ArrayNode::MoveFrom(capacity, GetArrayNode());
} else {
data_ = ArrayNode::CopyFrom(capacity, GetArrayNode());
}
return static_cast<ArrayNode*>(data_.get());
}
};
// Specialize make_object<ArrayNode> to make sure it is correct.
template <>
inline ObjectPtr<ArrayNode> make_object() {
return ArrayNode::Empty();
}
/*! \brief An object representing a structure or enumeration. */
class ADTObj : public Object, public InplaceArrayBase<ADTObj, ObjectRef> {
public:
/*! \brief The tag representing the constructor used. */
int32_t tag;
/*! \brief Number of fields in the ADT object. */
uint32_t size;
// The fields of the structure follows directly in memory.
static constexpr const uint32_t _type_index = TypeIndex::kRuntimeADT;
static constexpr const char* _type_key = "runtime.ADT";
TVM_DECLARE_FINAL_OBJECT_INFO(ADTObj, Object);
private:
/*!
* \return The number of elements in the array.
*/
size_t GetSize() const { return size; }
/*!
* \brief Initialize the elements in the array.
*
* \tparam Iterator Iterator type of the array.
* \param begin The begin iterator.
* \param end The end iterator.
*/
template <typename Iterator>
void Init(Iterator begin, Iterator end) {
size_t num_elems = std::distance(begin, end);
this->size = 0;
auto it = begin;
for (size_t i = 0; i < num_elems; ++i) {