1 /* From NetBSD: optimize.c,v 1.3 1995/04/29 05:42:28 cgd Exp */
4 * Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that: (1) source code distributions
9 * retain the above copyright notice and this paragraph in its entirety, (2)
10 * distributions including binary code include the above copyright notice and
11 * this paragraph in its entirety in the documentation or other materials
12 * provided with the distribution, and (3) all advertising materials mentioning
13 * features or use of this software display the following acknowledgement:
14 * ``This product includes software developed by the University of California,
15 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
16 * the University nor the names of its contributors may be used to endorse
17 * or promote products derived from this software without specific prior
19 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
20 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
23 * Optimization module for tcpdump intermediate representation.
27 "@(#) Header: optimize.c,v 1.45 94/06/20 19:07:55 leres Exp (LBL)";
30 #include <sys/types.h>
34 #include <net/ppp_defs.h>
52 #define A_ATOM BPF_MEMWORDS
53 #define X_ATOM (BPF_MEMWORDS+1)
58 * This define is used to represent *both* the accumulator and
59 * x register in use-def computations.
60 * Currently, the use-def code assumes only one definition per instruction.
62 #define AX_ATOM N_ATOMS
65 * A flag to indicate that further optimization is needed.
66 * Iterative passes are continued until a given pass yields no
72 * A block is marked if only if its mark equals the current mark.
73 * Rather than traverse the code array, marking each item, 'cur_mark' is
74 * incremented. This automatically makes each element unmarked.
77 #define isMarked(p) ((p)->mark == cur_mark)
78 #define unMarkAll() cur_mark += 1
79 #define Mark(p) ((p)->mark = cur_mark)
81 static void opt_init(struct block *);
82 static void opt_cleanup(void);
84 static void make_marks(struct block *);
85 static void mark_code(struct block *);
87 static void intern_blocks(struct block *);
89 static int eq_slist(struct slist *, struct slist *);
91 static void find_levels_r(struct block *);
93 static void find_levels(struct block *);
94 static void find_dom(struct block *);
95 static void propedom(struct edge *);
96 static void find_edom(struct block *);
97 static void find_closure(struct block *);
98 static int atomuse(struct stmt *);
99 static int atomdef(struct stmt *);
100 static void compute_local_ud(struct block *);
101 static void find_ud(struct block *);
102 static void init_val(void);
103 static long F(int, long, long);
104 static inline void vstore(struct stmt *, long *, long, int);
105 static void opt_blk(struct block *, int);
106 static int use_conflict(struct block *, struct block *);
107 static void opt_j(struct edge *);
108 static void or_pullup(struct block *);
109 static void and_pullup(struct block *);
110 static void opt_blks(struct block *, int);
111 static inline void link_inedge(struct edge *, struct block *);
112 static void find_inedges(struct block *);
113 static void opt_root(struct block **);
114 static void opt_loop(struct block *, int);
115 static void fold_op(struct stmt *, long, long);
116 static inline struct slist *this_op(struct slist *);
117 static void opt_not(struct block *);
118 static void opt_peep(struct block *);
119 static void opt_stmt(struct stmt *, long[], int);
120 static void deadstmt(struct stmt *, struct stmt *[]);
121 static void opt_deadstores(struct block *);
122 static void opt_blk(struct block *, int);
123 static int use_conflict(struct block *, struct block *);
124 static void opt_j(struct edge *);
125 static struct block *fold_edge(struct block *, struct edge *);
126 static inline int eq_blk(struct block *, struct block *);
127 static int slength(struct slist *);
128 static int count_blocks(struct block *);
129 static void number_blks_r(struct block *);
130 static int count_stmts(struct block *);
131 static void convert_code_r(struct block *);
134 struct block **blocks;
139 * A bit vector set representation of the dominators.
140 * We round up the set size to the next power of two.
142 static int nodewords;
143 static int edgewords;
144 struct block **levels;
146 #define BITS_PER_WORD (8*sizeof(u_long))
148 * True if a is in uset {p}
150 #define SET_MEMBER(p, a) \
151 ((p)[(unsigned)(a) / BITS_PER_WORD] & (1 << ((unsigned)(a) % BITS_PER_WORD)))
156 #define SET_INSERT(p, a) \
157 (p)[(unsigned)(a) / BITS_PER_WORD] |= (1 << ((unsigned)(a) % BITS_PER_WORD))
160 * Delete 'a' from uset p.
162 #define SET_DELETE(p, a) \
163 (p)[(unsigned)(a) / BITS_PER_WORD] &= ~(1 << ((unsigned)(a) % BITS_PER_WORD))
168 #define SET_INTERSECT(a, b, n)\
170 register u_long *_x = a, *_y = b;\
171 register int _n = n;\
172 while (--_n >= 0) *_x++ &= *_y++;\
178 #define SET_SUBTRACT(a, b, n)\
180 register u_long *_x = a, *_y = b;\
181 register int _n = n;\
182 while (--_n >= 0) *_x++ &=~ *_y++;\
188 #define SET_UNION(a, b, n)\
190 register u_long *_x = a, *_y = b;\
191 register int _n = n;\
192 while (--_n >= 0) *_x++ |= *_y++;\
195 static uset all_dom_sets;
196 static uset all_closure_sets;
197 static uset all_edge_sets;
200 #define MAX(a,b) ((a)>(b)?(a):(b))
216 find_levels_r(JT(b));
217 find_levels_r(JF(b));
218 level = MAX(JT(b)->level, JF(b)->level) + 1;
222 b->link = levels[level];
227 * Level graph. The levels go from 0 at the leaves to
228 * N_LEVELS at the root. The levels[] array points to the
229 * first node of the level list, whose elements are linked
230 * with the 'link' field of the struct block.
236 memset((char *)levels, 0, n_blocks * sizeof(*levels));
242 * Find dominator relationships.
243 * Assumes graph has been leveled.
254 * Initialize sets to contain all nodes.
257 i = n_blocks * nodewords;
260 /* Root starts off empty. */
261 for (i = nodewords; --i >= 0;)
264 /* root->level is the highest level no found. */
265 for (i = root->level; i >= 0; --i) {
266 for (b = levels[i]; b; b = b->link) {
267 SET_INSERT(b->dom, b->id);
270 SET_INTERSECT(JT(b)->dom, b->dom, nodewords);
271 SET_INTERSECT(JF(b)->dom, b->dom, nodewords);
280 SET_INSERT(ep->edom, ep->id);
282 SET_INTERSECT(ep->succ->et.edom, ep->edom, edgewords);
283 SET_INTERSECT(ep->succ->ef.edom, ep->edom, edgewords);
288 * Compute edge dominators.
289 * Assumes graph has been leveled and predecessors established.
300 for (i = n_edges * edgewords; --i >= 0; )
303 /* root->level is the highest level no found. */
304 memset(root->et.edom, 0, edgewords * sizeof(*(uset)0));
305 memset(root->ef.edom, 0, edgewords * sizeof(*(uset)0));
306 for (i = root->level; i >= 0; --i) {
307 for (b = levels[i]; b != 0; b = b->link) {
315 * Find the backwards transitive closure of the flow graph. These sets
316 * are backwards in the sense that we find the set of nodes that reach
317 * a given node, not the set of nodes that can be reached by a node.
319 * Assumes graph has been leveled.
329 * Initialize sets to contain no nodes.
331 memset((char *)all_closure_sets, 0,
332 n_blocks * nodewords * sizeof(*all_closure_sets));
334 /* root->level is the highest level no found. */
335 for (i = root->level; i >= 0; --i) {
336 for (b = levels[i]; b; b = b->link) {
337 SET_INSERT(b->closure, b->id);
340 SET_UNION(JT(b)->closure, b->closure, nodewords);
341 SET_UNION(JF(b)->closure, b->closure, nodewords);
347 * Return the register number that is used by s. If A and X are both
348 * used, return AX_ATOM. If no register is used, return -1.
350 * The implementation should probably change to an array access.
356 register int c = s->code;
361 switch (BPF_CLASS(c)) {
364 return (BPF_RVAL(c) == BPF_A) ? A_ATOM :
365 (BPF_RVAL(c) == BPF_X) ? X_ATOM : -1;
369 return (BPF_MODE(c) == BPF_IND) ? X_ATOM :
370 (BPF_MODE(c) == BPF_MEM) ? s->k : -1;
380 if (BPF_SRC(c) == BPF_X)
385 return BPF_MISCOP(c) == BPF_TXA ? X_ATOM : A_ATOM;
392 * Return the register number that is defined by 's'. We assume that
393 * a single stmt cannot define more than one register. If no register
394 * is defined, return -1.
396 * The implementation should probably change to an array access.
405 switch (BPF_CLASS(s->code)) {
419 return BPF_MISCOP(s->code) == BPF_TAX ? X_ATOM : A_ATOM;
429 atomset def = 0, use = 0, kill = 0;
432 for (s = b->stmts; s; s = s->next) {
433 if (s->s.code == NOP)
435 atom = atomuse(&s->s);
437 if (atom == AX_ATOM) {
438 if (!ATOMELEM(def, X_ATOM))
439 use |= ATOMMASK(X_ATOM);
440 if (!ATOMELEM(def, A_ATOM))
441 use |= ATOMMASK(A_ATOM);
443 else if (atom < N_ATOMS) {
444 if (!ATOMELEM(def, atom))
445 use |= ATOMMASK(atom);
450 atom = atomdef(&s->s);
452 if (!ATOMELEM(use, atom))
453 kill |= ATOMMASK(atom);
454 def |= ATOMMASK(atom);
457 if (!ATOMELEM(def, A_ATOM) && BPF_CLASS(b->s.code) == BPF_JMP)
458 use |= ATOMMASK(A_ATOM);
466 * Assume graph is already leveled.
476 * root->level is the highest level no found;
477 * count down from there.
479 maxlevel = root->level;
480 for (i = maxlevel; i >= 0; --i)
481 for (p = levels[i]; p; p = p->link) {
486 for (i = 1; i <= maxlevel; ++i) {
487 for (p = levels[i]; p; p = p->link) {
488 p->out_use |= JT(p)->in_use | JF(p)->in_use;
489 p->in_use |= p->out_use &~ p->kill;
495 * These data structures are used in a Cocke and Shwarz style
496 * value numbering scheme. Since the flowgraph is acyclic,
497 * exit values can be propagated from a node's predecessors
498 * provided it is uniquely defined.
504 struct valnode *next;
508 static struct valnode *hashtbl[MODULUS];
512 /* Integer constants mapped with the load immediate opcode. */
513 #define K(i) F(BPF_LD|BPF_IMM|BPF_W, i, 0L)
520 struct vmapinfo *vmap;
521 struct valnode *vnode_base;
522 struct valnode *next_vnode;
528 next_vnode = vnode_base;
529 memset((char *)vmap, 0, maxval * sizeof(*vmap));
530 memset((char *)hashtbl, 0, sizeof hashtbl);
533 /* Because we really don't have an IR, this stuff is a little messy. */
543 hash = (u_int)code ^ (v0 << 4) ^ (v1 << 8);
546 for (p = hashtbl[hash]; p; p = p->next)
547 if (p->code == code && p->v0 == v0 && p->v1 == v1)
551 if (BPF_MODE(code) == BPF_IMM &&
552 (BPF_CLASS(code) == BPF_LD || BPF_CLASS(code) == BPF_LDX)) {
553 vmap[val].const_val = v0;
554 vmap[val].is_const = 1;
561 p->next = hashtbl[hash];
568 vstore(s, valp, newval, alter)
574 if (alter && *valp == newval)
587 a = vmap[v0].const_val;
588 b = vmap[v1].const_val;
590 switch (BPF_OP(s->code)) {
605 bpf_error("division by zero");
633 s->code = BPF_LD|BPF_IMM;
637 static inline struct slist *
641 while (s != 0 && s->s.code == NOP)
650 struct block *tmp = JT(b);
661 struct slist *next, *last;
674 next = this_op(s->next);
680 * st M[k] --> st M[k]
683 if (s->s.code == BPF_ST &&
684 next->s.code == (BPF_LDX|BPF_MEM) &&
685 s->s.k == next->s.k) {
687 next->s.code = BPF_MISC|BPF_TAX;
693 if (s->s.code == (BPF_LD|BPF_IMM) &&
694 next->s.code == (BPF_MISC|BPF_TAX)) {
695 s->s.code = BPF_LDX|BPF_IMM;
696 next->s.code = BPF_MISC|BPF_TXA;
700 * This is an ugly special case, but it happens
701 * when you say tcp[k] or udp[k] where k is a constant.
703 if (s->s.code == (BPF_LD|BPF_IMM)) {
704 struct slist *add, *tax, *ild;
707 * Check that X isn't used on exit from this
708 * block (which the optimizer might cause).
709 * We know the code generator won't generate
710 * any local dependencies.
712 if (ATOMELEM(b->out_use, X_ATOM))
715 if (next->s.code != (BPF_LDX|BPF_MSH|BPF_B))
718 add = this_op(next->next);
719 if (add == 0 || add->s.code != (BPF_ALU|BPF_ADD|BPF_X))
722 tax = this_op(add->next);
723 if (tax == 0 || tax->s.code != (BPF_MISC|BPF_TAX))
726 ild = this_op(tax->next);
727 if (ild == 0 || BPF_CLASS(ild->s.code) != BPF_LD ||
728 BPF_MODE(ild->s.code) != BPF_IND)
731 * XXX We need to check that X is not
732 * subsequently used. We know we can eliminate the
733 * accumulator modifications since it is defined
734 * by the last stmt of this sequence.
736 * We want to turn this sequence:
739 * (005) ldxms [14] {next} -- optional
742 * (008) ild [x+0] {ild}
744 * into this sequence:
762 * If we have a subtract to do a comparison, and the X register
763 * is a known constant, we can merge this value into the
766 if (last->s.code == (BPF_ALU|BPF_SUB|BPF_X) &&
767 !ATOMELEM(b->out_use, A_ATOM)) {
768 val = b->val[X_ATOM];
769 if (vmap[val].is_const) {
770 b->s.k += vmap[val].const_val;
773 } else if (b->s.k == 0) {
779 b->s.code = BPF_CLASS(b->s.code) | BPF_OP(b->s.code) |
785 * Likewise, a constant subtract can be simplified.
787 else if (last->s.code == (BPF_ALU|BPF_SUB|BPF_K) &&
788 !ATOMELEM(b->out_use, A_ATOM)) {
797 if (last->s.code == (BPF_ALU|BPF_AND|BPF_K) &&
798 !ATOMELEM(b->out_use, A_ATOM) && b->s.k == 0) {
800 b->s.code = BPF_JMP|BPF_K|BPF_JSET;
806 * If the accumulator is a known constant, we can compute the
809 val = b->val[A_ATOM];
810 if (vmap[val].is_const && BPF_SRC(b->s.code) == BPF_K) {
811 v = vmap[val].const_val;
812 switch (BPF_OP(b->s.code)) {
843 * Compute the symbolic value of expression of 's', and update
844 * anything it defines in the value table 'val'. If 'alter' is true,
845 * do various optimizations. This code would be cleaner if symbolic
846 * evaluation and code transformations weren't folded together.
849 opt_stmt(s, val, alter)
859 case BPF_LD|BPF_ABS|BPF_W:
860 case BPF_LD|BPF_ABS|BPF_H:
861 case BPF_LD|BPF_ABS|BPF_B:
862 v = F(s->code, s->k, 0L);
863 vstore(s, &val[A_ATOM], v, alter);
866 case BPF_LD|BPF_IND|BPF_W:
867 case BPF_LD|BPF_IND|BPF_H:
868 case BPF_LD|BPF_IND|BPF_B:
870 if (alter && vmap[v].is_const) {
871 s->code = BPF_LD|BPF_ABS|BPF_SIZE(s->code);
872 s->k += vmap[v].const_val;
873 v = F(s->code, s->k, 0L);
877 v = F(s->code, s->k, v);
878 vstore(s, &val[A_ATOM], v, alter);
882 v = F(s->code, 0L, 0L);
883 vstore(s, &val[A_ATOM], v, alter);
888 vstore(s, &val[A_ATOM], v, alter);
891 case BPF_LDX|BPF_IMM:
893 vstore(s, &val[X_ATOM], v, alter);
896 case BPF_LDX|BPF_MSH|BPF_B:
897 v = F(s->code, s->k, 0L);
898 vstore(s, &val[X_ATOM], v, alter);
901 case BPF_ALU|BPF_NEG:
902 if (alter && vmap[val[A_ATOM]].is_const) {
903 s->code = BPF_LD|BPF_IMM;
904 s->k = -vmap[val[A_ATOM]].const_val;
905 val[A_ATOM] = K(s->k);
908 val[A_ATOM] = F(s->code, val[A_ATOM], 0L);
911 case BPF_ALU|BPF_ADD|BPF_K:
912 case BPF_ALU|BPF_SUB|BPF_K:
913 case BPF_ALU|BPF_MUL|BPF_K:
914 case BPF_ALU|BPF_DIV|BPF_K:
915 case BPF_ALU|BPF_AND|BPF_K:
916 case BPF_ALU|BPF_OR|BPF_K:
917 case BPF_ALU|BPF_LSH|BPF_K:
918 case BPF_ALU|BPF_RSH|BPF_K:
919 op = BPF_OP(s->code);
922 if (op == BPF_ADD || op == BPF_SUB ||
923 op == BPF_LSH || op == BPF_RSH ||
928 if (op == BPF_MUL || op == BPF_AND) {
929 s->code = BPF_LD|BPF_IMM;
930 val[A_ATOM] = K(s->k);
934 if (vmap[val[A_ATOM]].is_const) {
935 fold_op(s, val[A_ATOM], K(s->k));
936 val[A_ATOM] = K(s->k);
940 val[A_ATOM] = F(s->code, val[A_ATOM], K(s->k));
943 case BPF_ALU|BPF_ADD|BPF_X:
944 case BPF_ALU|BPF_SUB|BPF_X:
945 case BPF_ALU|BPF_MUL|BPF_X:
946 case BPF_ALU|BPF_DIV|BPF_X:
947 case BPF_ALU|BPF_AND|BPF_X:
948 case BPF_ALU|BPF_OR|BPF_X:
949 case BPF_ALU|BPF_LSH|BPF_X:
950 case BPF_ALU|BPF_RSH|BPF_X:
951 op = BPF_OP(s->code);
952 if (alter && vmap[val[X_ATOM]].is_const) {
953 if (vmap[val[A_ATOM]].is_const) {
954 fold_op(s, val[A_ATOM], val[X_ATOM]);
955 val[A_ATOM] = K(s->k);
958 s->code = BPF_ALU|BPF_K|op;
959 s->k = vmap[val[X_ATOM]].const_val;
962 F(s->code, val[A_ATOM], K(s->k));
967 * Check if we're doing something to an accumulator
968 * that is 0, and simplify. This may not seem like
969 * much of a simplification but it could open up further
971 * XXX We could also check for mul by 1, and -1, etc.
973 if (alter && vmap[val[A_ATOM]].is_const
974 && vmap[val[A_ATOM]].const_val == 0) {
975 if (op == BPF_ADD || op == BPF_OR ||
976 op == BPF_LSH || op == BPF_RSH || op == BPF_SUB) {
977 s->code = BPF_MISC|BPF_TXA;
978 vstore(s, &val[A_ATOM], val[X_ATOM], alter);
981 else if (op == BPF_MUL || op == BPF_DIV ||
983 s->code = BPF_LD|BPF_IMM;
985 vstore(s, &val[A_ATOM], K(s->k), alter);
988 else if (op == BPF_NEG) {
993 val[A_ATOM] = F(s->code, val[A_ATOM], val[X_ATOM]);
996 case BPF_MISC|BPF_TXA:
997 vstore(s, &val[A_ATOM], val[X_ATOM], alter);
1000 case BPF_LD|BPF_MEM:
1002 if (alter && vmap[v].is_const) {
1003 s->code = BPF_LD|BPF_IMM;
1004 s->k = vmap[v].const_val;
1007 vstore(s, &val[A_ATOM], v, alter);
1010 case BPF_MISC|BPF_TAX:
1011 vstore(s, &val[X_ATOM], val[A_ATOM], alter);
1014 case BPF_LDX|BPF_MEM:
1016 if (alter && vmap[v].is_const) {
1017 s->code = BPF_LDX|BPF_IMM;
1018 s->k = vmap[v].const_val;
1021 vstore(s, &val[X_ATOM], v, alter);
1025 vstore(s, &val[s->k], val[A_ATOM], alter);
1029 vstore(s, &val[s->k], val[X_ATOM], alter);
1036 register struct stmt *s;
1037 register struct stmt *last[];
1043 if (atom == AX_ATOM) {
1054 last[atom]->code = NOP;
1062 register struct block *b;
1064 register struct slist *s;
1066 struct stmt *last[N_ATOMS];
1068 memset((char *)last, 0, sizeof last);
1070 for (s = b->stmts; s != 0; s = s->next)
1071 deadstmt(&s->s, last);
1072 deadstmt(&b->s, last);
1074 for (atom = 0; atom < N_ATOMS; ++atom)
1075 if (last[atom] && !ATOMELEM(b->out_use, atom)) {
1076 last[atom]->code = NOP;
1082 opt_blk(b, do_stmts)
1092 * Initialize the atom values.
1093 * If we have no predecessors, everything is undefined.
1094 * Otherwise, we inherent our values from our predecessors.
1095 * If any register has an ambiguous value (i.e. control paths are
1096 * merging) give it the undefined value of 0.
1100 memset((char *)b->val, 0, sizeof(b->val));
1102 memcpy((char *)b->val, (char *)p->pred->val, sizeof(b->val));
1103 while ((p = p->next) != NULL) {
1104 for (i = 0; i < N_ATOMS; ++i)
1105 if (b->val[i] != p->pred->val[i])
1109 aval = b->val[A_ATOM];
1110 for (s = b->stmts; s; s = s->next)
1111 opt_stmt(&s->s, b->val, do_stmts);
1114 * This is a special case: if we don't use anything from this
1115 * block, and we load the accumulator with value that is
1116 * already there, eliminate all the statements.
1118 if (do_stmts && b->out_use == 0 && aval != 0 &&
1119 b->val[A_ATOM] == aval)
1126 * Set up values for branch optimizer.
1128 if (BPF_SRC(b->s.code) == BPF_K)
1129 b->oval = K(b->s.k);
1131 b->oval = b->val[X_ATOM];
1132 b->et.code = b->s.code;
1133 b->ef.code = -b->s.code;
1137 * Return true if any register that is used on exit from 'succ', has
1138 * an exit value that is different from the corresponding exit value
1142 use_conflict(b, succ)
1143 struct block *b, *succ;
1146 atomset use = succ->out_use;
1151 for (atom = 0; atom < N_ATOMS; ++atom)
1152 if (ATOMELEM(use, atom))
1153 if (b->val[atom] != succ->val[atom])
1158 static struct block *
1159 fold_edge(child, ep)
1160 struct block *child;
1164 int aval0, aval1, oval0, oval1;
1165 int code = ep->code;
1173 if (child->s.code != code)
1176 aval0 = child->val[A_ATOM];
1177 oval0 = child->oval;
1178 aval1 = ep->pred->val[A_ATOM];
1179 oval1 = ep->pred->oval;
1186 * The operands are identical, so the
1187 * result is true if a true branch was
1188 * taken to get here, otherwise false.
1190 return sense ? JT(child) : JF(child);
1192 if (sense && code == (BPF_JMP|BPF_JEQ|BPF_K))
1194 * At this point, we only know the comparison if we
1195 * came down the true branch, and it was an equality
1196 * comparison with a constant. We rely on the fact that
1197 * distinct constants have distinct value numbers.
1209 register struct block *target;
1211 if (JT(ep->succ) == 0)
1214 if (JT(ep->succ) == JF(ep->succ)) {
1216 * Common branch targets can be eliminated, provided
1217 * there is no data dependency.
1219 if (!use_conflict(ep->pred, ep->succ->et.succ)) {
1221 ep->succ = JT(ep->succ);
1225 * For each edge dominator that matches the successor of this
1226 * edge, promote the edge successor to the its grandchild.
1228 * XXX We violate the set abstraction here in favor a reasonably
1232 for (i = 0; i < edgewords; ++i) {
1233 register u_long x = ep->edom[i];
1238 k += i * BITS_PER_WORD;
1240 target = fold_edge(ep->succ, edges[k]);
1242 * Check that there is no data dependency between
1243 * nodes that will be violated if we move the edge.
1245 if (target != 0 && !use_conflict(ep->pred, target)) {
1248 if (JT(target) != 0)
1250 * Start over unless we hit a leaf.
1266 struct block **diffp, **samep;
1274 * Make sure each predecessor loads the same value.
1277 val = ep->pred->val[A_ATOM];
1278 for (ep = ep->next; ep != 0; ep = ep->next)
1279 if (val != ep->pred->val[A_ATOM])
1282 if (JT(b->in_edges->pred) == b)
1283 diffp = &JT(b->in_edges->pred);
1285 diffp = &JF(b->in_edges->pred);
1292 if (JT(*diffp) != JT(b))
1295 if (!SET_MEMBER((*diffp)->dom, b->id))
1298 if ((*diffp)->val[A_ATOM] != val)
1301 diffp = &JF(*diffp);
1304 samep = &JF(*diffp);
1309 if (JT(*samep) != JT(b))
1312 if (!SET_MEMBER((*samep)->dom, b->id))
1315 if ((*samep)->val[A_ATOM] == val)
1318 /* XXX Need to check that there are no data dependencies
1319 between dp0 and dp1. Currently, the code generator
1320 will not produce such dependencies. */
1321 samep = &JF(*samep);
1324 /* XXX This doesn't cover everything. */
1325 for (i = 0; i < N_ATOMS; ++i)
1326 if ((*samep)->val[i] != pred->val[i])
1329 /* Pull up the node. */
1335 * At the top of the chain, each predecessor needs to point at the
1336 * pulled up node. Inside the chain, there is only one predecessor
1340 for (ep = b->in_edges; ep != 0; ep = ep->next) {
1341 if (JT(ep->pred) == b)
1342 JT(ep->pred) = pull;
1344 JF(ep->pred) = pull;
1359 struct block **diffp, **samep;
1367 * Make sure each predecessor loads the same value.
1369 val = ep->pred->val[A_ATOM];
1370 for (ep = ep->next; ep != 0; ep = ep->next)
1371 if (val != ep->pred->val[A_ATOM])
1374 if (JT(b->in_edges->pred) == b)
1375 diffp = &JT(b->in_edges->pred);
1377 diffp = &JF(b->in_edges->pred);
1384 if (JF(*diffp) != JF(b))
1387 if (!SET_MEMBER((*diffp)->dom, b->id))
1390 if ((*diffp)->val[A_ATOM] != val)
1393 diffp = &JT(*diffp);
1396 samep = &JT(*diffp);
1401 if (JF(*samep) != JF(b))
1404 if (!SET_MEMBER((*samep)->dom, b->id))
1407 if ((*samep)->val[A_ATOM] == val)
1410 /* XXX Need to check that there are no data dependencies
1411 between diffp and samep. Currently, the code generator
1412 will not produce such dependencies. */
1413 samep = &JT(*samep);
1416 /* XXX This doesn't cover everything. */
1417 for (i = 0; i < N_ATOMS; ++i)
1418 if ((*samep)->val[i] != pred->val[i])
1421 /* Pull up the node. */
1427 * At the top of the chain, each predecessor needs to point at the
1428 * pulled up node. Inside the chain, there is only one predecessor
1432 for (ep = b->in_edges; ep != 0; ep = ep->next) {
1433 if (JT(ep->pred) == b)
1434 JT(ep->pred) = pull;
1436 JF(ep->pred) = pull;
1446 opt_blks(root, do_stmts)
1454 maxlevel = root->level;
1455 for (i = maxlevel; i >= 0; --i)
1456 for (p = levels[i]; p; p = p->link)
1457 opt_blk(p, do_stmts);
1461 * No point trying to move branches; it can't possibly
1462 * make a difference at this point.
1466 for (i = 1; i <= maxlevel; ++i) {
1467 for (p = levels[i]; p; p = p->link) {
1472 for (i = 1; i <= maxlevel; ++i) {
1473 for (p = levels[i]; p; p = p->link) {
1481 link_inedge(parent, child)
1482 struct edge *parent;
1483 struct block *child;
1485 parent->next = child->in_edges;
1486 child->in_edges = parent;
1496 for (i = 0; i < n_blocks; ++i)
1497 blocks[i]->in_edges = 0;
1500 * Traverse the graph, adding each edge to the predecessor
1501 * list of its successors. Skip the leaves (i.e. level 0).
1503 for (i = root->level; i > 0; --i) {
1504 for (b = levels[i]; b != 0; b = b->link) {
1505 link_inedge(&b->et, JT(b));
1506 link_inedge(&b->ef, JF(b));
1515 struct slist *tmp, *s;
1519 while (BPF_CLASS((*b)->s.code) == BPF_JMP && JT(*b) == JF(*b))
1529 opt_loop(root, do_stmts)
1546 opt_blks(root, do_stmts);
1555 * Optimize the filter code in its dag representation.
1559 struct block **rootp;
1568 intern_blocks(root);
1579 if (BPF_CLASS(p->s.code) != BPF_RET) {
1587 * Mark code array such that isMarked(i) is true
1588 * only for nodes that are alive.
1599 * True iff the two stmt lists load the same value from the packet into
1604 struct slist *x, *y;
1607 while (x && x->s.code == NOP)
1609 while (y && y->s.code == NOP)
1615 if (x->s.code != y->s.code || x->s.k != y->s.k)
1624 struct block *b0, *b1;
1626 if (b0->s.code == b1->s.code &&
1627 b0->s.k == b1->s.k &&
1628 b0->et.succ == b1->et.succ &&
1629 b0->ef.succ == b1->ef.succ)
1630 return eq_slist(b0->stmts, b1->stmts);
1643 for (i = 0; i < n_blocks; ++i)
1644 blocks[i]->link = 0;
1648 for (i = n_blocks - 1; --i >= 0; ) {
1649 if (!isMarked(blocks[i]))
1651 for (j = i + 1; j < n_blocks; ++j) {
1652 if (!isMarked(blocks[j]))
1654 if (eq_blk(blocks[i], blocks[j])) {
1655 blocks[i]->link = blocks[j]->link ?
1656 blocks[j]->link : blocks[j];
1661 for (i = 0; i < n_blocks; ++i) {
1667 JT(p) = JT(p)->link;
1671 JF(p) = JF(p)->link;
1681 free((void *)vnode_base);
1683 free((void *)edges);
1684 free((void *)space);
1685 free((void *)levels);
1686 free((void *)blocks);
1690 * Return the number of stmts in 's'.
1698 for (; s; s = s->next)
1699 if (s->s.code != NOP)
1705 * Return the number of nodes reachable by 'p'.
1706 * All nodes should be initially unmarked.
1712 if (p == 0 || isMarked(p))
1715 return count_blocks(JT(p)) + count_blocks(JF(p)) + 1;
1719 * Do a depth first search on the flow graph, numbering the
1720 * the basic blocks, and entering them into the 'blocks' array.`
1728 if (p == 0 || isMarked(p))
1736 number_blks_r(JT(p));
1737 number_blks_r(JF(p));
1741 * Return the number of stmts in the flowgraph reachable by 'p'.
1742 * The nodes should be unmarked before calling.
1750 if (p == 0 || isMarked(p))
1753 n = count_stmts(JT(p)) + count_stmts(JF(p));
1754 return slength(p->stmts) + n + 1;
1758 * Allocate memory. All allocation is done before optimization
1759 * is begun. A linear bound on the size of all data structures is computed
1760 * from the total number of blocks and/or statements.
1767 int i, n, max_stmts;
1770 * First, count the blocks, so we can malloc an array to map
1771 * block number to block. Then, put the blocks into the array.
1774 n = count_blocks(root);
1775 blocks = (struct block **)malloc(n * sizeof(*blocks));
1778 number_blks_r(root);
1780 n_edges = 2 * n_blocks;
1781 edges = (struct edge **)malloc(n_edges * sizeof(*edges));
1784 * The number of levels is bounded by the number of nodes.
1786 levels = (struct block **)malloc(n_blocks * sizeof(*levels));
1788 edgewords = n_edges / (8 * sizeof(u_long)) + 1;
1789 nodewords = n_blocks / (8 * sizeof(u_long)) + 1;
1792 space = (u_long *)malloc(2 * n_blocks * nodewords * sizeof(*space)
1793 + n_edges * edgewords * sizeof(*space));
1796 for (i = 0; i < n; ++i) {
1800 all_closure_sets = p;
1801 for (i = 0; i < n; ++i) {
1802 blocks[i]->closure = p;
1806 for (i = 0; i < n; ++i) {
1807 register struct block *b = blocks[i];
1815 b->ef.id = n_blocks + i;
1816 edges[n_blocks + i] = &b->ef;
1821 for (i = 0; i < n; ++i)
1822 max_stmts += slength(blocks[i]->stmts) + 1;
1824 * We allocate at most 3 value numbers per statement,
1825 * so this is an upper bound on the number of valnodes
1828 maxval = 3 * max_stmts;
1829 vmap = (struct vmapinfo *)malloc(maxval * sizeof(*vmap));
1830 vnode_base = (struct valnode *)malloc(maxval * sizeof(*vmap));
1834 * Some pointers used to convert the basic block form of the code,
1835 * into the array form that BPF requires. 'fstart' will point to
1836 * the malloc'd array while 'ftail' is used during the recursive traversal.
1838 static struct bpf_insn *fstart;
1839 static struct bpf_insn *ftail;
1849 struct bpf_insn *dst;
1854 if (p == 0 || isMarked(p))
1858 convert_code_r(JF(p));
1859 convert_code_r(JT(p));
1861 slen = slength(p->stmts);
1862 dst = ftail -= slen + 1;
1864 p->offset = dst - fstart;
1866 for (src = p->stmts; src; src = src->next) {
1867 if (src->s.code == NOP)
1869 dst->code = (u_short)src->s.code;
1874 bids[dst - fstart] = p->id + 1;
1876 dst->code = (u_short)p->s.code;
1879 off = JT(p)->offset - (p->offset + slen) - 1;
1881 bpf_error("long jumps not supported");
1883 off = JF(p)->offset - (p->offset + slen) - 1;
1885 bpf_error("long jumps not supported");
1892 * Convert flowgraph intermediate representation to the
1893 * BPF array representation. Set *lenp to the number of instructions.
1896 icode_to_fcode(root, lenp)
1901 struct bpf_insn *fp;
1904 n = *lenp = count_stmts(root);
1906 fp = (struct bpf_insn *)malloc(sizeof(*fp) * n);
1907 memset((char *)fp, 0, sizeof(*fp) * n);
1912 convert_code_r(root);
1921 struct bpf_program f;
1923 memset(bids, 0, sizeof bids);
1924 f.bf_insns = icode_to_fcode(root, &f.bf_len);
1927 free((char *)f.bf_insns);