Create a gist now

Instantly share code, notes, and snippets.

@kotcrab /Fctx.kt Secret
Created May 27, 2018

Embed
What would you like to do?
fun Assembler.preserve(regs: Array<Reg>): FunctionContext {
val ctx = FunctionContext(this, regs)
ctx.preserve()
return ctx
}
class FunctionContext(private val assembler: Assembler, private val regs: Array<Reg>) {
fun byteSize() = regs.size * 4
fun preserve() = with(assembler) {
addi(sp, sp, -regs.size * 4)
regs.forEachIndexed { idx, reg ->
sw(reg, idx * 4, sp)
}
}
fun restore() = with(assembler) {
restoreRegs()
addi(sp, sp, regs.size * 4)
}
fun exit() = with(assembler) {
jr(ra)
nop()
}
fun restoreAndExit() = with(assembler) {
restoreRegs()
jr(ra)
addi(sp, sp, regs.size * 4)
nop()
}
private fun restoreRegs() = with(assembler) {
regs.forEachIndexed { idx, reg ->
lw(reg, idx * 4, sp)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment