Skip to content

Commit

Permalink
WIP: circuit rewrite patterns.
Browse files Browse the repository at this point in the history
  • Loading branch information
markkurossi committed May 8, 2024
1 parent ab9a4cd commit 9110e83
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
52 changes: 52 additions & 0 deletions compiler/circuits/rewrite.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
//
// Copyright (c) 2024 Markku Rossi
//
// All rights reserved.
//

package circuits

import (
"fmt"
"time"

"github.com/markkurossi/mpc/circuit"
)

// Rewrite applies rewrite patterns to the circuit.
func (cc *Compiler) Rewrite() {
var stats circuit.Stats

start := time.Now()

for _, g := range cc.Gates {
switch g.Op {
case circuit.AND:
// AND(A,A) = A
if g.A == g.B && g.O.NumOutputs() > 0 {
stats[g.Op]++
g.ShortCircuit(g.A)
}
case circuit.OR:
// OR(A,A) = A
if g.A == g.B && g.O.NumOutputs() > 0 {
stats[g.Op]++
g.ShortCircuit(g.A)
}
case circuit.XOR:
// XOR(A,A) = 0
if g.A == g.B && g.O.NumOutputs() > 0 {
stats[g.Op]++
g.O.SetValue(Zero)
}
}
}

elapsed := time.Since(start)

if cc.Params.Diagnostics {
fmt.Printf(" - Rewrite: %12s: %d/%d (%.2f%%)\n",
elapsed, stats.Count(), len(cc.Gates),
float64(stats.Count())/float64(len(cc.Gates))*100)
}
}
3 changes: 2 additions & 1 deletion compiler/ssa/circuitgen.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//
// Copyright (c) 2020-2023 Markku Rossi
// Copyright (c) 2020-2024 Markku Rossi
//
// All rights reserved.
//
Expand Down Expand Up @@ -44,6 +44,7 @@ func (prog *Program) CompileCircuit(params *utils.Params) (
fmt.Printf("Compiling circuit...\n")
}
cc.ConstPropagate()
cc.Rewrite()
cc.ShortCircuitXORZero()
if params.OptPruneGates {
orig := float64(len(cc.Gates))
Expand Down

0 comments on commit 9110e83

Please sign in to comment.