cverif 0.0.7

Verifies that compiled machine code faithfully matches its C source
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
//! Typed C program representation (target: ARM EABI, ILP32, little-endian).

use super::lex::Loc;
use std::collections::HashMap;
use std::sync::Arc as Rc; // shared read-only between verification threads

pub type TypeId = u32;

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct FuncType {
    pub ret: TypeId,
    pub params: Vec<TypeId>,
    pub variadic: bool,
    /// Declared with a prototype (`f(void)` or `f(int)`, as opposed to `f()`).
    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,
    /// Bit-field: (first bit within the byte at `offset`, width in bits).
    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),
}

/// Initial contents of a global: raw bytes plus address relocations.
#[derive(Clone, Debug, Default)]
pub struct Init {
    pub bytes: Vec<u8>,
    /// (offset, target, addend): a 32-bit pointer to `target + addend` is stored at `offset`.
    pub relocs: Vec<(u32, SymRef, i64)>,
}

#[derive(Clone, Debug)]
pub struct Global {
    pub name: Rc<str>,
    pub ty: TypeId,
    /// Internal linkage (file-scope `static`) or function-local `static`.
    pub is_static: bool,
    /// Function-local static: the binary symbol is `name.N`.
    pub is_local_static: bool,
    pub is_const: bool,
    pub is_volatile: bool,
    /// Has a definition (initializer or tentative definition) rather than only `extern`.
    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,
    /// The first `nparams` locals are the parameters.
    pub nparams: usize,
    pub locals: Vec<Local>,
    pub body: Option<Body>,
    pub loc: Loc,
    /// The body uses something the front end cannot model ("line N: reason"); the function
    /// has an empty stand-in body and must be reported as unsupported, as must its callers.
    pub unsupported: Option<String>,
    /// Number of fixed parameters is `nparams`; this one also takes variable arguments.
    pub variadic_def: bool,
    /// Written in assembly (a `naked` function, or a body that is nothing but inline assembly
    /// the front end has no meaning for): the function itself cannot be verified, but its
    /// callers treat it like a function defined elsewhere.
    pub opaque: bool,
    /// The whole body in assembly, statement after statement (a `naked` function made of
    /// assembly statements without operands): what its machine code must consist of.
    pub asm: Option<Rc<str>>,
    /// Assembly statements of the body that are compared as blocks (see [`AsmBlock`]).
    pub asm_blocks: Vec<AsmBlock>,
    /// A `naked` function with a C body: it has no return sequence, and reaching its end
    /// is undefined.
    pub naked: bool,
}

/// An inline assembly statement that the front end has no meaning for, but whose place in
/// the function makes it comparable all the same: the binary must contain exactly these
/// instructions (see `thumb::asm`) and reach them when the source reaches the statement, with
/// the operand the source gives.  Two kinds:
///
/// * a statement that never falls through (it ends in an unconditional branch or a return):
///   control leaves C for good, like a call to a function that does not return;
/// * `ldr sp, =symbol` as the first thing a `naked` function does: the stack is switched,
///   and the rest of the function is verified for whatever stack it runs on.
#[derive(Clone, Debug)]
pub struct AsmBlock {
    /// Name of the event (the statement's text, blanks collapsed, in braces).
    pub name: Rc<str>,
    /// The template; `%0` stands for the register of the operand.
    pub text: Rc<str>,
    /// The statement has a register input operand.
    pub operand: bool,
    /// The operand's constraint restricts it to r0-r7.
    pub low: bool,
    /// The second kind above.
    pub sets_sp: bool,
}

