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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
|
#include "cps/CodeGen.h"
#include "cps/ArrayHandler.h"
#include "cps/FileHandler.h"
#include "cps/MemoryHandler.h"
#include "cps/ExceptionHandler.h"
#include "Builtins.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Verifier.h"
#include <cstdarg>
#include <cstdio>
using namespace llvm;
using namespace cps;
using namespace cps::detail;
CodeGen::~CodeGen() = default;
bool CodeGen::isBuiltinName(const std::string &Name) {
return findBuiltin(Name) != nullptr;
}
void CodeGen::reportError(const char *Fmt, ...) {
va_list Args;
va_start(Args, Fmt);
fprintf(stderr, "error: ");
vfprintf(stderr, Fmt, Args);
if (DiagnosticLine) fprintf(stderr, " at line %d", DiagnosticLine);
fprintf(stderr, "\n");
va_end(Args);
HadError = true;
}
CodeGen::CodeGen() {
TheContext = std::make_unique<LLVMContext>();
TheModule = std::make_unique<Module>("cps_module", *TheContext);
Builder = std::make_unique<IRBuilder<>>(*TheContext);
Types = std::make_unique<TypeSystem>(*TheContext);
Exceptions = std::make_unique<ExceptionHandler>(*TheContext, *Builder, *TheModule);
RuntimeChecker = std::make_unique<RuntimeCheck>(*TheModule, *TheContext, *Builder, *Exceptions);
Arrays = std::make_unique<ArrayHandler>(*TheContext,
*Builder,
*TheModule,
Symbols,
*Types,
*RuntimeChecker);
FuncGen = std::make_unique<FunctionGen>(*TheContext,
*TheModule,
*Builder,
*Types,
*Exceptions,
Symbols,
HadError, DiagnosticLine);
ArithHandler = std::make_unique<ArithmeticHandler>(*TheContext, *Builder, HadError,
*RuntimeChecker);
StrHandler = std::make_unique<StringHandler>(*TheContext, *Builder, *TheModule);
StrConvHandler = std::make_unique<StringConversionHandler>(*TheContext, *Builder, *TheModule);
Files = std::make_unique<FileHandler>(*TheContext, *Builder, *TheModule, *RuntimeChecker,
*Exceptions);
Memory = std::make_unique<MemoryHandler>(*TheContext, *Builder, *TheModule, *Types,
*RuntimeChecker, *Exceptions);
// Array parameters are bound into ArrayHandler through this inversion so
// FunctionGen never sees the array subsystem.
FuncGen->setArrayParamBinder(
[this](const ParamDecl &P, Value *DataPtr,
const std::vector<Value*> &LBs, const std::vector<Value*> &UBs) {
Arrays->bindArrayParameter(P.Name, P.TypeName, DataPtr, LBs, UBs,
/*MakeCopy=*/P.Mode == PassMode::ByVal, *this);
});
FuncGen->setCopyRegistrar([this](Value *Addr, const std::string &TypeName, int Line) {
activateStackObject(registerStackObject(Addr, TypeName, Line, false, true));
});
SetupExternalFunctions();
}
void CodeGen::SetupExternalFunctions() {
std::vector<Type*> PrintfArgs;
PrintfArgs.push_back(PointerType::getUnqual(*TheContext));
FunctionType *PrintfType = FunctionType::get(Type::getInt32Ty(*TheContext), PrintfArgs, true);
PrintfFunc = TheModule->getOrInsertFunction("printf", PrintfType);
FunctionType *ScanfType = FunctionType::get(Type::getInt32Ty(*TheContext), PrintfArgs, true);
ScanfFunc = TheModule->getOrInsertFunction("scanf", ScanfType);
FunctionType *MallocType = FunctionType::get(PointerType::getUnqual(*TheContext),
{Type::getInt64Ty(*TheContext)},
false);
MallocFunc = TheModule->getOrInsertFunction("malloc", MallocType);
PrintfFormatStr = Builder->CreateGlobalString("%lld\n", "fmt_nl", 0, TheModule.get());
PrintfFloatFormatStr = Builder->CreateGlobalString("%f\n", "fmt_flt", 0, TheModule.get());
PrintfStringFormatStr = Builder->CreateGlobalString("%s\n", "fmt_str", 0, TheModule.get());
PrintfCharFormatStr = Builder->CreateGlobalString("%c\n", "fmt_chr", 0, TheModule.get());
ScanfFormatStr = Builder->CreateGlobalString("%lld", "fmt_in", 0, TheModule.get());
ScanfFloatFormatStr = Builder->CreateGlobalString("%lf", "fmt_in_flt", 0, TheModule.get());
ScanfStringFormatStr = Builder->CreateGlobalString("%s", "fmt_in_str", 0, TheModule.get());
TrueStr = Builder->CreateGlobalString("TRUE", "str_true", 0, TheModule.get());
FalseStr = Builder->CreateGlobalString("FALSE", "str_false", 0, TheModule.get());
EmptyStringStr = Builder->CreateGlobalString("", "str_empty", 0, TheModule.get());
Arrays->setupExternalFunctions();
}
AllocaInst *CodeGen::CreateEntryBlockAlloca(Function *TheFunction, const std::string &VarName) {
return CreateEntryBlockAlloca(TheFunction, Type::getInt64Ty(*TheContext), VarName);
}
AllocaInst *CodeGen::CreateEntryBlockAlloca(Function *TheFunction,
Type *AllocType,
const std::string &VarName) {
IRBuilder<> TmpB(&TheFunction->getEntryBlock(), TheFunction->getEntryBlock().begin());
return TmpB.CreateAlloca(AllocType, nullptr, VarName);
}
void CodeGen::registerSymbol(const std::string &Name,
Value *Storage,
const std::string &TypeName,
bool IsArray) {
Symbols[Name] = {Storage, TypeName, IsArray, nullptr, ConstantScopes.back().ID};
}
const SymbolInfo *CodeGen::getSymbolInfo(const std::string &Name) const {
auto It = Symbols.find(Name);
if (It == Symbols.end()) {
return nullptr;
}
return &It->second;
}
// A whole-array variable reference evaluates to the raw buffer pointer, which
// the pointer->STRING coercion would accept unchanged; file-statement operands
// must reject it explicitly or garbage gets treated as a C string.
bool CodeGen::isWholeArrayVar(ExprAST *Expr) const {
auto *Var = dynamic_cast<VariableExprAST*>(Expr);
if (!Var) return false;
const SymbolInfo *Info = getSymbolInfo(Var->getName());
return Info && Info->IsArray;
}
const TypeInfo *CodeGen::resolveType(const std::string &TypeName) const {
return Types->resolve(TypeName);
}
void CodeGen::compile(const std::vector<std::unique_ptr<StmtAST>> &Statements) {
FunctionType *FT = FunctionType::get(Type::getInt32Ty(*TheContext), false);
Function *F = Function::Create(FT, Function::ExternalLinkage, "main", TheModule.get());
BasicBlock *BB = BasicBlock::Create(*TheContext, "entry", F);
Builder->SetInsertPoint(BB);
Exceptions->prepareFunction(F);
BasicBlock *UnhandledBB = BasicBlock::Create(*TheContext, "unhandled_exception", F);
Exceptions->pushHandler(UnhandledBB);
// User types first: prototypes may name them in parameters/returns.
runTypePrePass(Statements);
// Pre-register every top-level FUNCTION/PROCEDURE prototype so calls may
// precede definitions.
for (const auto &Stmt : Statements) {
SaveAndRestore<int> Location(DiagnosticLine, Stmt->getLine());
if (auto *FuncDef = dynamic_cast<FunctionDefAST*>(Stmt.get())) {
FuncGen->emitPrototype(FuncDef->getProto());
}
}
for (const auto &[Class, Methods] : ClassMethods) {
for (const auto &[Name, Method] : Methods) {
SaveAndRestore<int> Location(DiagnosticLine, Method->getLine());
FuncGen->emitPrototype(Method->getProto());
}
}
for (const auto &Stmt : Statements) {
SaveAndRestore<int> Location(DiagnosticLine, Stmt->getLine());
emitStmt(Stmt.get());
}
if (!Builder->GetInsertBlock()->hasTerminator()) {
Exceptions->recordExit(Builder->CreateRet(ConstantInt::get(*TheContext, APInt(32, 0))));
}
finishStackObjects(F);
auto *Exception = Exceptions->popHandler();
Builder->SetInsertPoint(UnhandledBB);
Exceptions->beginCatch(Exception);
Exceptions->endCatch();
Value *Msg = Builder->CreateGlobalString("Unhandled exception. Program terminated.\n",
"err_unhandled", 0, TheModule.get());
Builder->CreateCall(PrintfFunc, {Msg});
Builder->CreateRet(ConstantInt::get(Type::getInt32Ty(*TheContext), 1));
if (verifyModule(*TheModule, &errs())) {
errs() << "fatal error: LLVM module verification failed\n";
HadError = true;
}
}
void CodeGen::print(raw_ostream &Output) {
TheModule->print(Output, nullptr);
}
// Collects the arguments for a call to a user FUNCTION/PROCEDURE, dispatching
// on the *declared* signature: BYREF parameters take the variable's alloca,
// BYVAL parameters are evaluated and coerced to the declared parameter type.
bool CodeGen::marshalCallArgs(const std::string &Callee,
const std::vector<std::unique_ptr<ExprAST>> &ArgExprs,
int Line,
std::vector<Value*> &Out) {
SaveAndRestore<int> Location(DiagnosticLine, Line ? Line : DiagnosticLine);
const FuncSig *Sig = FuncGen->getSignature(Callee);
if (!Sig) {
reportError("Call to undefined function %s", Callee.c_str());
return false;
}
if (ArgExprs.size() != Sig->Params.size()) {
reportError("Incorrect # arguments passed to %s", Callee.c_str());
return false;
}
for (size_t i = 0; i < ArgExprs.size(); ++i) {
const ParamSig &P = Sig->Params[i];
const std::string &TypeName = P.TypeName;
bool IsByRef = P.IsByRef;
ExprAST *ArgExpr = ArgExprs[i].get();
if (P.IsArray) {
if (!Arrays->emitArrayArgument(ArgExpr, P.TypeName, P.Rank, P.DeclaredBounds,
Callee, Line, *this, Out)) {
return false;
}
continue;
}
// A whole-array argument against a scalar parameter is always a user
// error (and would smash the data pointer if let through).
if (auto *Var = dynamic_cast<VariableExprAST*>(ArgExpr)) {
const SymbolInfo *Info = getSymbolInfo(Var->getName());
if (Info && Info->IsArray) {
reportError("Cannot pass whole array %s to %s; the parameter is not an array (declare it ARRAY OF %s)",
Var->getName().c_str(), Callee.c_str(), TypeName.c_str());
return false;
}
}
if (IsByRef) {
auto *Var = dynamic_cast<VariableExprAST*>(ArgExpr);
if (!Var) {
reportError("BYREF argument to %s must be a variable", Callee.c_str());
return false;
}
const SymbolInfo *Info = getSymbolInfo(Var->getName());
if (!Info) {
reportError("Unknown variable %s in BYREF call", Var->getName().c_str());
return false;
}
if (!requireWritable(*Info, Var->getName())) return false;
// BYREF aliases the storage, so the types must match exactly.
if (!Types->sameType(Info->TypeName, TypeName)) {
reportError("BYREF argument %s to %s must be of type %s (got %s)",
Var->getName().c_str(), Callee.c_str(),
TypeName.c_str(), Info->TypeName.c_str());
return false;
}
Out.push_back(symbolAddress(*Info));
} else {
Value *V = emitCoercedExpr(ArgExpr, resolveType(TypeName));
if (!V) return false;
Out.push_back(V);
}
}
return true;
}
|