-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsimplify.go
90 lines (87 loc) · 2.17 KB
/
simplify.go
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
package irutil
import (
"log"
"github.com/llir/llvm/ir/constant"
)
// Simplify returns an equivalent (and potentially simplified) constant to
// the constant expression.
func Simplify(c constant.Constant) constant.Constant {
switch c := c.(type) {
case *constant.ExprAdd:
x, ok := Simplify(c.X).(*constant.Int)
y, ok2 := Simplify(c.Y).(*constant.Int)
if ok && ok2 {
z := constant.NewInt(x.Typ, 0)
z.X = z.X.Add(x.X, y.X)
return z
}
return c
case *constant.ExprSub:
x, ok := Simplify(c.X).(*constant.Int)
y, ok2 := Simplify(c.Y).(*constant.Int)
if ok && ok2 {
z := constant.NewInt(x.Typ, 0)
z.X = z.X.Sub(x.X, y.X)
return z
}
return c
case *constant.ExprMul:
x, ok := Simplify(c.X).(*constant.Int)
y, ok2 := Simplify(c.Y).(*constant.Int)
if ok && ok2 {
z := constant.NewInt(x.Typ, 0)
z.X = z.X.Mul(x.X, y.X)
return z
}
return c
case *constant.ExprSDiv:
// TODO: if we need to handle signed division differently from unsigned division.
x, ok := Simplify(c.X).(*constant.Int)
y, ok2 := Simplify(c.Y).(*constant.Int)
if ok && ok2 {
z := constant.NewInt(x.Typ, 0)
z.X = z.X.Div(x.X, y.X)
return z
}
return c
case *constant.ExprUDiv:
x, ok := Simplify(c.X).(*constant.Int)
y, ok2 := Simplify(c.Y).(*constant.Int)
if ok && ok2 {
z := constant.NewInt(x.Typ, 0)
z.X = z.X.Div(x.X, y.X)
return z
}
return c
case *constant.ExprFAdd:
x, ok := Simplify(c.X).(*constant.Float)
y, ok2 := Simplify(c.Y).(*constant.Float)
if ok && ok2 {
z := constant.NewFloat(x.Typ, 0)
z.X = z.X.Add(x.X, y.X)
return z
}
return c
case *constant.ExprFSub:
x, ok := Simplify(c.X).(*constant.Float)
y, ok2 := Simplify(c.Y).(*constant.Float)
if ok && ok2 {
z := constant.NewFloat(x.Typ, 0)
z.X = z.X.Sub(x.X, y.X)
return z
}
return c
case *constant.ExprFMul:
x, ok := Simplify(c.X).(*constant.Float)
y, ok2 := Simplify(c.Y).(*constant.Float)
if ok && ok2 {
z := constant.NewFloat(x.Typ, 0)
z.X = z.X.Mul(x.X, y.X)
return z
}
return c
default:
log.Printf("support for simplifying constant expression %T not yet implemented; returning original constant expression", c)
return c
}
}