/// One instruction of an inline assembly statement that the front end knows the meaning of: an
/// observable event the binary must reproduce with the same instruction.
#[derive(Clone, Debug)]
pub struct AsmInsn {
    /// The instruction without its register operand: `cpsid i`, `wfi`, `bkpt 3`, `mrs primask`,
    /// `msr basepri`.
    pub name: Rc<str>,
    /// The value an MSR writes.
    pub input: Option<Expr>,
    /// The instruction produces a value (MRS): it is the value of the expression.
    pub output: bool,
    /// The statement lists `memory` among the things it clobbers: as far as memory is concerned
    /// it is a call to an unknown function.
    pub memory: bool,
    /// A statement compared as a block that never falls through (see [`AsmBlock`]).
    pub noreturn: bool,
    /// A statement compared as a block.
    pub block: 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),
    // --- lvalues ---
    Str(u32),
    Local(u32),
    Global(u32),
    /// Function designator.
    Func(u32),
    Deref(Box<Expr>),
    /// Member of the lvalue at byte offset.
    Member(Box<Expr>, u32),
    /// Bit-field member of the lvalue: byte offset, first bit within that byte, width.
    BitField(Box<Expr>, u32, u8, u8),
    /// Compound literal: an unnamed local that is (re)initialised whenever the expression is evaluated.
    Compound {
        var: u32,
        zero: bool,
        items: Vec<(u32, Expr)>,
    },
    /// Only as an initialiser item: the value of a bit-field (first bit, width) of the unit at the item's offset.
    Bits(Box<Expr>, u8, u8),
    // --- rvalues ---
    /// Address of an lvalue (also array and function decay).
    Addr(Box<Expr>),
    /// Lvalue-to-rvalue conversion.
    Load(Box<Expr>),
    /// Conversion to `ty`.
    Cast(Box<Expr>),
    Neg(Box<Expr>),
    BitNot(Box<Expr>),
    LogNot(Box<Expr>),
    /// Operands already converted to the operation type (the left operand's type).
    Bin(BinOp, Box<Expr>, Box<Expr>),
    /// pointer + index * elem_size; index is a 32-bit signed integer.
    PtrAdd(Box<Expr>, Box<Expr>, u32),
    /// (a - b) / elem_size
    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>),
    /// Read-modify-write of an lvalue.  The second operand computes the new value and refers
    /// to the old one through `EK::Prev`.  With `post`, the result is the old value.
    AssignOp(Box<Expr>, Box<Expr>, bool),
    Prev,
    /// Callee is a pointer-to-function rvalue.
    Call(Box<Expr>, Vec<Expr>),
    /// `va_start(ap, last)`: the operand is the `va_list` lvalue.
    VaStart(Box<Expr>),
    /// `va_arg(ap, type)`: the operand is the `va_list` lvalue, the expression type is `type`.
    VaArg(Box<Expr>),
    /// The address of a new object with automatic storage whose size in bytes is the operand
    /// (`alloca`, and the storage of a variable-length array).  The object lives until the
    /// function returns.  The operand counts elements of the given size; a variable-length
    /// array names its declaration (the hidden local that holds its address), must have at
    /// least one element, and lives until its scope is left (see `VlaLive`).
    Alloca(Box<Expr>, u32, Option<u32>),
    /// Control is at a point where only these variable-length array declarations of the
    /// function are in scope: the objects of the others are dead.
    VlaLive(Rc<[u32]>),
    /// A modelled inline assembly instruction; the value is what an MRS reads (32 bits).
    Asm(Box<AsmInsn>),
}

impl Expr {
    /// The operands of this expression, in no particular order.
    pub fn children(&self) -> Vec<&Expr> {
        match &self.kind {
            EK::Const(_)
            | EK::FConst(_)
            | EK::Str(_)
            | EK::Local(_)
            | EK::Global(_)
            | EK::Func(_)
            | EK::Prev
            | EK::VlaLive(_) => Vec::new(),
            EK::Asm(a) => a.input.iter().collect(),
            EK::Alloca(a, ..)
            | EK::Deref(a)
            | EK::Member(a, _)
            | EK::BitField(a, ..)
            | EK::Bits(a, ..)
            | EK::Addr(a)
            | EK::Load(a)
            | EK::Cast(a)
            | EK::Neg(a)
            | EK::BitNot(a)
            | EK::LogNot(a)
            | EK::VaStart(a)
            | EK::VaArg(a) => vec![a],
            EK::Bin(_, a, b)
            | EK::PtrAdd(a, b, _)
            | EK::PtrDiff(a, b, _)
            | EK::LogAnd(a, b)
            | EK::LogOr(a, b)
            | EK::Comma(a, b)
            | EK::Assign(a, b)
            | EK::AssignOp(a, b, _) => vec![a, b],
            EK::Cond(a, b, c) => vec![a, b, c],
            EK::Compound { items, .. } => items.iter().map(|x| &x.1).collect(),
            EK::Call(f, args) => std::iter::once(&**f).chain(args.iter()).collect(),
        }
    }
}

