use crate::entity::{EntitySet, SecondaryMap};
use crate::flowgraph::{BlockPredecessor, ControlFlowGraph};
use crate::ir;
use crate::ir::instructions::BranchInfo;
use crate::packed_option::PackedOption;
use crate::timing;
use crate::verifier::{VerifierErrors, VerifierStepResult};
pub fn verify_flags(
func: &ir::Function,
cfg: &ControlFlowGraph,
errors: &mut VerifierErrors,
) -> VerifierStepResult<()> {
let _tt = timing::verify_flags();
let mut verifier = FlagsVerifier {
func,
cfg,
livein: SecondaryMap::new(),
};
verifier.check(errors)
}
struct FlagsVerifier<'a> {
func: &'a ir::Function,
cfg: &'a ControlFlowGraph,
livein: SecondaryMap<ir::Block, PackedOption<ir::Value>>,
}
impl<'a> FlagsVerifier<'a> {
fn check(&mut self, errors: &mut VerifierErrors) -> VerifierStepResult<()> {
let mut worklist = EntitySet::with_capacity(self.func.layout.block_capacity());
for block in self.func.layout.blocks() {
worklist.insert(block);
}
while let Some(block) = worklist.pop() {
if let Some(value) = self.visit_block(block, errors)? {
match self.livein[block].expand() {
None => {
self.livein[block] = value.into();
for BlockPredecessor { block: pred, .. } in self.cfg.pred_iter(block) {
worklist.insert(pred);
}
}
Some(old) if old != value => {
return errors.fatal((
block,
format!("conflicting live-in CPU flags: {} and {}", old, value),
));
}
x => assert_eq!(x, Some(value)),
}
} else {
assert_eq!(self.livein[block].expand(), None);
}
}
Ok(())
}
fn visit_block(
&self,
block: ir::Block,
errors: &mut VerifierErrors,
) -> VerifierStepResult<Option<ir::Value>> {
let mut live_val = None;
for inst in self.func.layout.block_insts(block).rev() {
if let Some(live) = live_val {
for &res in self.func.dfg.inst_results(inst) {
if res == live {
live_val = None;
} else if self.func.dfg.value_type(res).is_flags() {
errors
.report((inst, format!("{} clobbers live CPU flags in {}", res, live)));
return Err(());
}
}
}
for &arg in self.func.dfg.inst_args(inst) {
if self.func.dfg.value_type(arg).is_flags() {
merge(&mut live_val, arg, inst, errors)?;
}
}
match self.func.dfg.analyze_branch(inst) {
BranchInfo::NotABranch => {}
BranchInfo::SingleDest(dest, _) => {
if let Some(val) = self.livein[dest].expand() {
merge(&mut live_val, val, inst, errors)?;
}
}
BranchInfo::Table(jt, dest) => {
if let Some(dest) = dest {
if let Some(val) = self.livein[dest].expand() {
merge(&mut live_val, val, inst, errors)?;
}
}
for dest in self.func.jump_tables[jt].iter() {
if let Some(val) = self.livein[*dest].expand() {
merge(&mut live_val, val, inst, errors)?;
}
}
}
}
}
Ok(live_val)
}
}
fn merge(
a: &mut Option<ir::Value>,
b: ir::Value,
inst: ir::Inst,
errors: &mut VerifierErrors,
) -> VerifierStepResult<()> {
if let Some(va) = *a {
if b != va {
return errors.fatal((
inst,
format!("conflicting live CPU flags: {} and {}", va, b),
));
}
} else {
*a = Some(b);
}
Ok(())
}