-
Notifications
You must be signed in to change notification settings - Fork 0
/
abstract_syntax_tree.cpp
88 lines (76 loc) · 2.6 KB
/
abstract_syntax_tree.cpp
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <llvm-14/llvm/IR/Value.h>
#include <map>
#include <memory>
#include <iostream>
#include <llvm/ADT/APFloat.h>
#include <llvm/ADT/STLExtras.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Type.h>
#include <llvm/IR/Verifier.h>
#include <vector>
#include <algorithm>
#include "abstract_syntax_tree.h"
namespace BallLang {
static std::unique_ptr<llvm::LLVMContext> CONTEXT;
static std::unique_ptr<llvm::Module> MODULE;
static std::unique_ptr<llvm::IRBuilder<>> BUILDER(std::make_unique<llvm::IRBuilder<>>(*CONTEXT));
std::map<std::string, llvm::Value*> namedValues;
ExprAST::~ExprAST() {}
llvm::Value* ExprAST::codegen() const {
return nullptr; // TODO: remove with the implementation of concepts
}
llvm::Value* NumberExprAST::codegen() const {
return llvm::ConstantFP::get(*CONTEXT, llvm::APFloat(this->value));
}
llvm::Value* BinaryExprAST::codegen() const {
llvm::Value* LValue = this->LHS.codegen();
llvm::Value* RValue = this->RHS.codegen();
switch (oper) {
case '+': return BUILDER->CreateFAdd(LValue, RValue);
case '-': return BUILDER->CreateFSub(LValue, RValue);
case '*': return BUILDER->CreateFMul(LValue, RValue);
case '<':
return BUILDER->CreateUIToFP(
BUILDER->CreateFCmpULT(LValue, RValue),
llvm::Type::getDoubleTy(*CONTEXT),
"booltmp"
);
default: std::cout << "INVALID OPERATOR: " << oper << std::endl;
}
return nullptr;
}
llvm::Value* CallExprAST::codegen() const {
llvm::Function* funcCallee = MODULE->getFunction(this->callee);
if (!funcCallee) {
std::cout << "There is no play called ~" << callee << "~ in the playbook." << std::endl;
return nullptr;
}
if (funcCallee->arg_size() != this->args.size()) {
std::cout << "Incorrect number of players for the play" << std::endl;
return nullptr;
}
std::vector<llvm::Value*> argValues{};
std::transform(this->args.begin(), this->args.end(), argValues.begin(),
[](const ExprAST& expr) { return expr.codegen(); }
);
return BUILDER->CreateCall(funcCallee, argValues, "calltmp");
}
llvm::Value* PrototypeAST::codegen() const {
return nullptr;
}
llvm::Value* FunctionAST::codegen() const {
return nullptr;
}
llvm::Value* VariableExprAST::codegen() const {
const auto& vIter = namedValues.find(name);
if (vIter != namedValues.end())
return vIter->second;
else
return nullptr;
}
};