impl Body {
    /// Every expression the body evaluates (the roots, not their operands).
    pub fn exprs(&self) -> impl Iterator<Item = &Expr> {
        self.blocks.iter().flat_map(|b| {
            let ops = b.ops.iter().flat_map(|op| -> Vec<&Expr> {
                match &op.kind {
                    OpKind::Eval(e) => vec![e],
                    OpKind::Init { items, .. } => items.iter().map(|x| &x.1).collect(),
                }
            });
            let term = match &b.term {
                Term::Br(e, ..) | Term::Switch(e, ..) | Term::Ret(Some(e)) => Some(e),
                Term::Jump(_) | Term::Ret(None) | Term::Unreachable => None,
            };
            ops.chain(term)
        })
    }
}

impl Program {
    /// Mark the bytes of an object of type `t` at `off` that hold (part of) a member; what
    /// stays unmarked in `out` is padding.  False if the layout is not known well enough, in
    /// which case every byte counts as data.
    fn mark_data(&self, t: TypeId, off: u32, out: &mut [bool]) -> bool {
        match self.ty(t) {
            Type::Record(r) => {
                let rec = &self.records[*r as usize];
                if !rec.complete {
                    return false;
                }
                if rec.is_union {
                    // Which member is live is not known: no byte is known to be padding.
                    let end = (off + rec.size).min(out.len() as u32);
                    out[off as usize..end as usize].fill(true);
                    return true;
                }
                rec.fields.iter().all(|f| match f.bits {
                    Some(_) => {
                        // The whole storage unit of a bit-field counts.
                        let n = self.size_of(f.ty).unwrap_or(4);
                        let end = (off + f.offset + n).min(out.len() as u32);
                        out[(off + f.offset) as usize..end as usize].fill(true);
                        true
                    }
                    None => self.mark_data(f.ty, off + f.offset, out),
                })
            }
            Type::Array(e, Some(n)) => {
                let Some(size) = self.size_of(*e) else { return false };
                (0..*n).all(|i| self.mark_data(*e, off + i * size, out))
            }
            Type::Array(_, None) => false,
            _ => match self.size_of(t) {
                Some(n) if (off + n) as usize <= out.len() => {
                    out[off as usize..(off + n) as usize].fill(true);
                    true
                }
                _ => false,
            },
        }
    }

    /// The padding of an object of type `t`: (offset, length) of each run of bytes that
    /// belong to no member.  Empty when there is none or the layout is not fully known.
    pub fn padding(&self, t: TypeId) -> Vec<(u32, u32)> {
        let Some(size) = self.size_of(t).filter(|&s| s <= 4096) else {
            return Vec::new();
        };
        let mut data = vec![false; size as usize];
        if !self.mark_data(t, 0, &mut data) {
            return Vec::new();
        }
        let mut out: Vec<(u32, u32)> = Vec::new();
        for (i, _) in data.iter().enumerate().filter(|x| !*x.1) {
            match out.last_mut() {
                Some(last) if last.0 + last.1 == i as u32 => last.1 += 1,
                _ => out.push((i as u32, 1)),
            }
        }
        out
    }

