Skip to content

Instantly share code, notes, and snippets.

@kotcrab

kotcrab/Fctx.kt Secret

Created May 27, 2018 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kotcrab/a1e9670aa9503d4264b54ab8dd4bbca5 to your computer and use it in GitHub Desktop.
Save kotcrab/a1e9670aa9503d4264b54ab8dd4bbca5 to your computer and use it in GitHub Desktop.
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