-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsymbolTable.cpp
More file actions
344 lines (270 loc) · 11.8 KB
/
symbolTable.cpp
File metadata and controls
344 lines (270 loc) · 11.8 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#include "symbolTable.hpp"
#include "hw3_output.hpp"
#include "parser.tab.hpp"
#include "ralloc.hpp"
using namespace output;
using std::get;
SymbolTable::SymbolTable() {
this->nestedLoopDepth = 0;
this->currOffset = 0;
this->addScope();
this->addSymbol(NEW(FuncIdC, ("print", "VOID", vector<shared_ptr<IdC>>({NEW(IdC, ("msg", "STRING"))}), true)));
this->addSymbol(NEW(FuncIdC, ("printi", "VOID", vector<shared_ptr<IdC>>({NEW(IdC, ("i", "INT"))}), true)));
this->addSymbol(NEW(FuncIdC, ("error_division_by_zero", "VOID", vector<shared_ptr<IdC>>({}), true)));
// Emit print functions' implementation
auto &buffer = CodeBuffer::instance();
buffer.emitGlobal("declare i32 @printf(i8*, ...)");
buffer.emitGlobal("declare void @exit(i32)");
buffer.emitGlobal("@.int_specifier = constant [4 x i8] c\"%d\\0A\\00\"");
buffer.emitGlobal("@.str_specifier = constant [4 x i8] c\"%s\\0A\\00\"");
buffer.emitGlobal("@.error_div_zero_msg = constant [23 x i8] c\"Error division by zero\\00\"");
buffer.emitGlobal("");
buffer.emitGlobal("define void @printi(i32) {");
buffer.emitGlobal("\t%spec_ptr = getelementptr [4 x i8], [4 x i8]* @.int_specifier, i32 0, i32 0");
buffer.emitGlobal("\tcall i32 (i8*, ...) @printf(i8* %spec_ptr, i32 %0)");
buffer.emitGlobal("\tret void");
buffer.emitGlobal("}");
buffer.emitGlobal("");
buffer.emitGlobal("define void @print(i8*) {");
buffer.emitGlobal("\t%spec_ptr = getelementptr [4 x i8], [4 x i8]* @.str_specifier, i32 0, i32 0");
buffer.emitGlobal("\tcall i32 (i8*, ...) @printf(i8* %spec_ptr, i8* %0)");
buffer.emitGlobal("\tret void");
buffer.emitGlobal("}");
buffer.emitGlobal("");
buffer.emitGlobal("define void @error_division_by_zero() {");
buffer.emitGlobal("\t%spec_ptr = getelementptr [23 x i8], [23 x i8]* @.error_div_zero_msg, i32 0, i32 0");
buffer.emitGlobal("\tcall void (i8*) @print(i8* %spec_ptr)");
buffer.emitGlobal("\tcall void (i32) @exit(i32 0)");
buffer.emitGlobal("\tret void");
buffer.emitGlobal("}");
buffer.emitGlobal("");
}
SymbolTable::~SymbolTable() {}
void SymbolTable::addScope(int funcArgCount) {
if (not((funcArgCount >= 0 and this->scopeStartOffsets.size() == 1) or (this->scopeStartOffsets.size() > 1 and funcArgCount == 0) or this->scopeStartOffsets.size() == 0)) {
throw Exception("Code error. We should only add a scope of a function when we are in the global scope");
}
this->scopeSymbols.push_back(vector<string>());
this->scopeStartOffsets.push_back(this->currOffset);
}
void SymbolTable::removeScope() {
// endScope();
string funcTypeStr;
shared_ptr<FuncIdC> funcId;
vector<string> argTypes;
// If we are going back into the global scope
if (this->scopeSymbols.size() == 2) {
this->currOffset = 0;
// For each string in the last scope, remove it from the symbol table
Offset offset = -1;
for (int i = this->formals.size() - 1; i >= 0; i--) {
printID(this->formals[i], offset--, this->symTbl[this->formals[i]]->getType());
this->symTbl.erase(this->formals[i]);
}
this->formals.clear();
} else {
this->currOffset -= this->scopeSymbols.back().size();
}
Offset offset = this->scopeStartOffsets.back();
for (string s : this->scopeSymbols.back()) {
if ((funcId = DC(FuncIdC, this->symTbl[s])) != nullptr) {
funcTypeStr = makeFunctionType(funcId->getType(), funcId->getArgTypes());
printID(s, offset, funcTypeStr);
} else {
printID(s, offset++, this->symTbl[s]->getType());
}
this->symTbl.erase(s);
}
scopeSymbols.pop_back();
scopeStartOffsets.pop_back();
}
void SymbolTable::addFormal(shared_ptr<IdC> type) {
if (type == nullptr) {
throw Exception("Can't add a nullptr formal to the symbol table");
}
if (this->symTbl[type->getName()] != nullptr) {
errorDef(yylineno, type->getName());
}
this->formals.push_back(type->getName());
this->symTbl[type->getName()] = type;
}
void SymbolTable::addSymbol(shared_ptr<IdC> type) {
const string &name = type->getName();
// Check that the symbol doesn't exist in the scope yet
if (type == nullptr) {
throw Exception("Can't add a nullptr symbol to the symbol table");
}
if (type->getType() == "STRING") {
errorMismatch(yylineno);
}
if (this->symTbl[name] != nullptr) {
errorDef(yylineno, name);
}
this->scopeSymbols.back().push_back(name);
type->setOffset(this->currOffset);
this->symTbl[name] = type;
if (this->scopeStartOffsets.size() > 1) {
this->currOffset++;
}
}
void SymbolTable::addContinue() {
if (this->nestedLoopDepth == 0) {
errorUnexpectedContinue(yylineno);
}
auto &buffer = CodeBuffer::instance();
buffer.emit("; DEBUG: " + to_string(yylineno) + ": adding continue statement for loop in depth " + to_string(this->nestedLoopDepth));
buffer.emit("br label %" + this->loopCondStartLabelStack.back());
}
void SymbolTable::addBreak() {
if (this->nestedLoopDepth == 0) {
errorUnexpectedBreak(yylineno);
}
auto &buffer = CodeBuffer::instance();
buffer.emit("; DEBUG: " + to_string(yylineno) + ": adding break to loop in depth " + to_string(this->nestedLoopDepth));
AddressIndPair instruction = make_pair(buffer.emit("br label @"), FIRST);
this->breakListStack.back().push_back(instruction);
}
void SymbolTable::startLoop(const string &loopCondStartLabel) {
this->nestedLoopDepth++;
this->loopCondStartLabelStack.push_back(loopCondStartLabel);
this->breakListStack.push_back(vector<AddressIndPair>());
}
void SymbolTable::endLoop(AddressList &falseList) {
auto &buffer = CodeBuffer::instance();
string endLoopLabel = buffer.genLabel("endLoopDepth" + to_string(this->nestedLoopDepth));
buffer.bpatch(this->breakListStack.back(), endLoopLabel);
buffer.bpatch(falseList, endLoopLabel);
this->breakListStack.pop_back();
this->loopCondStartLabelStack.pop_back();
this->nestedLoopDepth--;
}
shared_ptr<IdC> SymbolTable::getVarSymbol(const string &name) {
auto symbol = this->symTbl[name];
// Check that the symbol exists in the symbol table
if (symbol == nullptr or DC(FuncIdC, symbol) != nullptr) {
errorUndef(yylineno, name);
}
return symbol;
}
shared_ptr<FuncIdC> SymbolTable::getFuncSymbol(const string &name, bool shouldError) {
auto symbol = this->symTbl[name];
// Check that the symbol exists in the symbol table
shared_ptr<FuncIdC> funcSym = nullptr;
if ((symbol == nullptr or (funcSym = DC(FuncIdC, symbol)) == nullptr) and shouldError) {
errorUndefFunc(yylineno, name);
}
return funcSym;
}
void SymbolTable::printSymbolTable() {
Offset offset = 0;
for (auto it = this->symTbl.begin(); it != this->symTbl.end(); ++it) {
printID(it->first, offset++, it->second->getType());
}
}
int SymbolTable::getCurrentScopeDepth() const {
return this->scopeSymbols.size() - 1;
}
// Helper functions
void verifyMainExists(SymbolTable &symbolTable) {
auto token = yylex();
if (token) {
}
auto mainFunc = symbolTable.getFuncSymbol("main", false);
if (mainFunc == nullptr or mainFunc->getType() != "VOID" or mainFunc->getArgTypes().size() != 0) {
errorMainMissing();
}
symbolTable.removeScope();
}
// no need to "try" because we don't have a danger of conflicting types here
void addUninitializedSymbol(SymbolTable &symbolTable, shared_ptr<STypeC> rawSymbol) {
shared_ptr<IdC> symbol = DC(IdC, rawSymbol);
shared_ptr<ExpC> zeroExp = NEW(ExpC, (symbol->getType(), "0"));
symbolTable.addSymbol(symbol);
emitAssign(symbol, zeroExp, symbolTable.stackVariablesPtrReg);
}
void tryAddSymbolWithExp(SymbolTable &symbolTable, shared_ptr<STypeC> rawSymbol,
shared_ptr<STypeC> rawExp) {
shared_ptr<IdC> symbol = DC(IdC, rawSymbol);
shared_ptr<ExpC> exp = DC(ExpC, rawExp);
if (not areStrTypesCompatible(symbol->getType(), exp->getType())) {
errorMismatch(yylineno);
}
symbolTable.addSymbol(symbol); // now offset is set to symbol through shared ptr
emitAssign(symbol, exp, symbolTable.stackVariablesPtrReg);
}
// no need to "try" because we don't have a danger of conflicting types here
void addAutoSymbolWithExp(SymbolTable &symbolTable, shared_ptr<STypeC> rawId,
shared_ptr<STypeC> rawExp) {
string id = STYPE2STD(string, rawId);
shared_ptr<ExpC> exp = DC(ExpC, rawExp);
shared_ptr<IdC> symbol = NEW(IdC, (id, exp->getType()));
symbolTable.addSymbol(symbol); // now offset is set to symbol through shared ptr
emitAssign(symbol, exp, symbolTable.stackVariablesPtrReg);
}
void tryAssignExp(SymbolTable &symbolTable, shared_ptr<STypeC> rawId, shared_ptr<STypeC> rawExp) {
string id = STYPE2STD(string, rawId);
shared_ptr<IdC> symbol = symbolTable.getVarSymbol(id);
shared_ptr<ExpC> exp = DC(ExpC, rawExp);
string symbolType = symbol->getType();
string expType = exp->getType();
if (not areStrTypesCompatible(symbolType, expType)) {
errorMismatch(yylineno);
}
emitAssign(symbol, exp, symbolTable.stackVariablesPtrReg);
}
void emitAssign(shared_ptr<IdC> symbol, shared_ptr<ExpC> exp, string stackVariablesPtrReg) {
CodeBuffer &codeBuffer = CodeBuffer::instance();
Ralloc &ralloc = Ralloc::instance();
string llvmLvalType = typeNameToLlvmType(symbol->getType());
string llvmRvalType = typeNameToLlvmType(exp->getType());
string offsetReg = ralloc.getNextReg("offsetEmitAssign_" + symbol->getName());
string idAddrReg = ralloc.getNextReg("idAddrEmitAssign_" + symbol->getName());
string expReg = exp->getRegOrImmResult();
codeBuffer.emit(offsetReg + " = add i32 0, " + std::to_string(symbol->getOffset()));
codeBuffer.emit(idAddrReg + " = getelementptr i32, i32* " + stackVariablesPtrReg + ", i32 " + offsetReg);
string idAddrRegCorrectSize = idAddrReg;
// Check and zext if needed
if (llvmRvalType != llvmLvalType) {
string zextExpReg = ralloc.getNextReg("zextEmitAssign_" + symbol->getName());
codeBuffer.emit(zextExpReg + " = zext " + llvmRvalType + " " + expReg + " to " + llvmLvalType);
expReg = zextExpReg;
}
if (llvmLvalType != "i32") {
idAddrRegCorrectSize = ralloc.getNextReg("idAddrCorrect_" + symbol->getName());
codeBuffer.emit(idAddrRegCorrectSize + " = bitcast i32* " + idAddrReg + " to " + llvmLvalType + "*");
}
codeBuffer.emit("store " + llvmLvalType + " " + expReg + ", " + llvmLvalType + "* " + idAddrRegCorrectSize);
}
void handleReturn(shared_ptr<RetTypeNameC> retType) {
if (retType == nullptr) {
throw Exception("This should be impossible. Syntax error wise");
} else if (retType->getTypeName() != "VOID") {
errorMismatch(yylineno);
}
emitReturn(retType, nullptr);
}
void handleReturnExp(shared_ptr<RetTypeNameC> retType, shared_ptr<STypeC> rawExp) {
shared_ptr<ExpC> exp = DC(ExpC, rawExp);
exp->getRegOrImmResult();
if (retType == nullptr) {
throw Exception("This should be impossible. Syntax error wise");
} else if (not areStrTypesCompatible(retType->getTypeName(), exp->getType())) {
errorMismatch(yylineno);
}
emitReturn(retType, exp);
}
void emitReturn(shared_ptr<RetTypeNameC> retType, shared_ptr<ExpC> exp) {
CodeBuffer &codeBuffer = CodeBuffer::instance();
if (exp == nullptr) {
if (retType->getTypeName() != "VOID") {
errorMismatch(yylineno);
}
codeBuffer.emit("ret void");
return;
}
if (retType->getTypeName() != exp->getType()) {
throw Exception("this should be impossible. wrong function usage.");
}
string llvmType = typeNameToLlvmType(exp->getType());
codeBuffer.emit("ret " + llvmType + " " + exp->getRegOrImmResult());
}