    /// The parameter of function `fid` that the function returns unchanged on every return,
    /// as its source shows: every `return` gives the value of that parameter, and nothing
    /// else in the body refers to the parameter except to read it (so it is never assigned
    /// and its address is never taken).  This is a fact about the source function alone; a
    /// caller's proof may use it because the function is verified against that source.
    pub fn returns_param(&self, fid: u32) -> Option<usize> {
        let f = &self.funcs[fid as usize];
        let body = f.body.as_ref()?;
        if f.opaque
            || f.unsupported.is_some()
            || f.variadic_def
            || !self.is_scalar(f.ty.ret)
            || self.bits(f.ty.ret) != 32
        {
            return None;
        }
        fn strip(p: &Program, e: &Expr) -> Option<u32> {
            match &e.kind {
                EK::Load(x) => match x.kind {
                    EK::Local(k) => Some(k),
                    _ => None,
                },
                // A conversion between 32-bit integers and pointers keeps the value.
                EK::Cast(x) if p.is_scalar(e.ty) && p.is_scalar(x.ty) && !p.is_float(e.ty) && !p.is_float(x.ty) => {
                    (p.bits(e.ty) == 32 && p.bits(x.ty) == 32 && !matches!(p.ty(e.ty), Type::Bool))
                        .then(|| strip(p, x))
                        .flatten()
                }
                _ => None,
            }
        }
        let mut param: Option<u32> = None;
        for b in &body.blocks {
            // Flowing off the end of a function whose value the caller uses is undefined
            // (C11 6.9.1p12): only the returns that give a value count.
            if let Term::Ret(Some(e)) = &b.term {
                let k = strip(self, e)?;
                if param.is_some_and(|q| q != k) {
                    return None;
                }
                param = Some(k);
            }
        }
        let k = param.filter(|&k| (k as usize) < f.nparams)?;
        let l = &f.locals[k as usize];
        if !self.is_scalar(l.ty) || self.is_float(l.ty) || self.bits(l.ty) != 32 || self.is_volatile(l.ty) {
            return None;
        }
        // Any mention of the parameter other than reading its value disqualifies it.
        fn only_read(e: &Expr, k: u32) -> bool {
            match &e.kind {
                EK::Local(j) => *j != k,
                EK::Load(x) if matches!(x.kind, EK::Local(_)) => true,
                EK::Compound { var, .. } if *var == k => false,
                EK::Alloca(_, _, Some(v)) if *v == k => false,
                _ => e.children().into_iter().all(|c| only_read(c, k)),
            }
        }
        let inits = body.blocks.iter().flat_map(|b| b.ops.iter()).any(|op| match &op.kind {
            OpKind::Init { var, .. } => *var == k,
            OpKind::Eval(_) => false,
        });
        (!inits && body.exprs().all(|e| only_read(e, k))).then_some(k as usize)
    }
}

#[derive(Clone, Debug)]
pub struct Stmt {
    pub kind: SK,
    pub loc: Loc,
}

#[derive(Clone, Debug)]
pub enum SK {
    Expr(Expr),
    /// Initialise a local: optionally zero it, then store each (offset, value).
    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>),
    /// Inclusive range of values (a single value when both are equal).
    Case(u64, u64),
    Default,
    Break,
    Continue,
    Return(Option<Expr>),
    Goto(Rc<str>),
    Label(Rc<str>),
    Empty,
}

/// Control-flow graph of a function body.
#[derive(Clone, Debug, Default)]
pub struct Body {
    pub blocks: Vec<Block>,
}

#[derive(Clone, Debug)]
pub struct Block {
    pub ops: Vec<Op>,
    pub term: Term,
    /// Coverage point of the terminator.
    pub term_cov: u32,
    pub term_loc: Loc,
}

