cverif 0.0.2

Verifies that compiled machine code faithfully matches its C source
Documentation
//! Lowers the statement tree of a function into a control-flow graph.

use super::ast::*;
use super::lex::{Loc, Res, err};
use std::collections::HashMap;
use std::sync::Arc as Rc; // shared read-only between verification threads

pub const NO_COV: u32 = u32::MAX;

struct Switch {
    cases: Vec<(u64, u64, usize)>,
    default: Option<usize>,
}

struct Lower<'a> {
    prog: &'a mut Program,
    fid: u32,
    blocks: Vec<Block>,
    done: Vec<bool>,
    cur: usize,
    breaks: Vec<usize>,
    conts: Vec<usize>,
    labels: HashMap<Rc<str>, usize>,
    switches: Vec<Switch>,
}

pub fn lower(prog: &mut Program, fid: u32, body: &Stmt) -> Res<Body> {
    let mut l = Lower {
        prog,
        fid,
        blocks: Vec::new(),
        done: Vec::new(),
        cur: 0,
        breaks: Vec::new(),
        conts: Vec::new(),
        labels: HashMap::new(),
        switches: Vec::new(),
    };
    l.cur = l.new_block();
    l.stmt(body)?;
    let cur = l.cur;
    l.finish(cur, Term::Ret(None), body.loc, false);
    Ok(Body { blocks: l.blocks })
}

impl Lower<'_> {
    fn new_block(&mut self) -> usize {
        self.blocks.push(Block {
            ops: Vec::new(),
            term: Term::Unreachable,
            term_cov: NO_COV,
            term_loc: Loc::default(),
        });
        self.done.push(false);
        self.blocks.len() - 1
    }

    fn cov(&mut self, loc: Loc) -> u32 {
        let id = self.prog.ncov;
        self.prog.ncov += 1;
        self.prog.cov_info.push((self.fid, loc));
        id
    }

    fn finish(&mut self, b: usize, term: Term, loc: Loc, counted: bool) {
        if self.done[b] {
            return;
        }
        self.done[b] = true;
        let cov = if counted { self.cov(loc) } else { NO_COV };
        let blk = &mut self.blocks[b];
        blk.term = term;
        blk.term_cov = cov;
        blk.term_loc = loc;
    }

    /// Terminate the current block and continue in `next`.
    fn goto(&mut self, target: usize, next: usize, loc: Loc) {
        let cur = self.cur;
        self.finish(cur, Term::Jump(target), loc, false);
        self.cur = next;
    }

    fn label(&mut self, name: &Rc<str>) -> usize {
        if let Some(&b) = self.labels.get(name) {
            return b;
        }
        let b = self.new_block();
        self.labels.insert(name.clone(), b);
        b
    }

    fn op(&mut self, kind: OpKind, loc: Loc) {
        let cov = self.cov(loc);
        self.blocks[self.cur].ops.push(Op { kind, cov, loc });
    }

    fn stmt(&mut self, s: &Stmt) -> Res<()> {
        let loc = s.loc;
        match &s.kind {
            SK::Empty => {}
            SK::Expr(e) => self.op(OpKind::Eval(e.clone()), loc),
            SK::Init { var, zero, items } => self.op(
                OpKind::Init {
                    var: *var,
                    zero: *zero,
                    items: items.clone(),
                },
                loc,
            ),
            SK::Block(v) => {
                for s in v {
                    self.stmt(s)?;
                }
            }
            SK::If(c, t, e) => {
                let (bt, be, end) = (self.new_block(), self.new_block(), self.new_block());
                let cur = self.cur;
                self.finish(cur, Term::Br(c.clone(), bt, be), loc, true);
                self.cur = bt;
                self.stmt(t)?;
                self.goto(end, be, loc);
                if let Some(e) = e {
                    self.stmt(e)?;
                }
                self.goto(end, end, loc);
            }
            SK::While(c, body) => {
                let (head, bb, end) = (self.new_block(), self.new_block(), self.new_block());
                self.goto(head, head, loc);
                self.finish(head, Term::Br(c.clone(), bb, end), loc, true);
                self.cur = bb;
                self.breaks.push(end);
                self.conts.push(head);
                self.stmt(body)?;
                self.breaks.pop();
                self.conts.pop();
                self.goto(head, end, loc);
            }
            SK::DoWhile(body, c) => {
                let (bb, cond, end) = (self.new_block(), self.new_block(), self.new_block());
                self.goto(bb, bb, loc);
                self.breaks.push(end);
                self.conts.push(cond);
                self.stmt(body)?;
                self.breaks.pop();
                self.conts.pop();
                self.goto(cond, cond, loc);
                self.finish(cond, Term::Br(c.clone(), bb, end), c.loc, true);
                self.cur = end;
            }
            SK::For(init, c, step, body) => {
                if let Some(i) = init {
                    self.stmt(i)?;
                }
                let (head, bb, st, end) = (self.new_block(), self.new_block(), self.new_block(), self.new_block());
                self.goto(head, head, loc);
                match c {
                    Some(c) => self.finish(head, Term::Br(c.clone(), bb, end), loc, true),
                    None => self.finish(head, Term::Jump(bb), loc, false),
                }
                self.cur = bb;
                self.breaks.push(end);
                self.conts.push(st);
                self.stmt(body)?;
                self.breaks.pop();
                self.conts.pop();
                self.goto(st, st, loc);
                if let Some(e) = step {
                    self.op(OpKind::Eval(e.clone()), e.loc);
                }
                self.goto(head, end, loc);
            }
            SK::Switch(e, body) => {
                let head = self.cur;
                let end = self.new_block();
                self.cur = self.new_block();
                self.switches.push(Switch {
                    cases: Vec::new(),
                    default: None,
                });
                self.breaks.push(end);
                self.stmt(body)?;
                self.breaks.pop();
                let sw = self.switches.pop().unwrap();
                self.goto(end, end, loc);
                self.finish(
                    head,
                    Term::Switch(e.clone(), sw.cases, sw.default.unwrap_or(end)),
                    loc,
                    true,
                );
            }
            SK::Case(..) | SK::Default => {
                let b = self.new_block();
                self.goto(b, b, loc);
                let Some(sw) = self.switches.last_mut() else {
                    return err(loc, "case label outside switch");
                };
                match &s.kind {
                    SK::Case(lo, hi) => sw.cases.push((*lo, *hi, b)),
                    _ => sw.default = Some(b),
                }
            }
            SK::Break => {
                let Some(&t) = self.breaks.last() else {
                    return err(loc, "break outside loop or switch");
                };
                let n = self.new_block();
                self.goto(t, n, loc);
            }
            SK::Continue => {
                let Some(&t) = self.conts.last() else {
                    return err(loc, "continue outside loop");
                };
                let n = self.new_block();
                self.goto(t, n, loc);
            }
            SK::Return(e) => {
                let cur = self.cur;
                self.finish(cur, Term::Ret(e.clone()), loc, true);
                self.cur = self.new_block();
            }
            SK::Goto(name) => {
                let t = self.label(name);
                let n = self.new_block();
                self.goto(t, n, loc);
            }
            SK::Label(name) => {
                let b = self.label(name);
                self.goto(b, b, loc);
            }
        }
        Ok(())
    }
}