heap.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef EXECUTABLE_SEMANTICS_INTERPRETER_MEMORY_H_
  5. #define EXECUTABLE_SEMANTICS_INTERPRETER_MEMORY_H_
  6. #include <vector>
  7. #include "common/ostream.h"
  8. #include "executable_semantics/interpreter/address.h"
  9. #include "executable_semantics/interpreter/value.h"
  10. #include "llvm/Support/Compiler.h"
  11. namespace Carbon {
  12. // A Heap represents the abstract machine's dynamically allocated memory.
  13. class Heap {
  14. public:
  15. // Constructs an empty Heap.
  16. explicit Heap(Nonnull<Arena*> arena) : arena(arena){};
  17. Heap(const Heap&) = delete;
  18. Heap& operator=(const Heap&) = delete;
  19. // Returns the value at the given address in the heap after
  20. // checking that it is alive.
  21. auto Read(const Address& a, SourceLocation source_loc)
  22. -> Nonnull<const Value*>;
  23. // Writes the given value at the address in the heap after
  24. // checking that the address is alive.
  25. void Write(const Address& a, Nonnull<const Value*> v,
  26. SourceLocation source_loc);
  27. // Put the given value on the heap and mark it as alive.
  28. auto AllocateValue(Nonnull<const Value*> v) -> Address;
  29. // Marks the object at this address, and all of its sub-objects, as dead.
  30. void Deallocate(const Address& address);
  31. // Print the value at the given address to the stream `out`.
  32. void PrintAddress(const Address& a, llvm::raw_ostream& out) const;
  33. // Print all the values on the heap to the stream `out`.
  34. void Print(llvm::raw_ostream& out) const;
  35. LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
  36. private:
  37. // Signal an error if the address is no longer alive.
  38. void CheckAlive(const Address& address, SourceLocation source_loc);
  39. Nonnull<Arena*> arena;
  40. std::vector<Nonnull<const Value*>> values;
  41. std::vector<bool> alive;
  42. };
  43. } // namespace Carbon
  44. #endif // EXECUTABLE_SEMANTICS_INTERPRETER_MEMORY_H_