-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodegen.go
350 lines (288 loc) · 8.73 KB
/
codegen.go
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
345
346
347
348
349
350
package main
import (
"fmt"
"os"
"github.com/ajsnow/llvm"
)
var (
rootModule = llvm.NewModule("root")
rootFuncPassMgr = llvm.NewFunctionPassManagerForModule(rootModule)
nativeInitErr = llvm.InitializeNativeTarget()
execEngine, jitInitErr = llvm.NewJITCompiler(rootModule, 0)
builder = llvm.NewBuilder()
namedVals = map[string]llvm.Value{}
)
func init() {
if nativeInitErr != nil {
fmt.Fprintln(os.Stderr, nativeInitErr)
os.Exit(-1)
}
if jitInitErr != nil {
fmt.Fprintln(os.Stderr, jitInitErr)
os.Exit(-1)
}
}
func Optimize() {
rootFuncPassMgr.Add(execEngine.TargetData())
rootFuncPassMgr.AddPromoteMemoryToRegisterPass()
rootFuncPassMgr.AddInstructionCombiningPass()
rootFuncPassMgr.AddReassociatePass()
rootFuncPassMgr.AddGVNPass()
rootFuncPassMgr.AddCFGSimplificationPass()
rootFuncPassMgr.InitializeFunc()
}
func createEntryBlockAlloca(f llvm.Value, name string) llvm.Value {
var tmpB = llvm.NewBuilder()
tmpB.SetInsertPoint(f.EntryBasicBlock(), f.EntryBasicBlock().FirstInstruction())
return tmpB.CreateAlloca(llvm.DoubleType(), name)
}
func (n *fnPrototypeNode) createArgAlloca(f llvm.Value) {
args := f.Params()
for i := range args {
alloca := createEntryBlockAlloca(f, n.args[i])
builder.CreateStore(args[i], alloca)
namedVals[n.args[i]] = alloca
}
}
func (n *numberNode) codegen() llvm.Value {
return llvm.ConstFloat(llvm.DoubleType(), n.val)
}
func (n *variableNode) codegen() llvm.Value {
v := namedVals[n.name]
if v.IsNil() {
return ErrorV("unknown variable name")
}
return builder.CreateLoad(v, n.name)
}
func (n *ifNode) codegen() llvm.Value {
ifv := n.ifN.codegen()
if ifv.IsNil() {
return ErrorV("code generation failed for if expression")
}
ifv = builder.CreateFCmp(llvm.FloatONE, ifv, llvm.ConstFloat(llvm.DoubleType(), 0), "ifcond")
parentFunc := builder.GetInsertBlock().Parent()
thenBlk := llvm.AddBasicBlock(parentFunc, "then")
elseBlk := llvm.AddBasicBlock(parentFunc, "else")
mergeBlk := llvm.AddBasicBlock(parentFunc, "merge")
builder.CreateCondBr(ifv, thenBlk, elseBlk)
// generate 'then' block
builder.SetInsertPointAtEnd(thenBlk)
thenv := n.thenN.codegen()
if thenv.IsNil() {
return ErrorV("code generation failed for then expression")
}
builder.CreateBr(mergeBlk)
// Codegen of 'Then' can change the current block, update ThenBB for the PHI.
thenBlk = builder.GetInsertBlock()
// generate 'else' block
// C++ unknown eq: TheFunction->getBasicBlockList().push_back(ElseBB);
builder.SetInsertPointAtEnd(elseBlk)
elsev := n.elseN.codegen()
if elsev.IsNil() {
return ErrorV("code generation failed for else expression")
}
builder.CreateBr(mergeBlk)
elseBlk = builder.GetInsertBlock()
builder.SetInsertPointAtEnd(mergeBlk)
PhiNode := builder.CreatePHI(llvm.DoubleType(), "iftmp")
PhiNode.AddIncoming([]llvm.Value{thenv}, []llvm.BasicBlock{thenBlk})
PhiNode.AddIncoming([]llvm.Value{elsev}, []llvm.BasicBlock{elseBlk})
return PhiNode
}
func (n *forNode) codegen() llvm.Value {
startVal := n.start.codegen()
if startVal.IsNil() {
return ErrorV("code generation failed for start expression")
}
parentFunc := builder.GetInsertBlock().Parent()
alloca := createEntryBlockAlloca(parentFunc, n.counter)
builder.CreateStore(startVal, alloca)
loopBlk := llvm.AddBasicBlock(parentFunc, "loop")
builder.CreateBr(loopBlk)
builder.SetInsertPointAtEnd(loopBlk)
// save higher levels' variables if we have the same name
oldVal := namedVals[n.counter]
namedVals[n.counter] = alloca
if n.body.codegen().IsNil() {
return ErrorV("code generation failed for body expression")
}
var stepVal llvm.Value
if n.step != nil {
stepVal = n.step.codegen()
if stepVal.IsNil() {
return llvm.ConstNull(llvm.DoubleType())
}
} else {
stepVal = llvm.ConstFloat(llvm.DoubleType(), 1)
}
// evaluate end condition before increment
endVal := n.test.codegen()
if endVal.IsNil() {
return endVal
}
curVar := builder.CreateLoad(alloca, n.counter)
nextVar := builder.CreateFAdd(curVar, stepVal, "nextvar")
builder.CreateStore(nextVar, alloca)
endVal = builder.CreateFCmp(llvm.FloatONE, endVal, llvm.ConstFloat(llvm.DoubleType(), 0), "loopcond")
afterBlk := llvm.AddBasicBlock(parentFunc, "afterloop")
builder.CreateCondBr(endVal, loopBlk, afterBlk)
builder.SetInsertPointAtEnd(afterBlk)
if !oldVal.IsNil() {
namedVals[n.counter] = oldVal
} else {
delete(namedVals, n.counter)
}
return llvm.ConstFloat(llvm.DoubleType(), 0)
}
func (n *unaryNode) codegen() llvm.Value {
operandValue := n.operand.codegen()
if operandValue.IsNil() {
return ErrorV("nil operand")
}
f := rootModule.NamedFunction("unary" + string(n.name))
if f.IsNil() {
return ErrorV("unknown unary operator")
}
return builder.CreateCall(f, []llvm.Value{operandValue}, "unop")
}
func (n *variableExprNode) codegen() llvm.Value {
var oldvars = []llvm.Value{}
f := builder.GetInsertBlock().Parent()
for i := range n.vars {
name := n.vars[i].name
node := n.vars[i].node
var val llvm.Value
if node != nil {
val = node.codegen()
if val.IsNil() {
return val // nil
}
} else { // if no initialized value set to 0
val = llvm.ConstFloat(llvm.DoubleType(), 0)
}
alloca := createEntryBlockAlloca(f, name)
builder.CreateStore(val, alloca)
oldvars = append(oldvars, namedVals[name])
namedVals[name] = alloca
}
// evaluate body now that vars are in scope
bodyVal := n.body.codegen()
if bodyVal.IsNil() {
return ErrorV("body returns nil") // nil
}
// pop old values
for i := range n.vars {
namedVals[n.vars[i].name] = oldvars[i]
}
return bodyVal
}
func (n *fnCallNode) codegen() llvm.Value {
callee := rootModule.NamedFunction(n.callee)
if callee.IsNil() {
return ErrorV("unknown function referenced")
}
if callee.ParamsCount() != len(n.args) {
return ErrorV("incorrect number of arguments passed")
}
args := []llvm.Value{}
for _, arg := range n.args {
args = append(args, arg.codegen())
if args[len(args)-1].IsNil() {
return ErrorV("an argument was nil")
}
}
return builder.CreateCall(callee, args, "calltmp")
}
func (n *binaryNode) codegen() llvm.Value {
// Special case '=' because we don't emit the LHS as an expression
if n.op == "=" {
l, ok := n.left.(*variableNode)
if !ok {
return ErrorV("destination of '=' must be a variable")
}
// get value
val := n.right.codegen()
if val.IsNil() {
return ErrorV("cannot assign null value")
}
// lookup location of variable from name
p := namedVals[l.name]
// store
builder.CreateStore(val, p)
return val
}
l := n.left.codegen()
r := n.right.codegen()
if l.IsNil() || r.IsNil() {
return ErrorV("operand was nil")
}
switch n.op {
case "+":
return builder.CreateFAdd(l, r, "addtmp")
case "-":
return builder.CreateFSub(l, r, "subtmp")
case "*":
return builder.CreateFMul(l, r, "multmp")
case "/":
return builder.CreateFDiv(l, r, "divtmp")
case "<":
l = builder.CreateFCmp(llvm.FloatOLT, l, r, "cmptmp")
return builder.CreateUIToFP(l, llvm.DoubleType(), "booltmp")
default:
function := rootModule.NamedFunction("binary" + string(n.op))
if function.IsNil() {
return ErrorV("invalid binary operator")
}
return builder.CreateCall(function, []llvm.Value{l, r}, "binop")
}
}
func (n *fnPrototypeNode) codegen() llvm.Value {
funcArgs := []llvm.Type{}
for _ = range n.args {
funcArgs = append(funcArgs, llvm.DoubleType())
}
funcType := llvm.FunctionType(llvm.DoubleType(), funcArgs, false)
function := llvm.AddFunction(rootModule, n.name, funcType)
if function.Name() != n.name {
function.EraseFromParentAsFunction()
function = rootModule.NamedFunction(n.name)
}
if function.BasicBlocksCount() != 0 {
return ErrorV("redefinition of function: " + n.name)
}
if function.ParamsCount() != len(n.args) {
return ErrorV("redefinition of function with different number of args")
}
for i, param := range function.Params() {
param.SetName(n.args[i])
namedVals[n.args[i]] = param
}
return function
}
func (n *functionNode) codegen() llvm.Value {
namedVals = make(map[string]llvm.Value)
p := n.proto.(*fnPrototypeNode)
theFunction := n.proto.codegen()
if theFunction.IsNil() {
return ErrorV("prototype")
}
// if p.isOperator && len(p.args) == 2 {
// opChar, _ := utf8.DecodeLastRuneInString(p.name)
// binaryOpPrecedence[opChar] = p.precedence
// }
block := llvm.AddBasicBlock(theFunction, "entry")
builder.SetInsertPointAtEnd(block)
p.createArgAlloca(theFunction)
retVal := n.body.codegen()
if retVal.IsNil() {
theFunction.EraseFromParentAsFunction()
return ErrorV("function body")
}
builder.CreateRet(retVal)
if llvm.VerifyFunction(theFunction, llvm.PrintMessageAction) != nil {
theFunction.EraseFromParentAsFunction()
return ErrorV("function verifiction failed")
}
rootFuncPassMgr.RunFunc(theFunction)
return theFunction
}