Skip to content

Commit

Permalink
refactor(codegen): use integer literal without allocating a register …
Browse files Browse the repository at this point in the history
…if possible
  • Loading branch information
MilkeeyCat committed Sep 28, 2024
1 parent 3358faf commit 16c1811
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 24 deletions.
14 changes: 4 additions & 10 deletions src/archs/amd64/amd64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,24 +287,18 @@ impl Architecture for Amd64 {

//NOTE: if mafs doesn't works, probably because of this xd
fn div(&mut self, dest: &Destination, src: &Source, signed: bool) -> Result<(), ArchError> {
self.mov(
&dest.to_owned().into(),
&Destination::Register(operands::Register {
register: self.rax,
size: WORD_SIZE,
}),
signed,
)?;
self.mov(&dest.to_owned().into(), &self.rax.dest(WORD_SIZE), signed)?;
self.mov(src, dest, signed)?;
self.buf.push_str(&formatdoc!(
"
\tcqo
\tidiv {src}
\tidiv {dest}
",
));
self.mov(
&Source::Register(operands::Register {
register: self.rax,
size: src.size().unwrap_or(WORD_SIZE),
size: dest.size(),
}),
dest,
signed,
Expand Down
32 changes: 18 additions & 14 deletions src/codegen/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -411,36 +411,38 @@ impl CodeGen {
} else {
None
};
let tmp = new_dest
let lhs = new_dest
.clone()
.map(|(dest, _)| dest)
.unwrap_or_else(|| dest.clone());

self.expr(*expr.left, Some(tmp.clone()), state)?;
self.expr(*expr.left, Some(lhs.clone()), state)?;

let r = self.arch.alloc()?;
let (src, r) = if let Expr::Lit(lit) = *expr.right {
(Source::Immediate(lit.into()), None)
} else {
let r = self.arch.alloc()?;

self.expr(*expr.right, Some(r.dest(size)), state)?;
self.expr(*expr.right, Some(r.dest(size)), state)?;
(r.source(size), Some(r))
};

match &expr.op {
BinOp::Add => {
self.arch.add(&tmp, &r.source(size));
self.arch.add(&lhs, &src);
}
BinOp::Sub => {
self.arch.sub(&tmp, &r.source(size));
self.arch.sub(&lhs, &src);
}
BinOp::Mul => {
self.arch.mul(&tmp, &r.source(size), signed)?;
self.arch.mul(&lhs, &src, signed)?;
}
BinOp::Div => {
self.arch.div(&tmp, &r.source(size), signed)?;
self.arch.div(&lhs, &src, signed)?;
}
BinOp::BitwiseAnd | BinOp::BitwiseOr => {
self.arch.bitwise(
&tmp,
&r.source(size),
BitwiseOp::try_from(&expr.op).unwrap(),
);
self.arch
.bitwise(&lhs, &src, BitwiseOp::try_from(&expr.op).unwrap());
}
_ => unreachable!(),
};
Expand All @@ -458,7 +460,9 @@ impl CodeGen {
self.arch.free(r)?;
}

self.arch.free(r)?;
if let Some(r) = r {
self.arch.free(r)?;
}
}
}
BinOp::LessThan
Expand Down

0 comments on commit 16c1811

Please sign in to comment.