use std::fmt;
use std::fmt::Formatter;
use id_arena::{Arena, Id};
use crate::core;
pub type BasicBlockId = Id<BasicBlock>;
pub struct BasicBlock {
label: core::llvm_string::LLVMString,
pub predecessor: Option<BasicBlockId>,
pub kind: BasicBlockKind,
instructions: Vec<core::instruction::InstructionId>,
inst_allocator: Arena<core::instruction::Instruction>,
}
impl fmt::Display for BasicBlock {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
if !self.label.is_empty() {
writeln!(f, "{}:", self.label)?;
}
for inst_id in self.instructions.iter() {
let inst = self.inst_allocator.get(*inst_id).unwrap();
writeln!(f, " {}", inst)?;
}
Ok(())
}
}
#[allow(dead_code)]
impl BasicBlock {
pub fn new(
l: core::llvm_string::LLVMString,
pred: Option<BasicBlockId>,
k: BasicBlockKind,
) -> Self {
Self {
label: l,
predecessor: pred,
kind: k,
instructions: Vec::new(),
inst_allocator: Arena::new(),
}
}
pub fn print_successors(
&self,
f: &mut Formatter<'_>,
allocator: &Arena<core::basic_block::BasicBlock>,
) -> fmt::Result {
match self.kind {
BasicBlockKind::TERMINATED => {}
BasicBlockKind::UNCONDITIONAL(succ_id) => {
let succ_bb = allocator.get(succ_id).unwrap();
write!(f, "{}", succ_bb)?;
}
}
Ok(())
}
pub fn get_label_ref(&self) -> &core::llvm_string::LLVMString {
&self.label
}
pub fn insts_empty(&self) -> bool {
self.instructions.is_empty()
}
pub fn new_inst(
&mut self,
inst: core::instruction::Instruction,
) -> core::instruction::InstructionId {
let inst_id = self.inst_allocator.alloc(inst);
self.instructions.push(inst_id);
inst_id
}
}
impl Default for BasicBlock {
fn default() -> Self {
Self {
label: core::llvm_string::LLVMString::from(String::new()),
predecessor: None,
kind: BasicBlockKind::TERMINATED,
instructions: Vec::new(),
inst_allocator: Arena::new(),
}
}
}
#[derive(Eq, PartialEq, PartialOrd, Ord, Hash)]
pub enum BasicBlockKind {
TERMINATED,
UNCONDITIONAL(BasicBlockId),
}