-
Notifications
You must be signed in to change notification settings - Fork 0
/
opt.c
75 lines (61 loc) · 1.56 KB
/
opt.c
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
#include "defs.h"
#include "data.h"
#include "decl.h"
static struct ASTnode *fold2(struct ASTnode *n) {
int val, leftval, rightval;
leftval = n->left->intvalue;
rightval = n->right->intvalue;
switch (n->op) {
case A_ADD:
val = leftval + rightval;
break;
case A_SUBTRACT:
val = leftval - rightval;
break;
case A_MULTIPLY:
val = leftval * rightval;
break;
case A_DIVIDE:
if (rightval == 0)
return (n);
val = leftval / rightval;
break;
default:
return (n);
}
return (mkastleaf(A_INTLIT, n->type, NULL, val));
}
static struct ASTnode *fold1(struct ASTnode *n) {
int val;
val = n->left->intvalue;
switch (n->op) {
case A_WIDEN:
break;
case A_INVERT:
val = ~val;
break;
case A_LOGNOT:
val = !val;
break;
default:
return (n);
}
return (mkastleaf(A_INTLIT, n->type, NULL, val));
}
static struct ASTnode *fold(struct ASTnode *n) {
if (n == NULL)
return (NULL);
n->left = fold(n->left);
n->right = fold(n->right);
if (n->left && n->left->op == A_INTLIT) {
if (n->right && n->right->op == A_INTLIT)
n = fold2(n);
else
n = fold1(n);
}
return (n);
}
struct ASTnode *optimise(struct ASTnode *n) {
n = fold(n);
return (n);
}