@@ -8,8 +8,14 @@ fun irExprToLow(expr: IRExpr): List<Instruction> {
88
99 fun traverse (expr : IRExpr ): Location {
1010 return when (expr) {
11- is IRIntLiteral -> ImmediateVal (expr.lit)
12- is IRBoolLiteral -> ImmediateVal (if (expr.lit) 1 else 0 )
11+ is IRIntLiteral -> {
12+ instructions.add(MoveInstruction (ImmediateVal (expr.lit), Register .r10()))
13+ Register .r10()
14+ }
15+ is IRBoolLiteral -> {
16+ instructions.add(MoveInstruction (ImmediateVal (if (expr.lit) 1 else 0 ), Register .r10()))
17+ Register .r10()
18+ }
1319 is IRMethodCallExpr -> {
1420 val argLocations = expr.argList.map { traverse(it) }
1521 argLocations.forEach { instructions.add(PushInstruction (it)) }
@@ -217,4 +223,69 @@ fun irStatementToLow(statement: IRStatement): List<Instruction> {
217223 }
218224
219225 return instructions
226+ }
227+
228+ fun irMethodToLow (method : IRMethodDeclaration ): List <Block > {
229+ val blocks = mutableListOf<Block >()
230+ blocks.add(Block (method.name, mutableListOf ()))
231+
232+ var falseBlockCount = 0
233+ var ifEndCount = 0
234+
235+ fun convert (ir : IR , block : Block ): Block {
236+ return when (ir) {
237+ is IRStatement -> {
238+ when (ir) {
239+ is IRAssignStatement , is IRInvokeStatement -> {
240+ val instructions = irStatementToLow(ir)
241+ block.instructions.addAll(instructions)
242+ block
243+ }
244+ is IRBreakStatement -> TODO ()
245+ is IRContinueStatement -> TODO ()
246+ is IRIfStatement -> {
247+ val conditionInstructions = irExprToLow(ir.condition)
248+ block.instructions.addAll(conditionInstructions)
249+ val ansLoc = (conditionInstructions.last() as MoveInstruction ).dest
250+ block.instructions.add(MoveInstruction (ansLoc, Register .r10()))
251+ block.instructions.add(CmpInstruction (Register .r10(), ImmediateVal (1 )))
252+
253+ falseBlockCount++
254+ ifEndCount++
255+ val falseBlock = Block (" lab_false_$falseBlockCount " , mutableListOf ())
256+ val ifEndBlock = Block (" lab_if_end_$ifEndCount " , mutableListOf ())
257+
258+ block.instructions.add(JumpInstruction (AsmJumpOp .JNE , falseBlock.label!! ))
259+ val newBlock = convert(ir.ifBlock, block)
260+ newBlock.instructions.add(JumpInstruction (AsmJumpOp .JMP , ifEndBlock.label!! ))
261+
262+ blocks.add(falseBlock)
263+ if (ir.elseBlock != null ) {
264+ convert(ir.elseBlock, falseBlock)
265+ }
266+
267+ blocks.add(ifEndBlock)
268+ ifEndBlock
269+ }
270+ is IRForStatement -> TODO ()
271+ is IRReturnStatement -> TODO ()
272+ is IRBlockStatement -> TODO ()
273+ }
274+ }
275+ is IRBlock -> {
276+ var currBlock = block
277+ for (memberDeclaration in ir.fieldDeclarations) {
278+ currBlock.instructions.add(PushInstruction (ImmediateVal (0 )))
279+ }
280+ for (statement in ir.statements) {
281+ currBlock = convert(statement, currBlock)
282+ }
283+ currBlock
284+ }
285+ else -> throw IllegalStateException (" cannot call this method on this IR" )
286+ }
287+ }
288+
289+ convert(method.block, blocks[0 ])
290+ return blocks
220291}
0 commit comments