mem_mgr.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. // TODO: Implement fast stack allocation.
  2. #ifndef _SCTL_MEM_MGR_HPP_
  3. #define _SCTL_MEM_MGR_HPP_
  4. #include <omp.h>
  5. #include <cstdlib>
  6. #include <cstdint>
  7. #include <cassert>
  8. #include <vector>
  9. #include <stack>
  10. #include <map>
  11. #include <set>
  12. #include SCTL_INCLUDE(common.hpp)
  13. namespace SCTL_NAMESPACE {
  14. class MemoryManager;
  15. #ifdef SCTL_MEMDEBUG
  16. template <class ValueType> class ConstIterator {
  17. template <typename T> friend class ConstIterator;
  18. template <typename T> friend class Iterator;
  19. void IteratorAssertChecks(Long j = 0) const;
  20. public:
  21. typedef Long difference_type;
  22. typedef ValueType value_type;
  23. typedef const ValueType* pointer;
  24. typedef const ValueType& reference;
  25. typedef std::random_access_iterator_tag iterator_category;
  26. protected:
  27. char* base;
  28. difference_type len, offset;
  29. Long alloc_ctr;
  30. void* mem_head;
  31. static const Long ValueSize = sizeof(ValueType);
  32. public:
  33. ConstIterator(void* base_ = nullptr) {
  34. base = (char*)base_;
  35. len = 0;
  36. offset = 0;
  37. alloc_ctr = 0;
  38. mem_head = nullptr;
  39. }
  40. // template <size_t LENGTH> ConstIterator(ValueType (&base_)[LENGTH]) { // DEPRECATED
  41. // SCTL_ASSERT(false);
  42. // }
  43. ConstIterator(const ValueType* base_, difference_type len_, bool dynamic_alloc = false);
  44. template <class AnotherType> explicit ConstIterator(const ConstIterator<AnotherType>& I) {
  45. this->base = I.base;
  46. this->len = I.len;
  47. this->offset = I.offset;
  48. SCTL_ASSERT_MSG((uintptr_t)(this->base + this->offset) % alignof(ValueType) == 0, "invalid alignment during pointer type conversion.");
  49. this->alloc_ctr = I.alloc_ctr;
  50. this->mem_head = I.mem_head;
  51. }
  52. // value_type* like operators
  53. reference operator*() const;
  54. const value_type* operator->() const;
  55. reference operator[](difference_type off) const;
  56. // Increment / Decrement
  57. ConstIterator& operator++() {
  58. offset += (Long)sizeof(ValueType);
  59. return *this;
  60. }
  61. ConstIterator operator++(int) {
  62. ConstIterator<ValueType> tmp(*this);
  63. ++*this;
  64. return tmp;
  65. }
  66. ConstIterator& operator--() {
  67. offset -= (Long)sizeof(ValueType);
  68. return *this;
  69. }
  70. ConstIterator operator--(int) {
  71. ConstIterator<ValueType> tmp(*this);
  72. --*this;
  73. return tmp;
  74. }
  75. // Arithmetic
  76. ConstIterator& operator+=(difference_type i) {
  77. offset += i * (Long)sizeof(ValueType);
  78. return *this;
  79. }
  80. ConstIterator operator+(difference_type i) const {
  81. ConstIterator<ValueType> tmp(*this);
  82. tmp.offset += i * (Long)sizeof(ValueType);
  83. return tmp;
  84. }
  85. friend ConstIterator operator+(difference_type i, const ConstIterator& right) { return (right + i); }
  86. ConstIterator& operator-=(difference_type i) {
  87. offset -= i * (Long)sizeof(ValueType);
  88. return *this;
  89. }
  90. ConstIterator operator-(difference_type i) const {
  91. ConstIterator<ValueType> tmp(*this);
  92. tmp.offset -= i * (Long)sizeof(ValueType);
  93. return tmp;
  94. }
  95. difference_type operator-(const ConstIterator& I) const {
  96. // if (base != I.base) SCTL_WARN("comparing two unrelated memory addresses.");
  97. Long diff = ((ValueType*)(base + offset)) - ((ValueType*)(I.base + I.offset));
  98. SCTL_ASSERT_MSG(I.base + I.offset + diff * (Long)sizeof(ValueType) == base + offset, "invalid memory address alignment.");
  99. return diff;
  100. }
  101. // Comparison operators
  102. bool operator==(const ConstIterator& I) const { return (base + offset == I.base + I.offset); }
  103. bool operator!=(const ConstIterator& I) const { return !(*this == I); }
  104. bool operator<(const ConstIterator& I) const {
  105. // if (base != I.base) SCTL_WARN("comparing two unrelated memory addresses.");
  106. return (base + offset) < (I.base + I.offset);
  107. }
  108. bool operator<=(const ConstIterator& I) const {
  109. // if (base != I.base) SCTL_WARN("comparing two unrelated memory addresses.");
  110. return (base + offset) <= (I.base + I.offset);
  111. }
  112. bool operator>(const ConstIterator& I) const {
  113. // if (base != I.base) SCTL_WARN("comparing two unrelated memory addresses.");
  114. return (base + offset) > (I.base + I.offset);
  115. }
  116. bool operator>=(const ConstIterator& I) const {
  117. // if (base != I.base) SCTL_WARN("comparing two unrelated memory addresses.");
  118. return (base + offset) >= (I.base + I.offset);
  119. }
  120. friend std::ostream& operator<<(std::ostream& out, const ConstIterator& I) {
  121. out << "(" << (long long)I.base << "+" << I.offset << ":" << I.len << ")";
  122. return out;
  123. }
  124. };
  125. template <class ValueType> class Iterator : public ConstIterator<ValueType> {
  126. public:
  127. typedef Long difference_type;
  128. typedef ValueType value_type;
  129. typedef ValueType* pointer;
  130. typedef ValueType& reference;
  131. typedef std::random_access_iterator_tag iterator_category;
  132. public:
  133. Iterator(void* base_ = nullptr) : ConstIterator<ValueType>(base_) {}
  134. template <size_t LENGTH> Iterator(ValueType (&base_)[LENGTH]) : ConstIterator<ValueType>(base_) {}
  135. Iterator(ValueType* base_, difference_type len_, bool dynamic_alloc = false) : ConstIterator<ValueType>(base_, len_, dynamic_alloc) {}
  136. template <class AnotherType> explicit Iterator(const ConstIterator<AnotherType>& I) : ConstIterator<ValueType>(I) {}
  137. // value_type* like operators
  138. reference operator*() const;
  139. value_type* operator->() const;
  140. reference operator[](difference_type off) const;
  141. // Increment / Decrement
  142. Iterator& operator++() {
  143. this->offset += (Long)sizeof(ValueType);
  144. return *this;
  145. }
  146. Iterator operator++(int) {
  147. Iterator<ValueType> tmp(*this);
  148. ++*this;
  149. return tmp;
  150. }
  151. Iterator& operator--() {
  152. this->offset -= (Long)sizeof(ValueType);
  153. return *this;
  154. }
  155. Iterator operator--(int) {
  156. Iterator<ValueType> tmp(*this);
  157. --*this;
  158. return tmp;
  159. }
  160. // Arithmetic
  161. Iterator& operator+=(difference_type i) {
  162. this->offset += i * (Long)sizeof(ValueType);
  163. return *this;
  164. }
  165. Iterator operator+(difference_type i) const {
  166. Iterator<ValueType> tmp(*this);
  167. tmp.offset += i * (Long)sizeof(ValueType);
  168. return tmp;
  169. }
  170. friend Iterator operator+(difference_type i, const Iterator& right) { return (right + i); }
  171. Iterator& operator-=(difference_type i) {
  172. this->offset -= i * (Long)sizeof(ValueType);
  173. return *this;
  174. }
  175. Iterator operator-(difference_type i) const {
  176. Iterator<ValueType> tmp(*this);
  177. tmp.offset -= i * (Long)sizeof(ValueType);
  178. return tmp;
  179. }
  180. difference_type operator-(const ConstIterator<ValueType>& I) const { return static_cast<const ConstIterator<ValueType>&>(*this) - I; }
  181. };
  182. template <class ValueType, Long DIM> class StaticArray : public Iterator<ValueType> { // Warning: objects are not byte-copyable
  183. public:
  184. StaticArray();
  185. StaticArray(const StaticArray&);
  186. StaticArray& operator=(const StaticArray&);
  187. ~StaticArray();
  188. StaticArray(std::initializer_list<ValueType> arr_) : StaticArray() {
  189. // static_assert(arr_.size() <= DIM, "too many initializer values"); // allowed in C++14
  190. SCTL_ASSERT_MSG(arr_.size() <= DIM, "too many initializer values");
  191. for (Long i = 0; i < arr_.size(); i++) arr[i] = arr_.begin()[i];
  192. }
  193. private:
  194. Iterator<ValueType> arr;
  195. ValueType arr_[DIM];
  196. };
  197. template <class ValueType> Iterator<ValueType> Ptr2Itr(void* ptr, Long len) { return Iterator<ValueType>((ValueType*)ptr, len); }
  198. template <class ValueType> ConstIterator<ValueType> Ptr2ConstItr(const void* ptr, Long len) { return ConstIterator<ValueType>((ValueType*)ptr, len); }
  199. #else
  200. template <class ValueType> ValueType* Ptr2Itr(void* ptr, Long len) { return (ValueType*) ptr; }
  201. template <class ValueType> const ValueType* Ptr2ConstItr(const void* ptr, Long len) { return (const ValueType*) ptr; }
  202. #endif
  203. /**
  204. * \brief Identify each type uniquely.
  205. */
  206. template <class T> class TypeTraits {
  207. public:
  208. static uintptr_t ID();
  209. };
  210. /**
  211. * \brief MemoryManager class declaration.
  212. */
  213. class MemoryManager {
  214. public:
  215. static const char init_mem_val = 42;
  216. /**
  217. * \brief Header data for each memory block.
  218. */
  219. struct MemHead {
  220. Long n_indx;
  221. Long n_elem;
  222. Long type_size;
  223. Long alloc_ctr;
  224. uintptr_t type_id;
  225. unsigned char check_sum;
  226. };
  227. /**
  228. * \brief Constructor for MemoryManager.
  229. */
  230. MemoryManager(Long N);
  231. /**
  232. * \brief Constructor for MemoryManager.
  233. */
  234. ~MemoryManager();
  235. static MemHead& GetMemHead(char* p);
  236. static void CheckMemHead(const MemHead& p);
  237. Iterator<char> malloc(const Long n_elem = 1, const Long type_size = sizeof(char), const uintptr_t type_id = TypeTraits<char>::ID()) const;
  238. void free(Iterator<char> p) const;
  239. void print() const;
  240. static void test();
  241. // Check all free memory equals init_mem_val
  242. void Check() const;
  243. // A global MemoryManager object. This is the default for aligned_new and aligned_free
  244. static MemoryManager& glbMemMgr() {
  245. static MemoryManager m(SCTL_GLOBAL_MEM_BUFF * 1024LL * 1024LL);
  246. return m;
  247. }
  248. private:
  249. // Private constructor
  250. MemoryManager();
  251. // Private copy constructor
  252. MemoryManager(const MemoryManager& m);
  253. /**
  254. * \brief Node structure for a doubly linked list, representing free and
  255. * occupied memory blocks. Blocks are split, merged or state is changed
  256. * between free and occupied in O(1) time given the pointer to the MemNode.
  257. */
  258. struct MemNode {
  259. bool free;
  260. Long size;
  261. char* mem_ptr;
  262. Long prev, next;
  263. std::multimap<Long, Long>::iterator it;
  264. };
  265. /**
  266. * \brief Return index of one of the available MemNodes from node_stack or
  267. * create new MemNode by resizing node_buff.
  268. */
  269. Long new_node() const;
  270. /**
  271. * \brief Add node index for now available MemNode to node_stack.
  272. */
  273. void delete_node(Long indx) const;
  274. char* buff; // pointer to memory buffer.
  275. Long buff_size; // total buffer size in bytes.
  276. Long n_dummy_indx; // index of first (dummy) MemNode in link list.
  277. mutable std::vector<MemNode> node_buff; // storage for MemNode objects, this can only grow.
  278. mutable std::stack<Long> node_stack; // stack of available free MemNodes from node_buff.
  279. mutable std::multimap<Long, Long> free_map; // pair (MemNode.size, MemNode_id) for all free MemNodes.
  280. mutable omp_lock_t omp_lock; // openmp lock to prevent concurrent changes.
  281. mutable std::set<void*> system_malloc; // track pointers allocated using system malloc.
  282. };
  283. inline uintptr_t align_ptr(uintptr_t ptr) {
  284. const uintptr_t ALIGN_MINUS_ONE = SCTL_MEM_ALIGN - 1;
  285. const uintptr_t NOT_ALIGN_MINUS_ONE = ~ALIGN_MINUS_ONE;
  286. return ((ptr + ALIGN_MINUS_ONE) & NOT_ALIGN_MINUS_ONE);
  287. }
  288. /**
  289. * \brief Aligned allocation as an alternative to new. Uses placement new to
  290. * construct objects.
  291. */
  292. template <class ValueType> Iterator<ValueType> aligned_new(Long n_elem = 1, const MemoryManager* mem_mgr = &MemoryManager::glbMemMgr());
  293. /**
  294. * \brief Aligned de-allocation as an alternative to delete. Calls the object
  295. * destructors. Not sure which destructor is called for virtual classes, this
  296. * is why we also match the TypeTraits<T>::ID()
  297. */
  298. template <class ValueType> void aligned_delete(Iterator<ValueType> A, const MemoryManager* mem_mgr = &MemoryManager::glbMemMgr());
  299. /**
  300. * \brief Wrapper to memcpy. Also checks if source and destination pointers are
  301. * the same.
  302. */
  303. template <class ValueType> Iterator<ValueType> memcopy(Iterator<ValueType> destination, ConstIterator<ValueType> source, Long num);
  304. template <class ValueType> Iterator<ValueType> memset(Iterator<ValueType> ptr, int value, Long num);
  305. } // end namespace SCTL_NAMESPACE
  306. #include SCTL_INCLUDE(mem_mgr.txx)
  307. #endif //_SCTL_MEM_MGR_HPP_