1 //===- Memory.h -------------------------------------------------*- C++ -*-===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines arena allocators.
12 // Almost all large objects, such as files, sections or symbols, are
13 // used for the entire lifetime of the linker once they are created.
14 // This usage characteristic makes arena allocator an attractive choice
15 // where the entire linker is one arena. With an arena, newly created
16 // objects belong to the arena and freed all at once when everything is done.
17 // Arena allocators are efficient and easy to understand.
18 // Most objects are allocated using the arena allocators defined by this file.
20 // If you edit this file, please edit COFF/Memory.h too.
22 //===----------------------------------------------------------------------===//
24 #ifndef LLD_ELF_MEMORY_H
25 #define LLD_ELF_MEMORY_H
27 #include "llvm/Support/Allocator.h"
28 #include "llvm/Support/StringSaver.h"
34 // Use this arena if your object doesn't have a destructor.
35 extern llvm::BumpPtrAllocator BAlloc;
36 extern llvm::StringSaver Saver;
38 // These two classes are hack to keep track of all
39 // SpecificBumpPtrAllocator instances.
40 struct SpecificAllocBase {
41 SpecificAllocBase() { Instances.push_back(this); }
42 virtual ~SpecificAllocBase() = default;
43 virtual void reset() = 0;
44 static std::vector<SpecificAllocBase *> Instances;
47 template <class T> struct SpecificAlloc : public SpecificAllocBase {
48 void reset() override { Alloc.DestroyAll(); }
49 llvm::SpecificBumpPtrAllocator<T> Alloc;
52 // Use this arena if your object has a destructor.
53 // Your destructor will be invoked from freeArena().
54 template <typename T, typename... U> T *make(U &&... Args) {
55 static SpecificAlloc<T> Alloc;
56 return new (Alloc.Alloc.Allocate()) T(std::forward<U>(Args)...);
59 inline void freeArena() {
60 for (SpecificAllocBase *Alloc : SpecificAllocBase::Instances)