diff --git a/minzc/pkg/mir2/adl_index_share.go b/minzc/pkg/mir2/adl_index_share.go index 12f2660ec..23ad8c34e 100644 --- a/minzc/pkg/mir2/adl_index_share.go +++ b/minzc/pkg/mir2/adl_index_share.go @@ -20,7 +20,8 @@ package mir2 // 2. Adjacent elements: ptr_add B, scale(ext(i + c)) with a dominating // ptr_add P = B + scale(ext(i)) becomes field P, c< limit) n = limit": the global is loaded +// once for the test and again for the assignment. +// +// Every register involved must have exactly one definition (instruction, +// block parameter or function parameter); otherwise its range is the full +// range of its width. Only 8- and 16-bit integer values are tracked, as +// unsigned bit patterns (exact for add and sub, whose wrap is what is +// being excluded). +type rangeFacts struct { + f *Func + dom map[string]map[string]bool + blocks map[string]*Block + preds map[string][]*Block + def map[Reg]*Inst + defBlock map[Reg]*Block + defPos map[Reg]int + param map[Reg]*Block // block parameters: their block + paramIdx map[Reg]int + ndef map[Reg]int + width map[Reg]int + facts []rangeEdgeFact + memo map[rangeKey]valueRange + busy map[rangeKey]bool + pure map[string]int // per block: index of the first memory barrier, -1 none + lastBar map[string]int // per block: index of the last memory barrier, -1 none + fwd map[string][]string +} + +type valueRange struct{ lo, hi int64 } + +type rangeKey struct { + r Reg + block string +} + +// rangeEdgeFact: "x cond y" (an unsigned compare or eq) holds on the edge +// from block at to block to, for the values x and y had when at's +// terminator ran. +type rangeEdgeFact struct { + x, y Reg + cond CmpCond + at string + to string +} + +const rangeFactsDepth = 12 + +func newRangeFacts(f *Func) *rangeFacts { + u := &rangeFacts{ + f: f, + dom: reachableDominators(f), + blocks: map[string]*Block{}, + preds: map[string][]*Block{}, + def: map[Reg]*Inst{}, + defBlock: map[Reg]*Block{}, + defPos: map[Reg]int{}, + param: map[Reg]*Block{}, + paramIdx: map[Reg]int{}, + ndef: map[Reg]int{}, + width: map[Reg]int{}, + memo: map[rangeKey]valueRange{}, + busy: map[rangeKey]bool{}, + pure: map[string]int{}, + lastBar: map[string]int{}, + fwd: map[string][]string{}, + } + setWidth := func(r Reg, t Ty) { + if t != nil && IsInt(t) && !IsPointer(t) && (t.Width() == 8 || t.Width() == 16) { + u.width[r] = t.Width() + } + } + for _, p := range f.Contract.Params { + u.ndef[p.Reg]++ + setWidth(p.Reg, p.Ty) + } + for _, b := range f.Blocks { + u.blocks[b.Label] = b + for n, p := range b.Params { + u.ndef[p.Dst]++ + u.param[p.Dst] = b + u.paramIdx[p.Dst] = n + setWidth(p.Dst, p.Ty) + } + first, last := -1, -1 + for n, x := range b.Insts { + if x.Dst != NoReg { + u.ndef[x.Dst]++ + u.def[x.Dst] = x + u.defBlock[x.Dst] = b + u.defPos[x.Dst] = n + setWidth(x.Dst, x.Ty) + } + for _, r := range x.ExtraRets { + u.ndef[r] += 2 + } + if x.Asm != nil { + for _, r := range x.Asm.Outs { + u.ndef[r] += 2 + } + } + if rangeMemoryBarrier(x) { + if first < 0 { + first = n + } + last = n + } + } + u.pure[b.Label], u.lastBar[b.Label] = first, last + } + if len(f.Blocks) > 0 { + for _, p := range f.Blocks[0].Params { + u.ndef[p.Dst] += 2 // entry parameters: values from outside + } + } + for _, b := range f.Blocks { + for _, l := range b.Successors() { + if u.blocks[l] != nil { + u.preds[l] = append(u.preds[l], b) + u.fwd[b.Label] = append(u.fwd[b.Label], l) + } + } + } + for _, b := range f.Blocks { + for _, e := range u.edgeFacts(b) { + if p := u.preds[e.to]; len(p) == 1 && p[0] == b { + u.facts = append(u.facts, e) + } + } + } + return u +} + +// edgeFacts lists the compare facts of b's terminator, one per outgoing +// edge it decides: br_if on a compare (both edges, the else edge with the +// negated condition), cond_ret on a compare (the edge to Then) and br_if2 +// (lhs == rhs, lhs < rhs, lhs > rhs, unsigned). An edge whose target is +// also reached by another edge of the same terminator gets no fact. +func (u *rangeFacts) edgeFacts(b *Block) []rangeEdgeFact { + cmpOf := func(r Reg) *Inst { + if r == NoReg || u.ndef[r] != 1 { + return nil + } + c := u.def[r] + for c != nil && c.Op == OpMove && u.ndef[c.Src[0]] == 1 { + c = u.def[c.Src[0]] + } + if c == nil || c.Op != OpCmp { + return nil + } + return c + } + var out []rangeEdgeFact + add := func(x, y Reg, cond CmpCond, to string) { + switch cond { + case CmpUlt, CmpUle, CmpUgt, CmpUge, CmpEq: + out = append(out, rangeEdgeFact{x: x, y: y, cond: cond, at: b.Label, to: to}) + } + } + switch t := b.Term.(type) { + case *TermBrIf: + if c := cmpOf(t.Cond); c != nil && t.Then != t.Else { + add(c.Src[0], c.Src[1], c.Cond, t.Then) + add(c.Src[0], c.Src[1], c.Cond.Negate(), t.Else) + } + case *TermCondRet: + if c := cmpOf(t.Cond); c != nil { + add(c.Src[0], c.Src[1], c.Cond, t.Then) + } + case *TermBrIf2: + if t.Lhs != NoReg && t.Rhs != NoReg && t.Eq != t.Lt && t.Eq != t.Gt && t.Lt != t.Gt { + add(t.Lhs, t.Rhs, CmpEq, t.Eq) + add(t.Lhs, t.Rhs, CmpUlt, t.Lt) + add(t.Lhs, t.Rhs, CmpUgt, t.Gt) + } + } + return out +} + +// rangeMemoryBarrier: x may write memory (or is not known not to). Pure +// arithmetic, address formation and non-volatile loads are not barriers. +func rangeMemoryBarrier(x *Inst) bool { + if x.Asm != nil || len(x.ExtraRets) != 0 { + return true + } + switch x.Op { + case OpAdd, OpSub, OpMul, OpAnd, OpOr, OpXor, OpShl, OpShr, OpSar, + OpNeg, OpNot, OpExt, OpSext, OpTrunc, OpCmp, OpConst, OpMove, + OpAddrOf, OpField, OpPtrAdd, OpPtrBump, OpPackBytes: + return false + case OpLoad: + return x.Volatile + } + return true +} + +func (u *rangeFacts) full(r Reg) (valueRange, bool) { + w, ok := u.width[r] + if !ok { + return valueRange{}, false + } + return valueRange{0, int64(1)<= 0, provably stays at +// or below limit (and so does not wrap at i's width when limit is the width +// maximum) wherever block b executes. +func (u *rangeFacts) AddNoWrap(i Reg, k int64, b *Block, limit int64) bool { + if k < 0 { + return false + } + _, hi, ok := u.RangeAt(i, b) + return ok && hi+k <= limit +} + +func (u *rangeFacts) rangeAt(r Reg, block string, depth int) (valueRange, bool) { + fr, ok := u.full(r) + if !ok { + return valueRange{}, false + } + if u.ndef[r] != 1 || depth > rangeFactsDepth || u.dom[block] == nil { + return fr, true + } + key := rangeKey{r, block} + if v, ok := u.memo[key]; ok { + return v, true + } + if u.busy[key] { + return fr, true + } + u.busy[key] = true + v := u.defRange(r, depth) + for _, fact := range u.facts { + if u.dominates(fact.to, block) { + v = u.refine(r, v, fact, depth) + } + } + delete(u.busy, key) + if v.lo > v.hi { // contradictory facts: unreachable; keep it sound + v = fr + } + u.memo[key] = v + return v, true +} + +// defRange bounds r where it is defined (its definition block's facts +// included through the operands' ranges at that block). +func (u *rangeFacts) defRange(r Reg, depth int) valueRange { + fr, _ := u.full(r) + max := fr.hi + if pb := u.param[r]; pb != nil { + return u.paramRange(r, pb, depth) + } + x := u.def[r] + if x == nil { + return fr + } + at := u.defBlock[r].Label + opnd := func(n int) (valueRange, bool) { + if x.Src[n] == NoReg { + return valueRange{}, false + } + return u.rangeAt(x.Src[n], at, depth+1) + } + constant := func(n int) (int64, bool) { + c := u.def[x.Src[n]] + if x.Src[n] == NoReg || c == nil || c.Op != OpConst || u.ndef[x.Src[n]] != 1 || c.Ty == nil { + return 0, false + } + return maskToWidth(c.Imm, c.Ty), true + } + clip := func(v valueRange) valueRange { + if v.lo < 0 || v.hi > max || v.lo > v.hi { + return fr + } + return v + } + switch x.Op { + case OpConst: + v := maskToWidth(x.Imm, x.Ty) + return clip(valueRange{v, v}) + case OpMove: + if a, ok := opnd(0); ok && u.width[x.Src[0]] == u.width[r] { + return clip(a) + } + case OpExt: + if x.SrcTy != nil && !IsSigned(x.SrcTy) && x.SrcTy.Width() == 8 { + if a, ok := opnd(0); ok && a.hi <= 255 { + return clip(a) + } + return clip(valueRange{0, 255}) + } + case OpAnd: + a, oka := opnd(0) + b, okb := opnd(1) + hi := max + if oka && a.hi < hi { + hi = a.hi + } + if okb && b.hi < hi { + hi = b.hi + } + return clip(valueRange{0, hi}) + case OpShr: + if k, ok := constant(1); ok && k < 16 { + if a, ok := opnd(0); ok { + return clip(valueRange{a.lo >> uint(k), a.hi >> uint(k)}) + } + return clip(valueRange{0, max >> uint(k)}) + } + case OpShl, OpMul: + k, ok := constant(1) + n := 0 + if !ok && x.Op == OpMul { + k, ok = constant(0) + n = 1 + } + if !ok { + break + } + factor := k + if x.Op == OpShl { + if k > 15 { + break + } + factor = int64(1) << uint(k) + } + if a, ok := opnd(n); ok && a.hi*factor <= max { + return clip(valueRange{a.lo * factor, a.hi * factor}) + } + case OpAdd: + a, oka := opnd(0) + b, okb := opnd(1) + if oka && okb && a.hi+b.hi <= max { + return clip(valueRange{a.lo + b.lo, a.hi + b.hi}) + } + case OpSub: + a, oka := opnd(0) + b, okb := opnd(1) + if oka && okb && a.lo-b.hi >= 0 { + return clip(valueRange{a.lo - b.hi, a.hi - b.lo}) + } + } + return fr +} + +// paramRange: the union of the incoming arguments of block parameter r, +// each at its predecessor and refined by that predecessor's branch. +func (u *rangeFacts) paramRange(r Reg, pb *Block, depth int) valueRange { + fr, _ := u.full(r) + idx := u.paramIdx[r] + var out valueRange + seen := false + for _, q := range u.preds[pb.Label] { + if u.dom[q.Label] == nil { + continue // unreachable predecessor + } + var args []Reg + edges := 0 + q.Term.ForEachEdge(func(target string, a []Reg, off int) { + if target != pb.Label { + return + } + edges++ + if idx-off >= 0 && idx-off < len(a) { + args = a + args = args[idx-off : idx-off+1] + } else { + args = nil + } + }) + if edges != 1 || len(args) != 1 { + return fr + } + a := args[0] + if u.through(a) == r { + continue // the parameter passed back unchanged (an invariant) + } + if u.width[a] != u.width[r] { + return fr + } + v, ok := u.rangeAt(a, q.Label, depth+1) + if !ok { + return fr + } + for _, fact := range u.edgeFacts(q) { + if fact.to == pb.Label { + v = u.refine(a, v, fact, depth) + } + } + if !seen { + out, seen = v, true + } else { + if v.lo < out.lo { + out.lo = v.lo + } + if v.hi > out.hi { + out.hi = v.hi + } + } + } + if !seen || out.lo > out.hi { + return fr + } + return out +} + +// refine intersects v, the range of r, with what fact says about r. +func (u *rangeFacts) refine(r Reg, v valueRange, fact rangeEdgeFact, depth int) valueRange { + x, y := fact.x, fact.y + if x == NoReg || y == NoReg || u.width[x] == 0 || u.width[x] != u.width[y] || u.width[x] != u.width[r] { + return v + } + // Normalise to a < b (strict), a <= b or a == b. + var a, b Reg + strict, eq := false, false + switch fact.cond { + case CmpEq: + a, b, eq = x, y, true + case CmpUlt: + a, b, strict = x, y, true + case CmpUle: + a, b = x, y + case CmpUgt: + a, b, strict = y, x, true + case CmpUge: + a, b = y, x + default: + return v + } + // The other operand's range is taken at the block whose terminator + // decided the edge (it dominates every block the fact holds in). + at := u.blocks[fact.at] + if at == nil { + return v + } + d := int64(0) + if strict { + d = 1 + } + if u.sameValue(r, a) { + if eq { + if o, ok := u.rangeAt(b, at.Label, depth+1); ok { + v = intersectRange(v, o) + } + } else if o, ok := u.rangeAt(b, at.Label, depth+1); ok && o.hi-d < v.hi { + v.hi = o.hi - d + } + } + if u.sameValue(r, b) { + if eq { + if o, ok := u.rangeAt(a, at.Label, depth+1); ok { + v = intersectRange(v, o) + } + } else if o, ok := u.rangeAt(a, at.Label, depth+1); ok && o.lo+d > v.lo { + v.lo = o.lo + d + } + } + return v +} + +func intersectRange(a, b valueRange) valueRange { + if b.lo > a.lo { + a.lo = b.lo + } + if b.hi < a.hi { + a.hi = b.hi + } + return a +} + +// through follows single-definition moves of the same width. +func (u *rangeFacts) through(r Reg) Reg { + for n := 0; n < 16; n++ { + x := u.def[r] + if x == nil || x.Op != OpMove || u.ndef[r] != 1 || u.ndef[x.Src[0]] != 1 || u.width[x.Src[0]] != u.width[r] { + return r + } + r = x.Src[0] + } + return r +} + +// sameValue: r and s hold the same value wherever r is read after s's +// definition point (see the type comment for loads). +func (u *rangeFacts) sameValue(r, s Reg) bool { + r, s = u.through(r), u.through(s) + if r == s { + return u.ndef[r] == 1 + } + return u.sameGlobalLoad(r, s) || u.sameGlobalLoad(s, r) +} + +// sameGlobalLoad: a and b are loads of the same global symbol, a's +// definition dominates b's, and no memory barrier lies on any path from a +// to b. +func (u *rangeFacts) sameGlobalLoad(a, b Reg) bool { + la, lb := u.def[a], u.def[b] + if la == nil || lb == nil || u.ndef[a] != 1 || u.ndef[b] != 1 || la.Op != OpLoad || lb.Op != OpLoad || + la.Volatile || lb.Volatile || la.Ty == nil || lb.Ty == nil || la.Ty != lb.Ty { + return false + } + sa, sb := u.globalSym(la.Src[0]), u.globalSym(lb.Src[0]) + if sa == "" || sa != sb { + return false + } + ba, bb := u.defBlock[a], u.defBlock[b] + pa, pb := u.defPos[a], u.defPos[b] + if ba == bb { + if pa >= pb { + return false + } + for n := pa + 1; n < pb; n++ { + if rangeMemoryBarrier(ba.Insts[n]) { + return false + } + } + // A path leaving the block and coming back would pass a's + // definition again (a dominates b's position): no other path. + return true + } + if !u.dominates(ba.Label, bb.Label) { + return false + } + // a's block after a, b's block before b, and every block on a path + // between them (reachable from a's block's successors and reaching b's + // block) must be barrier-free. + if l := u.lastBar[ba.Label]; l > pa { + return false + } + if f := u.pure[bb.Label]; f >= 0 && f < pb { + return false + } + // Blocks on some path from a's block to b's block: reachable from a's + // block's successors and reaching b's block. Each must be barrier-free + // as a whole, except a's block (a path leaving it has passed a again) + // and b's block when it is not on a cycle (checked up to b above). + reach := u.closure(u.fwd[ba.Label], func(l string) []string { return u.fwd[l] }) + var into []string + for _, p := range u.preds[bb.Label] { + into = append(into, p.Label) + } + back := u.closure(into, func(l string) []string { + var out []string + for _, p := range u.preds[l] { + out = append(out, p.Label) + } + return out + }) + for l := range reach { + if !back[l] || l == ba.Label { + continue + } + if u.pure[l] >= 0 { + return false + } + } + return true +} + +func (u *rangeFacts) closure(start []string, next func(string) []string) map[string]bool { + seen := map[string]bool{} + stack := append([]string(nil), start...) + for len(stack) > 0 { + l := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if seen[l] { + continue + } + seen[l] = true + stack = append(stack, next(l)...) + } + return seen +} + +// globalSym: r is a single-definition addr_of of a global symbol. +func (u *rangeFacts) globalSym(r Reg) string { + r = u.through(r) + x := u.def[r] + if x == nil || x.Op != OpAddrOf || u.ndef[r] != 1 || x.Sym == "" { + return "" + } + return x.Sym +} + +// noWrapProof: the exact (unwrapped) sum of a word add of the constant k +// is at most hi. +type noWrapProof struct { + k, hi int64 +} + +// MarkADLNoWrapAdds records, for every 16-bit add of a constant k in 1..255 +// to a non-constant word value i in f, an upper bound on the exact sum i + k +// when rangeFacts proves one below 2^16 (f must be in SSA form). The eZ80 +// address fold (ptrAddConstantFolds) reads these proofs after allocation. +// Returns the number of adds with a proof. +func MarkADLNoWrapAdds(f *Func) int { + f.noWrapAdds = nil + if f == nil || len(f.Blocks) == 0 || verifyFunc(f) != nil { + return 0 + } + var u *rangeFacts + n := 0 + for _, b := range f.Blocks { + for _, x := range b.Insts { + if x.Op != OpAdd || x.Ty == nil || x.Ty.Width() != 16 || x.Src[0] == NoReg || x.Src[1] == NoReg || x.Src[0] == x.Src[1] { + continue + } + if u == nil { + u = newRangeFacts(f) + } + for side := 0; side < 2; side++ { + c := u.def[x.Src[side]] + if c == nil || c.Op != OpConst || u.ndef[x.Src[side]] != 1 || c.Ty == nil { + continue + } + k := maskToWidth(c.Imm, c.Ty) + if k < 1 || k > 255 { + continue + } + i := x.Src[1-side] + if ci := u.def[i]; ci != nil && ci.Op == OpConst { + continue + } + _, hi, ok := u.RangeAt(i, b) + if !ok || u.width[i] != 16 || hi+k > 0xFFFF { + continue + } + if f.noWrapAdds == nil { + f.noWrapAdds = map[*Inst]noWrapProof{} + } + f.noWrapAdds[x] = noWrapProof{k: k, hi: hi + k} + n++ + break + } + } + } + return n +} diff --git a/minzc/pkg/mir2/nowrap_range_test.go b/minzc/pkg/mir2/nowrap_range_test.go new file mode 100644 index 000000000..137ff7f33 --- /dev/null +++ b/minzc/pkg/mir2/nowrap_range_test.go @@ -0,0 +1,306 @@ +package mir2 + +import "testing" + +// nwBuilder builds small SSA functions for the no-wrap range tests. +type nwBuilder struct { + f *Func + next Reg + cur *Block +} + +func newNWBuilder(params ...Ty) (*nwBuilder, []Reg) { + b := &nwBuilder{f: &Func{Name: "f"}, next: 1} + var regs []Reg + for _, t := range params { + r := b.reg() + b.f.Contract.Params = append(b.f.Contract.Params, Param{Reg: r, Ty: t}) + regs = append(regs, r) + } + b.block("entry") + return b, regs +} + +func (b *nwBuilder) reg() Reg { r := b.next; b.next++; return r } + +func (b *nwBuilder) block(label string, params ...Ty) []Reg { + blk := &Block{Label: label} + var regs []Reg + for _, t := range params { + r := b.reg() + blk.Params = append(blk.Params, BlockParam{Dst: r, Ty: t}) + regs = append(regs, r) + } + b.f.Blocks = append(b.f.Blocks, blk) + b.cur = blk + return regs +} + +func (b *nwBuilder) emit(x *Inst) *Inst { + if x.Dst == NoReg && x.Op != OpStore { + x.Dst = b.reg() + } + b.cur.Insts = append(b.cur.Insts, x) + return x +} + +func (b *nwBuilder) c(t Ty, v int64) Reg { return b.emit(&Inst{Op: OpConst, Ty: t, Imm: v}).Dst } +func (b *nwBuilder) op(o Op, t Ty, x, y Reg) Reg { + return b.emit(&Inst{Op: o, Ty: t, Src: [2]Reg{x, y}}).Dst +} +func (b *nwBuilder) add(t Ty, x Reg, k int64) *Inst { + kr := b.c(t, k) + return b.emit(&Inst{Op: OpAdd, Ty: t, Src: [2]Reg{x, kr}}) +} +func (b *nwBuilder) cmp(cc CmpCond, x, y Reg) Reg { + return b.emit(&Inst{Op: OpCmp, Ty: TyBool, Cond: cc, Src: [2]Reg{x, y}, SrcTy: TyU16}).Dst +} +func (b *nwBuilder) load(sym string, t Ty) Reg { + a := b.emit(&Inst{Op: OpAddrOf, Ty: TyPtr, Sym: sym}).Dst + return b.emit(&Inst{Op: OpLoad, Ty: t, Src: [2]Reg{a, NoReg}}).Dst +} +func (b *nwBuilder) store(sym string, t Ty, v Reg) { + a := b.emit(&Inst{Op: OpAddrOf, Ty: TyPtr, Sym: sym}).Dst + b.emit(&Inst{Op: OpStore, Ty: t, Src: [2]Reg{a, v}}) +} +func (b *nwBuilder) jmp(to string, args ...Reg) { b.cur.Term = &TermJmp{Target: to, Args: args} } +func (b *nwBuilder) br(c Reg, then string, thenArgs []Reg, els string, elseArgs []Reg) { + b.cur.Term = &TermBrIf{Cond: c, Then: then, ThenArgs: thenArgs, Else: els, ElseArgs: elseArgs} +} +func (b *nwBuilder) ret(v Reg) { + b.cur.Term = &TermRet{Vals: []Reg{v}} + b.f.Contract.Returns = []Return{{Ty: TyU16}} +} + +// proof runs MarkADLNoWrapAdds and returns the bound recorded for add. +func (b *nwBuilder) proof(t *testing.T, add *Inst) (int64, bool) { + t.Helper() + if err := verifyFunc(b.f); err != nil { + t.Fatalf("input not SSA: %v\n%s", err, dumpF(b.f)) + } + MarkADLNoWrapAdds(b.f) + p, ok := b.f.noWrapAdds[add] + return p.hi, ok +} + +// countedLoop: for (i = 0; i < bound; i++) { add i, k } with bound computed +// by mk in the entry block. Returns the builder and the add. +func countedLoop(t *testing.T, params []Ty, k int64, mk func(b *nwBuilder, p []Reg) Reg) (*nwBuilder, *Inst) { + b, p := newNWBuilder(params...) + bound := mk(b, p) + zero := b.c(TyU16, 0) + b.jmp("head", zero) + i := b.block("head", TyU16)[0] + b.br(b.cmp(CmpUlt, i, bound), "body", nil, "exit", nil) + b.block("body") + a := b.add(TyU16, i, k) + one := b.c(TyU16, 1) + nx := b.op(OpAdd, TyU16, i, one) + b.jmp("head", nx) + b.block("exit") + b.ret(i) + return b, a +} + +func TestNoWrapRangeCountedLoops(t *testing.T) { + cases := []struct { + name string + params []Ty + k int64 + bound func(b *nwBuilder, p []Reg) Reg + want bool + hi int64 + }{ + // i < ext(byte) <= 255: i <= 254, i + 4 <= 258. + {"byte bound", []Ty{TyU8}, 4, func(b *nwBuilder, p []Reg) Reg { + return b.emit(&Inst{Op: OpExt, Ty: TyU16, SrcTy: TyU8, Src: [2]Reg{p[0], NoReg}}).Dst + }, true, 258}, + // i < 300 (constant). + {"constant bound", nil, 255, func(b *nwBuilder, p []Reg) Reg { return b.c(TyU16, 300) }, true, 299 + 255}, + // i < n & 0x0FFF. + {"masked bound", []Ty{TyU16}, 7, func(b *nwBuilder, p []Reg) Reg { + return b.op(OpAnd, TyU16, p[0], b.c(TyU16, 0x0FFF)) + }, true, 0x0FFE + 7}, + // i < n, n unknown: i <= 65534, so i + 1 <= 65535 does not wrap ... + {"unknown bound, +1", []Ty{TyU16}, 1, func(b *nwBuilder, p []Reg) Reg { return p[0] }, true, 0xFFFF}, + // ... but i + 2 can (i = 65534): refused. + {"unknown bound, +2", []Ty{TyU16}, 2, func(b *nwBuilder, p []Reg) Reg { return p[0] }, false, 0}, + // i < n >> 4. + {"shifted bound", []Ty{TyU16}, 255, func(b *nwBuilder, p []Reg) Reg { + return b.op(OpShr, TyU16, p[0], b.c(TyU8, 4)) + }, true, 0x0FFE + 255}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + b, a := countedLoop(t, tc.params, tc.k, tc.bound) + hi, ok := b.proof(t, a) + if ok != tc.want || ok && hi != tc.hi { + t.Fatalf("proof %v hi %d, want %v hi %d\n%s", ok, hi, tc.want, tc.hi, dumpF(b.f)) + } + }) + } +} + +// The #370 repro: arr[i + 1] with i a parameter. Nothing bounds i. +func TestNoWrapRangeParameterRefused(t *testing.T) { + b, p := newNWBuilder(TyU16) + a := b.add(TyU16, p[0], 1) + b.ret(a.Dst) + if _, ok := b.proof(t, a); ok { + t.Fatalf("proof for i + 1 with an unknown i\n%s", dumpF(b.f)) + } +} + +// for (i = n; i > 0; i--) { add i, 1 }: i is 1..65535 in the body; i + 1 +// wraps for i = 65535 and must be refused. +func TestNoWrapRangeDownCountRefused(t *testing.T) { + b, p := newNWBuilder(TyU16) + b.jmp("head", p[0]) + i := b.block("head", TyU16)[0] + zero := b.c(TyU16, 0) + b.br(b.cmp(CmpUgt, i, zero), "body", nil, "exit", nil) + b.block("body") + a := b.add(TyU16, i, 1) + one := b.c(TyU16, 1) + b.jmp("head", b.op(OpSub, TyU16, i, one)) + b.block("exit") + b.ret(i) + if _, ok := b.proof(t, a); ok { + t.Fatalf("proof for i + 1 under i > 0\n%s", dumpF(b.f)) + } + // The range itself: 1..65535. + u := newRangeFacts(b.f) + if lo, hi, ok := u.RangeAt(i, b.f.Blocks[2]); !ok || lo != 1 || hi != 0xFFFF { + t.Fatalf("range of i in the body = %d..%d %v, want 1..65535", lo, hi, ok) + } +} + +// A fact holds only where its edge dominates: the else side of i < 1000, +// a join after the if, and a signed compare give nothing. +func TestNoWrapRangeFactScope(t *testing.T) { + build := func(cc CmpCond, where string) (*nwBuilder, *Inst) { + b, p := newNWBuilder(TyU16) + i := p[0] + lim := b.c(TyU16, 1000) + b.br(b.cmp(cc, i, lim), "then", nil, "else", nil) + b.block("then") + var a *Inst + if where == "then" { + a = b.add(TyU16, i, 5) + } + b.jmp("join") + b.block("else") + if where == "else" { + a = b.add(TyU16, i, 5) + } + b.jmp("join") + b.block("join") + if where == "join" { + a = b.add(TyU16, i, 5) + } + b.ret(i) + return b, a + } + b, a := build(CmpUlt, "then") + if hi, ok := b.proof(t, a); !ok || hi != 999+5 { + t.Fatalf("then side of i < 1000: proof %v hi %d, want 1004", ok, hi) + } + for _, w := range []string{"else", "join"} { + b, a := build(CmpUlt, w) + if _, ok := b.proof(t, a); ok { + t.Errorf("%s side of i < 1000: unexpected proof", w) + } + } + b, a = build(CmpLt, "then") + if _, ok := b.proof(t, a); ok { + t.Errorf("signed i < 1000: unexpected proof") + } + // uge on the not-taken edge is i < 1000. + b, a = build(CmpUge, "else") + if hi, ok := b.proof(t, a); !ok || hi != 1004 { + t.Errorf("else side of i >= 1000: proof %v hi %d, want 1004", ok, hi) + } +} + +// The C lowering of +// +// count = 0; if (n > 4) count = n - 4; if (count > limit) count = limit; +// for (i = 0; i < count; ++i) ... source[i + 4] ... +// +// loads n and limit twice. count <= 65531, so i + 4 <= 65534. With a store +// to limit between its two loads, the second load is unbounded and the +// proof must go. +func TestNoWrapRangeClampedCount(t *testing.T) { + build := func(storeBetween bool) (*nwBuilder, *Inst) { + b, _ := newNWBuilder() + n := b.load("n", TyU16) + zero := b.c(TyU16, 0) + b.br(b.cmp(CmpUgt, n, b.c(TyU16, 4)), "then1", nil, "join2", []Reg{zero}) + b.block("then1") + n2 := b.load("n", TyU16) + d := b.op(OpSub, TyU16, n2, b.c(TyU16, 4)) + b.jmp("join2", d) + c1 := b.block("join2", TyU16)[0] + lim := b.load("limit", TyU16) + b.br(b.cmp(CmpUgt, c1, lim), "then3", nil, "join4", []Reg{c1}) + b.block("then3") + if storeBetween { + b.store("limit", TyU16, b.c(TyU16, 0xFFFF)) + } + lim2 := b.load("limit", TyU16) + b.jmp("join4", lim2) + count := b.block("join4", TyU16)[0] + z := b.c(TyU16, 0) + b.jmp("head", z, count) + hp := b.block("head", TyU16, TyU16) + i, cnt := hp[0], hp[1] + b.br(b.cmp(CmpUlt, i, cnt), "body", nil, "exit", nil) + b.block("body") + a := b.add(TyU16, i, 4) + one := b.c(TyU16, 1) + b.jmp("head", b.op(OpAdd, TyU16, i, one), cnt) // count is an invariant parameter + b.block("exit") + b.ret(i) + return b, a + } + b, a := build(false) + if hi, ok := b.proof(t, a); !ok || hi != 65530+4 { + t.Fatalf("clamped count: proof %v hi %d, want 65534\n%s", ok, hi, dumpF(b.f)) + } + b, a = build(true) + if _, ok := b.proof(t, a); ok { + t.Fatalf("store between the loads of limit: unexpected proof\n%s", dumpF(b.f)) + } +} + +// The fold's limit depends on how the offset is widened: zero extension +// allows i + k up to 0xFFFF, a signed offset only up to 0x7FFF. +func TestADLFoldNoWrapSignedLimit(t *testing.T) { + i, k, s, p := Reg(1), Reg(2), Reg(3), Reg(4) + add := &Inst{Op: OpAdd, Dst: s, Ty: TyU16, Src: [2]Reg{i, k}} + ptr := &Inst{Op: OpPtrAdd, Dst: p, Ty: TyPtr, Src: [2]Reg{5, s}} + f := &Func{noWrapAdds: map[*Inst]noWrapProof{add: {k: 1, hi: 0x9000}}} + info := map[Reg]RegInfo{i: {Ty: TyU16}, s: {Ty: TyU16}} + if !adlFoldNoWrap(f, info, ptr, add, i, 1) { + t.Errorf("unsigned offset, i + 1 <= 0x9000: refused") + } + if adlFoldNoWrap(f, info, ptr, add, i, 2) { + t.Errorf("proof for k = 1 used for k = 2") + } + info[i] = RegInfo{Ty: TyI16} + if adlFoldNoWrap(f, info, ptr, add, i, 1) { + t.Errorf("signed index, i + 1 up to 0x9000: folded") + } + info[i] = RegInfo{Ty: TyU16} + ptr.OffsetSign = OffsetSigned + if adlFoldNoWrap(f, info, ptr, add, i, 1) { + t.Errorf("signed offset, i + 1 up to 0x9000: folded") + } + f.noWrapAdds[add] = noWrapProof{k: 1, hi: 0x7FFF} + if !adlFoldNoWrap(f, info, ptr, add, i, 1) { + t.Errorf("signed offset, i + 1 <= 0x7FFF: refused") + } + if adlFoldNoWrap(&Func{}, info, ptr, add, i, 1) { + t.Errorf("no proof recorded: folded") + } +} diff --git a/minzc/pkg/mir2/z80codegen_inst.go b/minzc/pkg/mir2/z80codegen_inst.go index 2cf023bef..3b6e66607 100644 --- a/minzc/pkg/mir2/z80codegen_inst.go +++ b/minzc/pkg/mir2/z80codegen_inst.go @@ -1557,16 +1557,22 @@ func (g *z80cg) genInst(inst *Inst) { } } + // ADL: the base is a 24-bit pointer; the 16-bit offset's bits 16-23 + // are unspecified and must be made its zero or sign extension. An + // immediate base is loaded into HL only afterwards, so the widening's + // HL save is not needed across it (the HL it saves is dead). + widened := false + if g.address24(inst.Src[0]) && baseSym != "" && (offPair == "BC" || offPair == "DE") { + g.emitADLExtendPair(offPair, g.adlOffsetSigned(inst, offReg)) + widened = true + } // Get base into HL. if baseSym != "" { g.emitf(" LD HL, %s", baseSym) } else if base != "HL" { g.emitMov("HL", base, 16) } - - // ADL: the base is a 24-bit pointer; the 16-bit offset's bits 16-23 - // are unspecified and must be made its zero or sign extension. - if g.address24(inst.Src[0]) && (offPair == "BC" || offPair == "DE") { + if g.address24(inst.Src[0]) && !widened && (offPair == "BC" || offPair == "DE") { g.emitADLExtendPair(offPair, g.adlOffsetSigned(inst, offReg)) } // ADD HL, offPair — only BC/DE/HL/SP valid. diff --git a/minzc/pkg/mir2/z80codegen_ptradd.go b/minzc/pkg/mir2/z80codegen_ptradd.go index ae2613cc2..10d4008b6 100644 --- a/minzc/pkg/mir2/z80codegen_ptradd.go +++ b/minzc/pkg/mir2/z80codegen_ptradd.go @@ -424,13 +424,15 @@ type ptrAddFold struct { // is emitted in between); its flags must be unobserved, the base a dead // address constant (deadAddressConstants), and i a non-constant word. // -// Not under the eZ80 ADL pointer ABI: there the 16-bit sum i+k is widened -// to 24 bits before the address add, so sym + (i+k mod 2^16) and -// (sym+k) + i differ when i+k wraps (i = 0xFFFF, k = 1 reads sym+0x10000 -// instead of sym+0). The Z80 address add wraps at 16 bits too, so both -// forms agree there. +// Under the eZ80 ADL pointer ABI the 16-bit sum i+k is widened to 24 bits +// before the address add, so sym + (i+k mod 2^16) and (sym+k) + i differ +// when i+k wraps (i = 0xFFFF, k = 1 reads sym+0x10000 instead of sym+0). +// There the fold needs the no-wrap proof MarkADLNoWrapAdds recorded for the +// add (adlFoldNoWrap); without one it is not made. The Z80 address add +// wraps at 16 bits too, so both forms agree there. func ptrAddConstantFolds(f *Func, constVal map[Reg]int64) map[*Inst]ptrAddFold { - if f.mod != nil && f.mod.PointerBits == 24 { + adl := f.mod != nil && f.mod.PointerBits == 24 + if adl && len(f.noWrapAdds) == 0 { return nil } deadAddr := deadAddressConstants(f) @@ -484,6 +486,9 @@ func ptrAddConstantFolds(f *Func, constVal map[Reg]int64) map[*Inst]ptrAddFold { if uses[add.Dst] != 1 || !wordMaskFlagsUnobserved(f, add.Dst) { continue } + if adl && !adlFoldNoWrap(f, info, p, add, i, kv) { + continue + } if folds == nil { folds = map[*Inst]ptrAddFold{} } @@ -492,3 +497,35 @@ func ptrAddConstantFolds(f *Func, constVal map[Reg]int64) map[*Inst]ptrAddFold { } return folds } + +// adlFoldNoWrap: in ADL, p = ptr_add @sym, (add i, k) may be emitted as +// (sym+k) + widen(i) only when that equals sym + widen(i+k mod 2^16). The +// unfolded offset is widened by p's OffsetSign, else by the sum's type; the +// folded one by p's OffsetSign, else by i's type (adlOffsetSigned). When +// both widen with zeros, i + k <= 0xFFFF suffices; otherwise i + k <= 0x7FFF +// is required (i and i+k are then non-negative as signed words, so zero and +// sign extension agree). The bound on i + k is the proof MarkADLNoWrapAdds +// recorded for this add with this constant. +func adlFoldNoWrap(f *Func, info map[Reg]RegInfo, p, add *Inst, i Reg, k int64) bool { + proof, ok := f.noWrapAdds[add] + if !ok || proof.k != k { + return false + } + signed := func(r Reg, t Ty) bool { + switch p.OffsetSign { + case OffsetSigned: + return true + case OffsetUnsigned: + return false + } + if ri, ok := info[r]; ok && ri.Ty != nil { + t = ri.Ty + } + return t != nil && IsSigned(t) + } + limit := int64(0xFFFF) + if signed(add.Dst, add.Ty) || signed(i, nil) { + limit = 0x7FFF + } + return proof.hi <= limit +} diff --git a/minzc/pkg/mir2/z80codegen_widening_add.go b/minzc/pkg/mir2/z80codegen_widening_add.go index 73c4a65ad..47f64a6c7 100644 --- a/minzc/pkg/mir2/z80codegen_widening_add.go +++ b/minzc/pkg/mir2/z80codegen_widening_add.go @@ -22,6 +22,12 @@ func (g *z80cg) genWideningByteAdd(ext *Inst) bool { if add.Op != OpAdd || add.Ty != ext.Ty || add.ClsHard || !wordMaskFlagsUnobserved(g.fn, add.Dst) { return false } + // A folded add (ptrAddConstantFolds) emits nothing: its ptr_add reads + // the extension's home as the index, so the extension must be + // materialised there, not fused into the add. + if g.ptrAddFoldedAdd[add] { + return false + } acc := NoReg if add.Src[0] == ext.Dst { acc = add.Src[1] diff --git a/minzc/pkg/pipeline/ez80_nowrap_fold_test.go b/minzc/pkg/pipeline/ez80_nowrap_fold_test.go new file mode 100644 index 000000000..926ea9865 --- /dev/null +++ b/minzc/pkg/pipeline/ez80_nowrap_fold_test.go @@ -0,0 +1,143 @@ +package pipeline + +import ( + "strings" + "testing" + + "github.com/minz/minzc/pkg/c89" + "github.com/minz/minzc/pkg/hir" + "github.com/minz/minzc/pkg/nanz" +) + +// The eZ80 address fold sym + (i + k) -> (sym+k) + i is exact only when +// i + k does not wrap at 16 bits (#370). It is made with a no-wrap proof +// (mir2 nowrap_range.go) and refused otherwise. Each function below has an +// index that does wrap for the asserted input; arr[0] = 7 is what a +// wrapping index reads, the unsafe fold reads past the array (0). +const ez80NoWrapRefusedSrc = `global arr: [u8; 4] = [7, 8, 9, 10] + +// i < n with n unknown: i <= 65534, so i + 2 can wrap (i = 65534). +fun up_unknown(start: u16, n: u16) -> u8 { + var s: u8 = 0 + var i: u16 = start + while i < n { + s = s + arr[i + 2] + i = i + 1 + } + return s +} + +// A down-counting loop: i > 65534 leaves i = 65535, and i + 1 wraps. +fun down(n: u16) -> u8 { + var s: u8 = 0 + var i: u16 = n + while i > 65534 { + s = s + arr[i + 1] + i = i - 1 + } + return s +} + +// The bound is checked on the other branch: no fact for the access. +fun wrong_edge(i: u16) -> u8 { + if i < 1000 { + return 0 + } + return arr[i + 3] +} + +assert up_unknown(65534, 65535) == 7 +assert up_unknown(0, 2) == 19 +assert down(65535) == 7 +assert wrong_edge(65533) == 7 +assert wrong_edge(1000) == 0 +` + +func TestEZ80NoWrapFoldRefusedWhenIndexWraps(t *testing.T) { + runEZ80Native(t, "nowrap_refused.nanz", ez80NoWrapRefusedSrc) + for _, size := range []bool{false, true} { + asm := ez80TestAssembly(t, "nowrap_refused.nanz", ez80NoWrapRefusedSrc, size) + for _, folded := range []string{"arr+1", "arr+2", "arr+3"} { + if strings.Contains(asm, folded) { + t.Errorf("OptSize=%v: %q folded without a no-wrap proof", size, folded) + } + } + } +} + +// Proven cases: a counted loop under a clamped count (the C benchmark's +// window sum), a dominating compare against a constant, and a masked index. +const ez80NoWrapProvenSrc = `unsigned char source[256]; +unsigned short n, result, limit; +unsigned char small[8] = {1, 2, 3, 4, 5, 6, 7, 8}; + +static void fill(void) { + unsigned short k; + for (k = 0; k < 256; ++k) source[k] = (unsigned char)(k * 3); +} + +unsigned short window(unsigned short nn, unsigned short lim) { + unsigned short s = 0, i, count = 0; + fill(); + n = nn; + limit = lim; + if (n > 4) count = n - 4; + if (count > limit) count = limit; + for (i = 0; i < count; ++i) s += source[i + 4]; + result = s; + return s; +} + +unsigned char guarded(unsigned short i) { + if (i < 4) return small[i + 3]; + return 0; +} + +unsigned char masked(unsigned short i) { + return small[(i & 3) + 2]; +} + +// assert window(10, 100) == 117 +// assert window(10, 3) == 45 +// assert window(3, 100) == 0 +// assert guarded(0) == 4 +// assert guarded(3) == 7 +// assert guarded(65535) == 0 +// assert masked(65535) == 6 +// assert masked(4) == 3 +` + +func TestEZ80NoWrapFoldMadeWithProof(t *testing.T) { + runEZ80Native(t, "nowrap_proven.c", ez80NoWrapProvenSrc) + for _, size := range []bool{false, true} { + asm := ez80TestAssembly(t, "nowrap_proven.c", ez80NoWrapProvenSrc, size) + for _, folded := range []string{"source+4", "small+3", "small+2"} { + if !strings.Contains(asm, folded) { + t.Errorf("OptSize=%v: %q not folded although i + k cannot wrap", size, folded) + } + } + } +} + +func ez80TestAssembly(t *testing.T, name, src string, size bool) string { + t.Helper() + var hm *hir.Module + var err error + if strings.HasSuffix(name, ".c") { + hm, err = c89.CompileWithOpts(src, name, c89.CompileOpts{NoLibc: true, PointerBits: 24}) + } else { + hm, err = nanz.ParseWithOpts(src, name, nanz.ParseOpts{PointerBits: 24}) + } + if err != nil { + t.Fatal(err) + } + opt := DefaultOptions() + opt.Backend = "ez80" + opt.AssertMode = "none" + opt.OptSize = size + s, err := CompileHIRSteps(hm, opt) + if err != nil { + t.Fatalf("%s (OptSize=%v): %v", name, size, err) + } + return s.Assembly +} diff --git a/minzc/pkg/pipeline/folded_add_widening_test.go b/minzc/pkg/pipeline/folded_add_widening_test.go new file mode 100644 index 000000000..9ebc81921 --- /dev/null +++ b/minzc/pkg/pipeline/folded_add_widening_test.go @@ -0,0 +1,51 @@ +package pipeline + +import ( + "testing" + + "github.com/minz/minzc/pkg/hir" + "github.com/minz/minzc/pkg/nanz" +) + +// blob[5 + u16(k >> 3)]: the add of the constant is folded into the +// address (blob+5) + ext(k >> 3), so it emits nothing and the ptr_add reads +// the extension's home as its index. The widening byte add fused the +// extension into that add instead (the extension never reached its home), +// so the address used whatever the home's high byte held: B = 3 from the +// caller wrote blob+5+0x305 (got 0, want 90). Z80 and eZ80. +const foldedAddWideningSrc = `global blob: [u8; 64] +fun st(k: u8) -> void { + blob[5 + u16(k >> 3)] = 0x5A +} +fun t() -> u8 { + asm z80 (clob B, F) { + LD B, 3 + } + st(40) + return blob[10] +} +assert t() == 90 +` + +func TestFoldedAddIsNotFusedIntoWideningByteAdd(t *testing.T) { + for _, size := range []bool{false, true} { + hm, err := nanz.Parse(foldedAddWideningSrc, "folded_add_widening.nanz") + if err != nil { + t.Fatal(err) + } + hm.AssertStats = &hir.AssertStats{} + for i := range hm.Asserts { + hm.Asserts[i].Via = "z80" + } + opt := DefaultOptions() + opt.AssertMode = "z80" + opt.OptSize = size + if _, err := CompileHIRSteps(hm, opt); err != nil { + t.Fatalf("Z80 (OptSize=%v): %v", size, err) + } + if hm.AssertStats.Executed == 0 || hm.AssertStats.Failed != 0 { + t.Fatalf("Z80 (OptSize=%v): asserts %+v", size, *hm.AssertStats) + } + } + runEZ80Native(t, "folded_add_widening.nanz", foldedAddWideningSrc) +} diff --git a/minzc/pkg/pipeline/pipeline.go b/minzc/pkg/pipeline/pipeline.go index 7bdd7b181..77cf9c081 100644 --- a/minzc/pkg/pipeline/pipeline.go +++ b/minzc/pkg/pipeline/pipeline.go @@ -771,6 +771,15 @@ func compileMIRProductSteps(hm *hir.Module, opt Options, s Steps, splitInfo map[ } } + // eZ80 ADL: no-wrap proofs for word adds of a constant, taken while the + // MIR is still SSA (nowrap_range.go). The emitter folds sym + (i + k) + // into (sym+k) + i only with such a proof (#370). + if opt.wide24() && w39Int("MZ_W59_NOWRAP", 1) != 0 { + for _, f := range m.Funcs { + mir2.MarkADLNoWrapAdds(f) + } + } + // Register allocation: per-function PBQP, combined result for codegen. for _, f := range m.Funcs { mir2.PreallocCoalesce(f) // BUG-001 fix: union block-arg/param pairs before PBQP diff --git a/scripts/ci/pipeline_profiles.json b/scripts/ci/pipeline_profiles.json index 0cc17b498..7a7a76d70 100644 --- a/scripts/ci/pipeline_profiles.json +++ b/scripts/ci/pipeline_profiles.json @@ -165,6 +165,9 @@ "TestEZ80ConstLHSMul", "TestEZ80IndexShare", "TestEZ80PtrAddConstantFoldWraps", + "TestEZ80NoWrapFoldRefusedWhenIndexWraps", + "TestEZ80NoWrapFoldMadeWithProof", + "TestFoldedAddIsNotFusedIntoWideningByteAdd", "TestEZ80ADLWordAccess", "TestEZ80ADLWordFlagsAndExtensions", "TestEZ80AssertModeRunsInProcess", diff --git a/scripts/fuzz_nowrap.py b/scripts/fuzz_nowrap.py new file mode 100644 index 000000000..dbcbea89f --- /dev/null +++ b/scripts/fuzz_nowrap.py @@ -0,0 +1,479 @@ +#!/usr/bin/env python3 +"""Differential fuzzer for narrow index arithmetic near the 16-bit wrap, -b ez80. + +Under the eZ80 ADL pointer ABI a 16-bit index is widened to 24 bits before +the address add, so sym + (i + k) may be emitted as (sym + k) + i only when +i + k provably does not wrap (#370; mir2 nowrap_range.go). Each seed +generates one function f(p0, p1, ...) -> u16 of one to three statements over +a 32-byte array arr and a 256-byte array tab, each accessing arr[i + K] (or +tab[j + K] with a byte index) with i in a window that keeps the access in +bounds: either 0 <= i + K < 32, or i in 65536-K .. 65535, where the 16-bit +sum wraps to 0 .. K-1. The shapes: + + - up: i = start; while i < bound { s = s*3 + arr[i + K]; i += 1 }, + bound a literal, a parameter, parameter & mask, a byte + (u8 of a parameter), or the clamped count of + "c = 0; if n > K0 { c = n - K0 }; if c > lim { c = lim }"; + start a literal 0 (low window only) or a parameter; + - down: i = start; while i > bound { s = s*3 + arr[i + K]; i -= 1 }; + - guard: if i < C (or <=, >, >=, either branch) { s = s*3 + arr[i + K] }; + - mask: s = s*3 + arr[(i & M) + K]; + - ext: s = s*3 + arr[u16(b >> SH) + K] or arr[u16(b & M) + K], b a byte; + - byte: j: u8 = start; while j < bound { s = s*3 + tab[j] + tab[j + K] } + (the u8 index wraps at 256; adjacent elements, index sharing). + +Every statement's parameters get two value sets chosen by the generator (both +keep every executed access in bounds); the oracle is a Python model of the +16-bit arithmetic. The same function is emitted in C and Nanz with +`assert f(...) == V` for both sets and compiled with mz -b ez80 +--asserts-force ez80 (pkg/ez80emu), default and --Osize. The number of folded +addresses (arr+K / tab+K in the assembly) is reported to show how often the +proven path is taken. + + scripts/fuzz_nowrap.py --mz MZ --seed 0 --count 2000 -j 3 --output DIR +""" +import argparse, concurrent.futures, json, re, subprocess, sys, tempfile +from pathlib import Path + +N = 32 # arr size +SETS = 2 # assert value sets per program +MAXIT = 48 # loop iterations at most + + +def arr_val(k, mul, add): + return (k * mul + add) & 255 + + +class Gen: + def __init__(s, seed): + import random + s.r = random.Random(seed) + s.params = [] # names + s.vals = [[] for _ in range(SETS)] + s.stmts = [] # (c_lines, nanz_lines, eval_fn) + s.mul = s.r.randrange(1, 256, 2) + s.add = s.r.randrange(256) + s.tmul = s.r.randrange(1, 256, 2) + s.tadd = s.r.randrange(256) + s.locals = [] # (name, type) declared at the top + + def param(s, values): + name = f"p{len(s.params)}" + s.params.append(name) + for n in range(SETS): + s.vals[n].append(values[n] & 0xFFFF) + return name + + def window(s, k): + """A window of i values for which (i + k) & 0xFFFF < N.""" + if s.r.random() < 0.5: + return (0, N - k - 1) + return (0x10000 - k, 0xFFFF) + + def range_in(s, k, lo_hi=None): + """start, end (exclusive) inside one window, at most MAXIT apart; may be empty.""" + lo, hi = lo_hi or s.window(k) + a = s.r.randint(lo, hi) + b = min(s.r.randint(a, min(hi, a + MAXIT - 1)) + 1, 0xFFFF) + if s.r.random() < 0.1 or b < a: + b = a # empty + return a, b + + def a(s, idx): # arr element in the oracle + return arr_val(idx & 0xFFFF, s.mul, s.add) + + def t(s, idx): + return arr_val(idx & 0xFF, s.tmul, s.tadd) + + def up(s): + r = s.r + k = r.randint(1, 8) + kind = r.choice(['lit', 'param', 'mask', 'byte', 'clamp']) + lit_start = kind != 'lit' and r.random() < 0.3 + s.m = r.choice([0xFFFF, 0x7FFF, 0x00FF, 0x003F, 0xFFF8, 0x0FFF]) + s.k0 = r.randint(1, 8) + sets = [] + for n in range(SETS): + for _ in range(200): + lohi = (0, N - k - 1) if lit_start else s.window(k) + st, en = s.range_in(k, lohi) + if lit_start: + st = 0 + en = min(en, N - k) + ok, extra = s.realise_bound(kind, en, k) + if ok: + sets.append((st, en, extra)) + break + else: + ok, extra = s.realise_bound(kind, 0, k) + if not ok: + raise RuntimeError('bound 0 not realisable') + sets.append((0, 0, extra)) + if kind == 'lit': + st, en, _ = sets[0] + sets = [(st, en, None)] * SETS + i = s.fresh('i') + cs, ns = [], [] + if lit_start: + start_c = start_n = "0" + elif kind == 'lit': + start_c = start_n = str(sets[0][0]) + else: + ps = s.param([x[0] for x in sets]) + start_c = start_n = ps + bc, bn, bound_eval = s.bound_expr(kind, sets, k, cs, ns) + s.locals.append((i, 'u16')) + cs += [f"{i} = {start_c};", f"while ({i} < {bc}) {{ s = (unsigned short)(s * 3 + arr[{i} + {k}]); {i}++; }}"] + ns += [f"{i} = {start_n}", f"while {i} < {bn} {{", f" s = s * 3 + u16(arr[{i} + {k}])", f" {i} = {i} + 1", "}"] + + def ev(s_, vals, n, st0=sets, lit=lit_start, kind=kind): + st = 0 if lit else (st0[0][0] if kind == 'lit' else None) + if st is None: + st = vals[s.params.index(ps)] + b = bound_eval(vals) + i_ = st + while i_ < b: + s_ = (s_ * 3 + s.a(i_ + k)) & 0xFFFF + i_ += 1 + return s_ + s.stmts.append((cs, ns, ev)) + + def realise_bound(s, kind, en, k): + """Parameter values giving the bound value en for this kind (ok, extra).""" + r = s.r + if kind in ('lit', 'param'): + return True, en + if kind == 'mask': + m = s.m + if en & ~m: + return False, None + x = en | (r.randrange(0x10000) & ~m & 0xFFFF) + return True, (x, m) + if kind == 'byte': + if en > 255: + return False, None + return True, (en | (r.randrange(256) << 8)) + # clamp: c = n > K0 ? n - K0 : 0; c = min(c, lim); bound = c + k0 = s.k0 + if r.random() < 0.5: # the n side decides + nval = en + k0 if en > 0 else r.randint(0, k0) + if nval > 0xFFFF: + return False, None + lim = r.randint(en, 0xFFFF) + else: # lim decides + lim = en + nval = r.randint(min(en + k0, 0xFFFF), 0xFFFF) + if nval - k0 < en: + return False, None + return True, (nval, lim, k0) + + def bound_expr(s, kind, sets, k, cs, ns): + if kind == 'lit': + v = sets[0][1] + return str(v), str(v), lambda vals: v + if kind == 'param': + p = s.param([x[1] for x in sets]) + return p, p, lambda vals: vals[s.params.index(p)] + if kind == 'mask': + m = s.m + p = s.param([x[2][0] for x in sets]) + return f"({p} & {m})", f"({p} & {m})", lambda v: v[s.params.index(p)] & m + if kind == 'byte': + p = s.param([x[2] for x in sets]) + return f"(unsigned char){p}", f"u16(u8({p}))", lambda v: v[s.params.index(p)] & 0xFF + # clamp + k0 = s.k0 + pn = s.param([x[2][0] for x in sets]) + pl = s.param([x[2][1] for x in sets]) + c = s.fresh('c') + s.locals.append((c, 'u16')) + cs += [f"{c} = 0;", f"if ({pn} > {k0}) {c} = {pn} - {k0};", f"if ({c} > {pl}) {c} = {pl};"] + ns += [f"{c} = 0", f"if {pn} > {k0} {{ {c} = {pn} - {k0} }}", f"if {c} > {pl} {{ {c} = {pl} }}"] + + def ev(v): + n_, l_ = v[s.params.index(pn)], v[s.params.index(pl)] + cc = (n_ - k0) & 0xFFFF if n_ > k0 else 0 + return l_ if cc > l_ else cc + return c, c, ev + + def down(s): + r = s.r + k = r.randint(1, 8) + lit = r.random() < 0.3 + sets = [] + for n in range(SETS): + lo, hi = s.window(k) # i runs start down to bound + 1, all >= max(lo, 1) + st = r.randint(max(lo, 1), hi) + bd = r.randint(max(lo, 1, st - MAXIT) - 1, st) + sets.append((st, bd)) + if lit: + sets = [sets[0]] * SETS + i = s.fresh('i') + s.locals.append((i, 'u16')) + if lit: + st_c, bd_c = str(sets[0][0]), str(sets[0][1]) + ps = pb = None + else: + ps = s.param([x[0] for x in sets]) + pb = s.param([x[1] for x in sets]) + st_c, bd_c = ps, pb + cs = [f"{i} = {st_c};", f"while ({i} > {bd_c}) {{ s = (unsigned short)(s * 3 + arr[{i} + {k}]); {i}--; }}"] + ns = [f"{i} = {st_c}", f"while {i} > {bd_c} {{", f" s = s * 3 + u16(arr[{i} + {k}])", f" {i} = {i} - 1", "}"] + + def ev(s_, vals, n): + if lit: + st, bd = sets[0] + else: + st, bd = vals[s.params.index(ps)], vals[s.params.index(pb)] + i_ = st + while i_ > bd: + s_ = (s_ * 3 + s.a(i_ + k)) & 0xFFFF + i_ -= 1 + return s_ + s.stmts.append((cs, ns, ev)) + + def guard(s): + r = s.r + k = r.randint(1, 8) + op = r.choice(['<', '<=', '>', '>=']) + c = r.choice([4, N - k - 1, N - k, 1000, 0x7FFF, 0xFFF0, 0x10000 - k - 1, 0xFFFE]) + inside = r.random() < 0.7 # access on the branch where the compare holds + holds = {'<': lambda x: x < c, '<=': lambda x: x <= c, '>': lambda x: x > c, '>=': lambda x: x >= c}[op] + safe = lambda x: holds(x) != inside or (x + k) & 0xFFFF < N + vals = [] + for n in range(SETS): + x = None + for _ in range(200): + lo, hi = s.window(k) if r.random() < 0.8 else (0, 0xFFFF) + y = r.randint(lo, hi) + if safe(y): + x = y + break + if x is None: + x = next((y for y in (0, 0xFFFF, c, c + 1, c - 1) if 0 <= y <= 0xFFFF and safe(y)), None) + if x is None: + return s.mask() + vals.append(x) + p = s.param(vals) + acc_c = f"s = (unsigned short)(s * 3 + arr[{p} + {k}]);" + acc_n = f"s = s * 3 + u16(arr[{p} + {k}])" + if inside: + cs = [f"if ({p} {op} {c}) {{ {acc_c} }} else {{ s = (unsigned short)(s + 1); }}"] + ns = [f"if {p} {op} {c} {{", f" {acc_n}", "} else {", " s = s + 1", "}"] + else: + cs = [f"if ({p} {op} {c}) {{ s = (unsigned short)(s + 1); }} else {{ {acc_c} }}"] + ns = [f"if {p} {op} {c} {{", " s = s + 1", "} else {", f" {acc_n}", "}"] + + def ev(s_, v, n): + x = v[s.params.index(p)] + if holds(x) == inside: + return (s_ * 3 + s.a(x + k)) & 0xFFFF + return (s_ + 1) & 0xFFFF + s.stmts.append((cs, ns, ev)) + + def mask(s): + r = s.r + k = r.randint(1, 8) + m = r.choice([1, 3, 7, 15, N - k - 1, 0xFFFF]) + vals = [] + for n in range(SETS): + if m == 0xFFFF or ((m + k) >= N): + lo, hi = s.window(k) + vals.append(r.randint(lo, hi)) + else: + vals.append(r.randrange(0x10000)) + if any(((x & m) + k) & 0xFFFF >= N for x in vals): + m = 0xFFFF + vals = [r.randint(*s.window(k)) for _ in range(SETS)] + p = s.param(vals) + cs = [f"s = (unsigned short)(s * 3 + arr[({p} & {m}) + {k}]);"] + ns = [f"s = s * 3 + u16(arr[({p} & {m}) + {k}])"] + + def ev(s_, v, n): + x = v[s.params.index(p)] + return (s_ * 3 + s.a((x & m) + k)) & 0xFFFF + s.stmts.append((cs, ns, ev)) + + def ext(s): + """arr[u16(b >> sh) + K] / arr[u16(b & m) + K]: a zero-extended byte + expression as the index (the extension feeds the folded add).""" + r = s.r + k = r.randint(1, 8) + if r.random() < 0.5: + sh = r.randint(4, 7) + op_c, op_n, f = f">> {sh}", f">> {sh}", (lambda b, sh=sh: b >> sh) + else: + m = r.choice([1, 3, 7, 15, 31 - k]) + op_c, op_n, f = f"& {m}", f"& {m}", (lambda b, m=m: b & m) + p = s.param([r.randrange(0x10000) for _ in range(SETS)]) + b = s.fresh('b') + s.locals.append((b, 'u8')) + cs = [f"{b} = (unsigned char){p};", f"s = (unsigned short)(s * 3 + arr[(unsigned short)({b} {op_c}) + {k}]);"] + ns = [f"{b} = u8({p})", f"s = s * 3 + u16(arr[u16({b} {op_n}) + {k}])"] + + def ev(s_, v, n): + x = f(v[s.params.index(p)] & 255) + return (s_ * 3 + s.a(x + k)) & 0xFFFF + s.stmts.append((cs, ns, ev)) + + def byte(s): + r = s.r + k = r.randint(1, 4) + lit = r.random() < 0.3 + sets = [] + for n in range(SETS): + a = r.randint(0, 255) + b = min(255, a + r.randint(0, MAXIT)) + sets.append((a, b)) + if lit: + sets = [sets[0]] * SETS + j = s.fresh('j') + s.locals.append((j, 'u8')) + if lit: + st_c, bd_c = str(sets[0][0]), str(sets[0][1]) + ps = pb = None + st_n, bd_n = st_c, bd_c + else: + ps = s.param([x[0] for x in sets]) + pb = s.param([x[1] for x in sets]) + st_c, bd_c = f"(unsigned char){ps}", f"(unsigned char){pb}" + st_n, bd_n = f"u8({ps})", f"u8({pb})" + cs = [f"{j} = {st_c};", + f"while ({j} < {bd_c}) {{ s = (unsigned short)(s * 3 + tab[{j}] + tab[(unsigned char)({j} + {k})]); {j}++; }}"] + ns = [f"{j} = {st_n}", f"while {j} < {bd_n} {{", f" s = s * 3 + u16(tab[{j}]) + u16(tab[{j} + {k}])", f" {j} = {j} + 1", "}"] + + def ev(s_, v, n): + if lit: + a, b = sets[0] + else: + a, b = v[s.params.index(ps)] & 255, v[s.params.index(pb)] & 255 + j_ = a + while j_ < b: + s_ = (s_ * 3 + s.t(j_) + s.t(j_ + k)) & 0xFFFF + j_ += 1 + return s_ + s.stmts.append((cs, ns, ev)) + + def fresh(s, base): + s.ntmp = getattr(s, 'ntmp', 0) + 1 + return f"{base}{s.ntmp}" + + def program(s): + for _ in range(s.r.randint(1, 3)): + s.r.choice([s.up, s.up, s.down, s.guard, s.mask, s.ext, s.byte])() + if not s.params: + s.param([s.r.randrange(0x10000) for _ in range(SETS)]) + + def expected(s): + out = [] + for n in range(SETS): + acc = 0 + for (_, _, ev) in s.stmts: + acc = ev(acc, s.vals[n], n) + out.append(acc) + return out + + +def render(g, lang, want): + arr = ', '.join(str(arr_val(k, g.mul, g.add)) for k in range(N)) + tab = ', '.join(str(arr_val(k, g.tmul, g.tadd)) for k in range(256)) + if lang == 'c': + out = [f"unsigned char arr[{N}] = {{{arr}}};", f"unsigned char tab[256] = {{{tab}}};"] + sig = ', '.join(f"unsigned short {p}" for p in g.params) + out.append(f"unsigned short f({sig}) {{") + out.append(" unsigned short s = 0;") + for (name, ty) in g.locals: + out.append(f" {'unsigned char' if ty == 'u8' else 'unsigned short'} {name};") + for (cs, _, _) in g.stmts: + out += [" " + l for l in cs] + out += [" return s;", "}"] + for n in range(SETS): + out.append(f"// assert f({', '.join(str(v) for v in g.vals[n])}) == {want[n]}") + return '\n'.join(out) + '\n' + out = [f"global arr: [u8; {N}] = [{arr}]", f"global tab: [u8; 256] = [{tab}]"] + sig = ', '.join(f"{p}: u16" for p in g.params) + out.append(f"fun f({sig}) -> u16 {{") + out.append(" var s: u16 = 0") + for (name, ty) in g.locals: + out.append(f" var {name}: {ty} = 0") + for (_, ns, _) in g.stmts: + out += [" " + l for l in ns] + out += [" return s", "}"] + for n in range(SETS): + out.append(f"assert f({', '.join(str(v) for v in g.vals[n])}) == {want[n]}") + return '\n'.join(out) + '\n' + + +def run(cmd, timeout): + try: + p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors='replace', timeout=timeout) + return p.returncode, p.stdout + except subprocess.TimeoutExpired: + return None, 'timeout' + + +FOLD = re.compile(r'\b(arr|tab)\+\d+') + + +def fuzz_one(seed, mz, timeout, outdir): + g = Gen(seed) + g.program() + want = g.expected() + res = {'seed': seed, 'want': want, 'folds': 0} + failures = [] + with tempfile.TemporaryDirectory(prefix='fuzz-nowrap-') as t: + t = Path(t) + for lang, ext in (('c', '.c'), ('nanz', '.nanz')): + src = render(g, lang, want) + path = t / ('case' + ext) + path.write_text(src) + for prof in ([], ['--Osize']): + asm = t / 'out.asm' + rc, out = run([mz, str(path), '-b', 'ez80', '--asserts-force', 'ez80', '--assert-receipt', '-o', str(asm)] + prof, timeout) + ok = rc == 0 and f'executed={SETS} passed={SETS}' in out + if ok and asm.exists(): + res['folds'] += len(FOLD.findall(asm.read_text(errors='replace'))) + if not ok: + err = next((l for l in out.splitlines() if 'rror' in l or 'got' in l), out.strip()[-200:]) + failures.append({'lang': lang, 'profile': prof[0] if prof else 'default', 'error': err}) + (outdir / f"seed-{seed}{ext}").write_text(src) + res['status'] = 'pass' if not failures else 'fail' + res['failures'] = failures + return res + + +def main(): + a = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + a.add_argument('--mz', required=True) + a.add_argument('--seed', type=int, default=0) + a.add_argument('--count', type=int, default=200) + a.add_argument('-j', type=int, default=3) + a.add_argument('--timeout', type=float, default=60) + a.add_argument('--output', type=Path, required=True) + a.add_argument('--print', action='store_true', help='print the Nanz and C programs of --seed and exit') + o = a.parse_args() + o.output.mkdir(parents=True, exist_ok=True) + if o.print: + g = Gen(o.seed); g.program(); w = g.expected() + print(render(g, 'nanz', w)); print(render(g, 'c', w)) + return 0 + mz = str(Path(o.mz).resolve()) + with concurrent.futures.ThreadPoolExecutor(max_workers=o.j) as pool: + results = list(pool.map(lambda s: fuzz_one(s, mz, o.timeout, o.output), range(o.seed, o.seed + o.count))) + (o.output / 'results.json').write_text(json.dumps(results, indent=1) + '\n') + by = {} + for r in results: + by[r['status']] = by.get(r['status'], 0) + 1 + for k, v in sorted(by.items()): + print(f"{k}: {v}") + for r in results: + if r['status'] != 'pass': + print(f"seed {r['seed']}: {r['status']}: {r.get('failures')}") + print(f"folded addresses (arr+K / tab+K) in passing products: {sum(r['folds'] for r in results)}, " + f"seeds with a fold: {sum(1 for r in results if r['folds'])}") + print(f"Passing seeds: {by.get('pass', 0)}/{len(results)} (C and Nanz, default and --Osize each)") + return 0 if by.get('pass', 0) == len(results) else 1 + + +if __name__ == '__main__': + sys.exit(main())