aboutsummaryrefslogtreecommitdiff
path: root/include/cps/MemoryHandler.h
blob: 2768ebe65c8019c2c98ca846d7497e03521ad49d (plain)
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

#pragma once
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"

namespace cps {

class TypeSystem;
class RuntimeCheck;
class ExceptionHandler;

// Explicit memory builtins and keyword NEW own entries in this allocation list.
// Internal STRING/ARRAY storage retains its existing lifetime rules.
class MemoryHandler {
    llvm::LLVMContext &Context;
    llvm::IRBuilder<> &Builder;
    llvm::Module &Module;
    TypeSystem &Types;
    RuntimeCheck &Checker;
    ExceptionHandler &Exceptions;
    llvm::IntegerType *SizeTy = nullptr;
    llvm::StructType *NodeTy = nullptr;
    llvm::GlobalVariable *Head = nullptr;
    llvm::FunctionCallee Malloc, Free, Realloc;
    llvm::Function *AllocateFn = nullptr, *ReleaseFn = nullptr, *FindFn = nullptr,
                   *ResizeFn = nullptr;
    llvm::Value *AllocationError = nullptr, *TrackingError = nullptr, *InvalidAddress = nullptr;

    void ensureRuntime();
    llvm::Function *createHelper(const char *Name, llvm::ArrayRef<llvm::Type *> Args);
    void buildFind();
    void buildAllocate();
    void buildRelease();
    void buildResize();

public:
    MemoryHandler(llvm::LLVMContext &C, llvm::IRBuilder<> &B, llvm::Module &M,
                  TypeSystem &TS, RuntimeCheck &RC, ExceptionHandler &EH)
        : Context(C), Builder(B), Module(M), Types(TS), Checker(RC), Exceptions(EH) {}

    llvm::Value *emitAllocate(llvm::Value *Size, int Line);
    llvm::Value *emitRelease(llvm::Value *Address, int Line);
    llvm::Value *emitResize(llvm::Value *Address, llvm::Value *Size, int Line);
};

} // namespace cps