#[derive(Clone, Debug)]
pub struct Op {
    pub kind: OpKind,
    /// Coverage point id, unique within the program.
    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),
    /// Cases are inclusive ranges (low, high, target), compared in the type of the controlling expression.
    Switch(Expr, Vec<(u64, u64, usize)>, usize),
    Ret(Option<Expr>),
    /// Falling off the end of a non-void function, or a block not yet terminated.
    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>,
    /// Some declaration carries `__attribute__((may_alias))`: accesses are not told apart by
    /// their types anywhere in the program.
    pub may_alias: bool,
    /// Translation units, in the order they were parsed: the path of each main file.
    pub units: Vec<String>,
    /// For each function / global, the translation unit that first declared it.  For objects
    /// with internal linkage this is the unit that owns them.
    pub func_unit: Vec<u16>,
    pub global_unit: Vec<u16>,
    /// Number of coverage points allocated.
    pub ncov: u32,
    /// Coverage point -> (function index, location).
    pub cov_info: Vec<(u32, Loc)>,
    /// The flags the source passes to the fortified `printf` functions (`__builtin___snprintf_chk`
    /// and the like), by the name of the plain function; `None` for one that is not a constant.
    pub fortify_flags: std::collections::BTreeSet<(Rc<str>, Option<u32>)>,
    /// Coverage points no execution reaches: an integer constant condition decides against
    /// them, so no code exists for them.  Indexed by coverage point.
    pub cov_dead: Vec<bool>,
    /// Enumerated types are at least as wide as `int` (`-fno-short-enums`, the AAPCS variant
    /// clang uses) instead of the smallest type that fits (`-fshort-enums`, GCC's bare-metal default).
    pub int_enums: bool,
    /// Names of functions declared `_Noreturn` / `__attribute__((noreturn))`.
    pub noreturn: std::collections::HashSet<Rc<str>>,
    /// Names of functions declared `__attribute__((returns_twice))`.
    pub returns_twice: std::collections::HashSet<Rc<str>>,
    /// `restrict`-qualified pointer parameters of function definitions: (function, parameter).
    pub restrict_params: std::collections::HashSet<(u32, u32)>,
    /// Volatile-qualified variants of types: unqualified id -> qualified id and back.
    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
    }

    /// The volatile-qualified variant of `t`: a distinct id with the same structure.  Only lvalues
    /// and pointees carry it; values always have the unqualified type.
    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() {
            // Qualifying an array qualifies its elements.
            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)
    }

    /// Bits of an object of type `t` that hold a value (as opposed to padding): bit ranges
    /// (first bit, length) relative to the start of the object.
    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)),
        }
    }

    /// Per-byte masks of the value bits of an object of type `t`.
    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)
    }

    /// May records `a` and `b` be one structure type?  Each translation unit reads the
    /// headers afresh and so has records of its own for the types it shares with the others:
    /// the same tag (or none) and the same layout, or a declaration left incomplete.
    pub fn records_may_match(&self, a: u32, b: u32) -> bool {
        if a == b {
            return true;
        }
        let (ra, rb) = (&self.records[a as usize], &self.records[b as usize]);
        if ra.name != rb.name || ra.is_union != rb.is_union {
            return false;
        }
        !ra.complete
            || !rb.complete
            || (ra.size == rb.size
                && ra.fields.len() == rb.fields.len()
                && ra
                    .fields
                    .iter()
                    .zip(&rb.fields)
                    .all(|(x, y)| x.name == y.name && x.offset == y.offset))
    }

    /// May `a` and `b` be compatible types?  False only for types that certainly are not:
    /// used to rule a function out as the target of a call through a pointer, which is
    /// sound only when the call would be undefined.  Integer types of one size, pointers
    /// to `void` and to anything, unprototyped functions and incomplete types all count as
    /// possibly compatible.
    pub fn may_be_compatible(&self, a: TypeId, b: TypeId, depth: u32) -> bool {
        let (a, b) = (self.unqual(a), self.unqual(b));
        if a == b || depth > 8 {
            return true;
        }
        match (self.ty(a), self.ty(b)) {
            (Type::Void, Type::Void) => true,
            (Type::Bool | Type::Int { .. }, Type::Bool | Type::Int { .. }) => self.size_of(a) == self.size_of(b),
            (Type::Float { size: x }, Type::Float { size: y }) => x == y,
            (Type::Ptr(x), Type::Ptr(y)) => {
                let void = |t: TypeId| matches!(self.ty(self.unqual(t)), Type::Void);
                void(*x) || void(*y) || self.may_be_compatible(*x, *y, depth + 1)
            }
            (Type::Array(x, n), Type::Array(y, m)) => {
                (n.is_none() || m.is_none() || n == m) && self.may_be_compatible(*x, *y, depth + 1)
            }
            (Type::Func(x), Type::Func(y)) => self.funcs_may_be_compatible(x, y, depth + 1),
            (Type::Record(x), Type::Record(y)) => self.records_may_match(*x, *y),
            _ => false,
        }
    }

    pub fn funcs_may_be_compatible(&self, a: &FuncType, b: &FuncType, depth: u32) -> bool {
        self.may_be_compatible(a.ret, b.ret, depth)
            && (!a.proto
                || !b.proto
                || (a.variadic == b.variadic
                    && a.params.len() == b.params.len()
                    && a.params
                        .iter()
                        .zip(&b.params)
                        .all(|(&x, &y)| self.may_be_compatible(x, y, depth))))
    }

    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,
        }
    }

    /// Size in bytes; None for incomplete types.
    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),
        }
    }

    /// Width in bits of a scalar type as a term.
    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>")
                )
            }
        }
    }
}