memory-block.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* Shared pool of memory blocks for pool allocators.
  2. Copyright (C) 2015-2018 Free Software Foundation, Inc.
  3. This file is part of GCC.
  4. GCC is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3, or (at your option)
  7. any later version.
  8. GCC is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GCC; see the file COPYING3. If not see
  14. <http://www.gnu.org/licenses/>. */
  15. #ifndef MEMORY_BLOCK_H
  16. #define MEMORY_BLOCK_H
  17. /* Shared pool which allows other memory pools to reuse each others' allocated
  18. memory blocks instead of calling free/malloc again. */
  19. class memory_block_pool
  20. {
  21. public:
  22. /* Blocks have fixed size. This is necessary for sharing. */
  23. static const size_t block_size = 64 * 1024;
  24. memory_block_pool ();
  25. static inline void *allocate () ATTRIBUTE_MALLOC;
  26. static inline void release (void *);
  27. void clear_free_list ();
  28. private:
  29. /* memory_block_pool singleton instance, defined in memory-block.cc. */
  30. static memory_block_pool instance;
  31. struct block_list
  32. {
  33. block_list *m_next;
  34. };
  35. /* Free list. */
  36. block_list *m_blocks;
  37. };
  38. /* Allocate a single block. Reuse a previously returned block, if possible. */
  39. inline void *
  40. memory_block_pool::allocate ()
  41. {
  42. if (instance.m_blocks == NULL)
  43. return XNEWVEC (char, block_size);
  44. void *result = instance.m_blocks;
  45. instance.m_blocks = instance.m_blocks->m_next;
  46. VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (result, block_size));
  47. return result;
  48. }
  49. /* Return UNCAST_BLOCK to the pool. */
  50. inline void
  51. memory_block_pool::release (void *uncast_block)
  52. {
  53. block_list *block = new (uncast_block) block_list;
  54. block->m_next = instance.m_blocks;
  55. instance.m_blocks = block;
  56. }
  57. extern void *mempool_obstack_chunk_alloc (size_t) ATTRIBUTE_MALLOC;
  58. extern void mempool_obstack_chunk_free (void *);
  59. #endif /* MEMORY_BLOCK_H */