use super::lex::Loc;
use std::collections::HashMap;
use std::sync::Arc as Rc;
pub type TypeId = u32;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct FuncType {
pub ret: TypeId,
pub params: Vec<TypeId>,
pub variadic: bool,
pub proto: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Type {
Void,
Bool,
Int { size: u8, signed: bool },
Float { size: u8 },
Ptr(TypeId),
Array(TypeId, Option<u32>),
Func(Rc<FuncType>),
Record(u32),
}
pub const VOID: TypeId = 0;
pub const BOOL: TypeId = 1;
pub const UCHAR: TypeId = 2;
pub const SCHAR: TypeId = 3;
pub const SHORT: TypeId = 4;
pub const USHORT: TypeId = 5;
pub const INT: TypeId = 6;
pub const UINT: TypeId = 7;
pub const LLONG: TypeId = 8;
pub const ULLONG: TypeId = 9;
pub const FLOAT: TypeId = 10;
pub const DOUBLE: TypeId = 11;
#[derive(Clone, Debug)]
pub struct Field {
pub name: Rc<str>,
pub ty: TypeId,
pub offset: u32,
pub bits: Option<(u8, u8)>,
}
#[derive(Clone, Debug)]
pub struct Record {
pub name: Option<Rc<str>>,
pub is_union: bool,
pub fields: Vec<Field>,
pub size: u32,
pub align: u32,
pub complete: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub enum SymRef {
Global(u32),
Func(u32),
Str(u32),
}
#[derive(Clone, Debug, Default)]
pub struct Init {
pub bytes: Vec<u8>,
pub relocs: Vec<(u32, SymRef, i64)>,
}
#[derive(Clone, Debug)]
pub struct Global {
pub name: Rc<str>,
pub ty: TypeId,
pub is_static: bool,
pub is_local_static: bool,
pub is_const: bool,
pub is_volatile: bool,
pub defined: bool,
pub init: Option<Init>,
pub loc: Loc,
}
#[derive(Clone, Debug)]
pub struct Local {
pub name: Rc<str>,
pub ty: TypeId,
}
#[derive(Clone, Debug)]
pub struct Func {
pub name: Rc<str>,
pub ty: Rc<FuncType>,
pub is_static: bool,
pub is_inline: bool,
pub nparams: usize,
pub locals: Vec<Local>,
pub body: Option<Body>,
pub loc: Loc,
pub unsupported: Option<String>,
pub variadic_def: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BinOp {
Add,
Sub,
Mul,
Div,
Rem,
And,
Or,
Xor,
Shl,
Shr,
Eq,
Ne,
Lt,
Le,
}
#[derive(Clone, Debug)]
pub struct Expr {
pub kind: EK,
pub ty: TypeId,
pub loc: Loc,
}
#[derive(Clone, Debug)]
pub enum EK {
Const(u64),
FConst(f64),
Str(u32),
Local(u32),
Global(u32),
Func(u32),
Deref(Box<Expr>),
Member(Box<Expr>, u32),
BitField(Box<Expr>, u32, u8, u8),
Compound {
var: u32,
zero: bool,
items: Vec<(u32, Expr)>,
},
Bits(Box<Expr>, u8, u8),
Addr(Box<Expr>),
Load(Box<Expr>),
Cast(Box<Expr>),
Neg(Box<Expr>),
BitNot(Box<Expr>),
LogNot(Box<Expr>),
Bin(BinOp, Box<Expr>, Box<Expr>),
PtrAdd(Box<Expr>, Box<Expr>, u32),
PtrDiff(Box<Expr>, Box<Expr>, u32),
LogAnd(Box<Expr>, Box<Expr>),
LogOr(Box<Expr>, Box<Expr>),
Cond(Box<Expr>, Box<Expr>, Box<Expr>),
Comma(Box<Expr>, Box<Expr>),
Assign(Box<Expr>, Box<Expr>),
AssignOp(Box<Expr>, Box<Expr>, bool),
Prev,
Call(Box<Expr>, Vec<Expr>),
VaStart(Box<Expr>),
VaArg(Box<Expr>),
}
#[derive(Clone, Debug)]
pub struct Stmt {
pub kind: SK,
pub loc: Loc,
}
#[derive(Clone, Debug)]
pub enum SK {
Expr(Expr),
Init {
var: u32,
zero: bool,
items: Vec<(u32, Expr)>,
},
Block(Vec<Stmt>),
If(Expr, Box<Stmt>, Option<Box<Stmt>>),
While(Expr, Box<Stmt>),
DoWhile(Box<Stmt>, Expr),
For(Option<Box<Stmt>>, Option<Expr>, Option<Expr>, Box<Stmt>),
Switch(Expr, Box<Stmt>),
Case(u64, u64),
Default,
Break,
Continue,
Return(Option<Expr>),
Goto(Rc<str>),
Label(Rc<str>),
Empty,
}
#[derive(Clone, Debug, Default)]
pub struct Body {
pub blocks: Vec<Block>,
}
#[derive(Clone, Debug)]
pub struct Block {
pub ops: Vec<Op>,
pub term: Term,
pub term_cov: u32,
pub term_loc: Loc,
}
#[derive(Clone, Debug)]
pub struct Op {
pub kind: OpKind,
pub cov: u32,
pub loc: Loc,
}
#[derive(Clone, Debug)]
pub enum OpKind {
Eval(Expr),
Init {
var: u32,
zero: bool,
items: Vec<(u32, Expr)>,
},
}
#[derive(Clone, Debug)]
pub enum Term {
Jump(usize),
Br(Expr, usize, usize),
Switch(Expr, Vec<(u64, u64, usize)>, usize),
Ret(Option<Expr>),
Unreachable,
}
#[derive(Default)]
pub struct Program {
pub types: Vec<Type>,
type_map: HashMap<Type, TypeId>,
pub records: Vec<Record>,
pub globals: Vec<Global>,
pub funcs: Vec<Func>,
pub strings: Vec<Rc<[u8]>>,
pub files: Vec<String>,
pub units: Vec<String>,
pub func_unit: Vec<u16>,
pub global_unit: Vec<u16>,
pub ncov: u32,
pub cov_info: Vec<(u32, Loc)>,
pub int_enums: bool,
pub noreturn: std::collections::HashSet<Rc<str>>,
pub restrict_params: std::collections::HashSet<(u32, u32)>,
volatile: HashMap<TypeId, TypeId>,
unqualified: HashMap<TypeId, TypeId>,
}
impl Program {
pub fn new() -> Program {
let mut p = Program::default();
let base = [
Type::Void,
Type::Bool,
Type::Int { size: 1, signed: false },
Type::Int { size: 1, signed: true },
Type::Int { size: 2, signed: true },
Type::Int { size: 2, signed: false },
Type::Int { size: 4, signed: true },
Type::Int { size: 4, signed: false },
Type::Int { size: 8, signed: true },
Type::Int { size: 8, signed: false },
Type::Float { size: 4 },
Type::Float { size: 8 },
];
for t in base {
p.intern(t);
}
p
}
pub fn intern(&mut self, t: Type) -> TypeId {
if let Some(&id) = self.type_map.get(&t) {
return id;
}
let id = self.types.len() as TypeId;
self.types.push(t.clone());
self.type_map.insert(t, id);
id
}
pub fn volatile_of(&mut self, t: TypeId) -> TypeId {
if self.unqualified.contains_key(&t) {
return t;
}
if let Some(&v) = self.volatile.get(&t) {
return v;
}
let ty = match self.ty(t).clone() {
Type::Array(e, n) => Type::Array(self.volatile_of(e), n),
other => other,
};
let id = self.types.len() as TypeId;
self.types.push(ty);
self.volatile.insert(t, id);
self.unqualified.insert(id, t);
id
}
pub fn is_volatile(&self, t: TypeId) -> bool {
self.unqualified.contains_key(&t)
}
pub fn unqual(&self, t: TypeId) -> TypeId {
self.unqualified.get(&t).copied().unwrap_or(t)
}
pub fn value_bits(&self, t: TypeId, base: u32, out: &mut Vec<(u32, u32)>) {
match self.ty(t) {
Type::Array(e, n) => {
let es = self.size_of(*e).unwrap_or(0);
for i in 0..n.unwrap_or(0) {
self.value_bits(*e, base + i * es * 8, out);
}
}
Type::Record(r) => {
for f in &self.records[*r as usize].fields {
match f.bits {
Some((bit, w)) => out.push((base + f.offset * 8 + bit as u32, w as u32)),
None => self.value_bits(f.ty, base + f.offset * 8, out),
}
}
}
_ => out.push((base, self.size_of(t).unwrap_or(0) * 8)),
}
}
pub fn value_mask(&self, t: TypeId) -> Vec<u8> {
let mut m = vec![0u8; self.size_of(t).unwrap_or(0) as usize];
let mut ranges = Vec::new();
self.value_bits(t, 0, &mut ranges);
for (first, len) in ranges {
for b in first..first + len {
if let Some(x) = m.get_mut(b as usize / 8) {
*x |= 1 << (b % 8);
}
}
}
m
}
pub fn ty(&self, id: TypeId) -> &Type {
&self.types[id as usize]
}
pub fn ptr_to(&mut self, t: TypeId) -> TypeId {
self.intern(Type::Ptr(t))
}
pub fn is_integer(&self, t: TypeId) -> bool {
matches!(self.ty(t), Type::Bool | Type::Int { .. })
}
pub fn is_float(&self, t: TypeId) -> bool {
matches!(self.ty(t), Type::Float { .. })
}
pub fn is_arith(&self, t: TypeId) -> bool {
self.is_integer(t) || self.is_float(t)
}
pub fn is_ptr(&self, t: TypeId) -> bool {
matches!(self.ty(t), Type::Ptr(_))
}
pub fn is_scalar(&self, t: TypeId) -> bool {
self.is_arith(t) || self.is_ptr(t)
}
pub fn is_signed(&self, t: TypeId) -> bool {
matches!(self.ty(t), Type::Int { signed: true, .. })
}
pub fn pointee(&self, t: TypeId) -> Option<TypeId> {
match self.ty(t) {
Type::Ptr(p) => Some(*p),
_ => None,
}
}
pub fn size_of(&self, t: TypeId) -> Option<u32> {
Some(match self.ty(t) {
Type::Void | Type::Func(_) => 1,
Type::Bool => 1,
Type::Int { size, .. } | Type::Float { size } => *size as u32,
Type::Ptr(_) => 4,
Type::Array(e, n) => self.size_of(*e)?.checked_mul((*n)?)?,
Type::Record(r) => {
let r = &self.records[*r as usize];
if !r.complete {
return None;
}
r.size
}
})
}
pub fn align_of(&self, t: TypeId) -> u32 {
match self.ty(t) {
Type::Void | Type::Func(_) | Type::Bool => 1,
Type::Int { size, .. } | Type::Float { size } => *size as u32,
Type::Ptr(_) => 4,
Type::Array(e, _) => self.align_of(*e),
Type::Record(r) => self.records[*r as usize].align.max(1),
}
}
pub fn bits(&self, t: TypeId) -> u8 {
match self.ty(t) {
Type::Bool => 8,
Type::Int { size, .. } | Type::Float { size } => size * 8,
_ => 32,
}
}
pub fn type_name(&self, t: TypeId) -> String {
match self.ty(t) {
Type::Void => "void".into(),
Type::Bool => "_Bool".into(),
Type::Int { size, signed } => {
format!("{}int{}_t", if *signed { "" } else { "u" }, size * 8)
}
Type::Float { size } => if *size == 4 { "float" } else { "double" }.into(),
Type::Ptr(p) => format!("{}*", self.type_name(*p)),
Type::Array(e, n) => format!(
"{}[{}]",
self.type_name(*e),
n.map(|n| n.to_string()).unwrap_or_default()
),
Type::Func(f) => format!("{}()", self.type_name(f.ret)),
Type::Record(r) => {
let r = &self.records[*r as usize];
format!(
"{} {}",
if r.is_union { "union" } else { "struct" },
r.name.as_deref().unwrap_or("<anon>")
)
}
}
}
}