2 * Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994, 1995, 1996
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that: (1) source code distributions
7 * retain the above copyright notice and this paragraph in its entirety, (2)
8 * distributions including binary code include the above copyright notice and
9 * this paragraph in its entirety in the documentation or other materials
10 * provided with the distribution, and (3) all advertising materials mentioning
11 * features or use of this software display the following acknowledgement:
12 * ``This product includes software developed by the University of California,
13 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14 * the University nor the names of its contributors may be used to endorse
15 * or promote products derived from this software without specific prior
17 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
21 * Optimization module for tcpdump intermediate representation.
25 "@(#) $Header: optimize.c,v 1.59 96/07/15 00:48:49 leres Exp $ (LBL)";
28 #include <sys/types.h>
40 #ifdef HAVE_OS_PROTO_H
48 #define A_ATOM BPF_MEMWORDS
49 #define X_ATOM (BPF_MEMWORDS+1)
54 * This define is used to represent *both* the accumulator and
55 * x register in use-def computations.
56 * Currently, the use-def code assumes only one definition per instruction.
58 #define AX_ATOM N_ATOMS
61 * A flag to indicate that further optimization is needed.
62 * Iterative passes are continued until a given pass yields no
68 * A block is marked if only if its mark equals the current mark.
69 * Rather than traverse the code array, marking each item, 'cur_mark' is
70 * incremented. This automatically makes each element unmarked.
73 #define isMarked(p) ((p)->mark == cur_mark)
74 #define unMarkAll() cur_mark += 1
75 #define Mark(p) ((p)->mark = cur_mark)
77 static void opt_init(struct block *);
78 static void opt_cleanup(void);
80 static void make_marks(struct block *);
81 static void mark_code(struct block *);
83 static void intern_blocks(struct block *);
85 static int eq_slist(struct slist *, struct slist *);
87 static void find_levels_r(struct block *);
89 static void find_levels(struct block *);
90 static void find_dom(struct block *);
91 static void propedom(struct edge *);
92 static void find_edom(struct block *);
93 static void find_closure(struct block *);
94 static int atomuse(struct stmt *);
95 static int atomdef(struct stmt *);
96 static void compute_local_ud(struct block *);
97 static void find_ud(struct block *);
98 static void init_val(void);
99 static int F(int, int, int);
100 static inline void vstore(struct stmt *, int *, int, int);
101 static void opt_blk(struct block *, int);
102 static int use_conflict(struct block *, struct block *);
103 static void opt_j(struct edge *);
104 static void or_pullup(struct block *);
105 static void and_pullup(struct block *);
106 static void opt_blks(struct block *, int);
107 static inline void link_inedge(struct edge *, struct block *);
108 static void find_inedges(struct block *);
109 static void opt_root(struct block **);
110 static void opt_loop(struct block *, int);
111 static void fold_op(struct stmt *, int, int);
112 static inline struct slist *this_op(struct slist *);
113 static void opt_not(struct block *);
114 static void opt_peep(struct block *);
115 static void opt_stmt(struct stmt *, int[], int);
116 static void deadstmt(struct stmt *, struct stmt *[]);
117 static void opt_deadstores(struct block *);
118 static void opt_blk(struct block *, int);
119 static int use_conflict(struct block *, struct block *);
120 static void opt_j(struct edge *);
121 static struct block *fold_edge(struct block *, struct edge *);
122 static inline int eq_blk(struct block *, struct block *);
123 static int slength(struct slist *);
124 static int count_blocks(struct block *);
125 static void number_blks_r(struct block *);
126 static int count_stmts(struct block *);
127 static int convert_code_r(struct block *);
129 static void opt_dump(struct block *);
133 struct block **blocks;
138 * A bit vector set representation of the dominators.
139 * We round up the set size to the next power of two.
141 static int nodewords;
142 static int edgewords;
143 struct block **levels;
145 #define BITS_PER_WORD (8*sizeof(bpf_u_int32))
147 * True if a is in uset {p}
149 #define SET_MEMBER(p, a) \
150 ((p)[(unsigned)(a) / BITS_PER_WORD] & (1 << ((unsigned)(a) % BITS_PER_WORD)))
155 #define SET_INSERT(p, a) \
156 (p)[(unsigned)(a) / BITS_PER_WORD] |= (1 << ((unsigned)(a) % BITS_PER_WORD))
159 * Delete 'a' from uset p.
161 #define SET_DELETE(p, a) \
162 (p)[(unsigned)(a) / BITS_PER_WORD] &= ~(1 << ((unsigned)(a) % BITS_PER_WORD))
167 #define SET_INTERSECT(a, b, n)\
169 register bpf_u_int32 *_x = a, *_y = b;\
170 register int _n = n;\
171 while (--_n >= 0) *_x++ &= *_y++;\
177 #define SET_SUBTRACT(a, b, n)\
179 register bpf_u_int32 *_x = a, *_y = b;\
180 register int _n = n;\
181 while (--_n >= 0) *_x++ &=~ *_y++;\
187 #define SET_UNION(a, b, n)\
189 register bpf_u_int32 *_x = a, *_y = b;\
190 register int _n = n;\
191 while (--_n >= 0) *_x++ |= *_y++;\
194 static uset all_dom_sets;
195 static uset all_closure_sets;
196 static uset all_edge_sets;
199 #define MAX(a,b) ((a)>(b)?(a):(b))
215 find_levels_r(JT(b));
216 find_levels_r(JF(b));
217 level = MAX(JT(b)->level, JF(b)->level) + 1;
221 b->link = levels[level];
226 * Level graph. The levels go from 0 at the leaves to
227 * N_LEVELS at the root. The levels[] array points to the
228 * first node of the level list, whose elements are linked
229 * with the 'link' field of the struct block.
235 memset((char *)levels, 0, n_blocks * sizeof(*levels));
241 * Find dominator relationships.
242 * Assumes graph has been leveled.
253 * Initialize sets to contain all nodes.
256 i = n_blocks * nodewords;
259 /* Root starts off empty. */
260 for (i = nodewords; --i >= 0;)
263 /* root->level is the highest level no found. */
264 for (i = root->level; i >= 0; --i) {
265 for (b = levels[i]; b; b = b->link) {
266 SET_INSERT(b->dom, b->id);
269 SET_INTERSECT(JT(b)->dom, b->dom, nodewords);
270 SET_INTERSECT(JF(b)->dom, b->dom, nodewords);
279 SET_INSERT(ep->edom, ep->id);
281 SET_INTERSECT(ep->succ->et.edom, ep->edom, edgewords);
282 SET_INTERSECT(ep->succ->ef.edom, ep->edom, edgewords);
287 * Compute edge dominators.
288 * Assumes graph has been leveled and predecessors established.
299 for (i = n_edges * edgewords; --i >= 0; )
302 /* root->level is the highest level no found. */
303 memset(root->et.edom, 0, edgewords * sizeof(*(uset)0));
304 memset(root->ef.edom, 0, edgewords * sizeof(*(uset)0));
305 for (i = root->level; i >= 0; --i) {
306 for (b = levels[i]; b != 0; b = b->link) {
314 * Find the backwards transitive closure of the flow graph. These sets
315 * are backwards in the sense that we find the set of nodes that reach
316 * a given node, not the set of nodes that can be reached by a node.
318 * Assumes graph has been leveled.
328 * Initialize sets to contain no nodes.
330 memset((char *)all_closure_sets, 0,
331 n_blocks * nodewords * sizeof(*all_closure_sets));
333 /* root->level is the highest level no found. */
334 for (i = root->level; i >= 0; --i) {
335 for (b = levels[i]; b; b = b->link) {
336 SET_INSERT(b->closure, b->id);
339 SET_UNION(JT(b)->closure, b->closure, nodewords);
340 SET_UNION(JF(b)->closure, b->closure, nodewords);
346 * Return the register number that is used by s. If A and X are both
347 * used, return AX_ATOM. If no register is used, return -1.
349 * The implementation should probably change to an array access.
355 register int c = s->code;
360 switch (BPF_CLASS(c)) {
363 return (BPF_RVAL(c) == BPF_A) ? A_ATOM :
364 (BPF_RVAL(c) == BPF_X) ? X_ATOM : -1;
368 return (BPF_MODE(c) == BPF_IND) ? X_ATOM :
369 (BPF_MODE(c) == BPF_MEM) ? s->k : -1;
379 if (BPF_SRC(c) == BPF_X)
384 return BPF_MISCOP(c) == BPF_TXA ? X_ATOM : A_ATOM;
391 * Return the register number that is defined by 's'. We assume that
392 * a single stmt cannot define more than one register. If no register
393 * is defined, return -1.
395 * The implementation should probably change to an array access.
404 switch (BPF_CLASS(s->code)) {
418 return BPF_MISCOP(s->code) == BPF_TAX ? X_ATOM : A_ATOM;
428 atomset def = 0, use = 0, kill = 0;
431 for (s = b->stmts; s; s = s->next) {
432 if (s->s.code == NOP)
434 atom = atomuse(&s->s);
436 if (atom == AX_ATOM) {
437 if (!ATOMELEM(def, X_ATOM))
438 use |= ATOMMASK(X_ATOM);
439 if (!ATOMELEM(def, A_ATOM))
440 use |= ATOMMASK(A_ATOM);
442 else if (atom < N_ATOMS) {
443 if (!ATOMELEM(def, atom))
444 use |= ATOMMASK(atom);
449 atom = atomdef(&s->s);
451 if (!ATOMELEM(use, atom))
452 kill |= ATOMMASK(atom);
453 def |= ATOMMASK(atom);
456 if (!ATOMELEM(def, A_ATOM) && BPF_CLASS(b->s.code) == BPF_JMP)
457 use |= ATOMMASK(A_ATOM);
465 * Assume graph is already leveled.
475 * root->level is the highest level no found;
476 * count down from there.
478 maxlevel = root->level;
479 for (i = maxlevel; i >= 0; --i)
480 for (p = levels[i]; p; p = p->link) {
485 for (i = 1; i <= maxlevel; ++i) {
486 for (p = levels[i]; p; p = p->link) {
487 p->out_use |= JT(p)->in_use | JF(p)->in_use;
488 p->in_use |= p->out_use &~ p->kill;
494 * These data structures are used in a Cocke and Shwarz style
495 * value numbering scheme. Since the flowgraph is acyclic,
496 * exit values can be propagated from a node's predecessors
497 * provided it is uniquely defined.
503 struct valnode *next;
507 static struct valnode *hashtbl[MODULUS];
511 /* Integer constants mapped with the load immediate opcode. */
512 #define K(i) F(BPF_LD|BPF_IMM|BPF_W, i, 0L)
519 struct vmapinfo *vmap;
520 struct valnode *vnode_base;
521 struct valnode *next_vnode;
527 next_vnode = vnode_base;
528 memset((char *)vmap, 0, maxval * sizeof(*vmap));
529 memset((char *)hashtbl, 0, sizeof hashtbl);
532 /* Because we really don't have an IR, this stuff is a little messy. */
542 hash = (u_int)code ^ (v0 << 4) ^ (v1 << 8);
545 for (p = hashtbl[hash]; p; p = p->next)
546 if (p->code == code && p->v0 == v0 && p->v1 == v1)
550 if (BPF_MODE(code) == BPF_IMM &&
551 (BPF_CLASS(code) == BPF_LD || BPF_CLASS(code) == BPF_LDX)) {
552 vmap[val].const_val = v0;
553 vmap[val].is_const = 1;
560 p->next = hashtbl[hash];
567 vstore(s, valp, newval, alter)
573 if (alter && *valp == newval)
586 a = vmap[v0].const_val;
587 b = vmap[v1].const_val;
589 switch (BPF_OP(s->code)) {
604 bpf_error("division by zero");
632 s->code = BPF_LD|BPF_IMM;
636 static inline struct slist *
640 while (s != 0 && s->s.code == NOP)
649 struct block *tmp = JT(b);
660 struct slist *next, *last;
672 next = this_op(s->next);
678 * st M[k] --> st M[k]
681 if (s->s.code == BPF_ST &&
682 next->s.code == (BPF_LDX|BPF_MEM) &&
683 s->s.k == next->s.k) {
685 next->s.code = BPF_MISC|BPF_TAX;
691 if (s->s.code == (BPF_LD|BPF_IMM) &&
692 next->s.code == (BPF_MISC|BPF_TAX)) {
693 s->s.code = BPF_LDX|BPF_IMM;
694 next->s.code = BPF_MISC|BPF_TXA;
698 * This is an ugly special case, but it happens
699 * when you say tcp[k] or udp[k] where k is a constant.
701 if (s->s.code == (BPF_LD|BPF_IMM)) {
702 struct slist *add, *tax, *ild;
705 * Check that X isn't used on exit from this
706 * block (which the optimizer might cause).
707 * We know the code generator won't generate
708 * any local dependencies.
710 if (ATOMELEM(b->out_use, X_ATOM))
713 if (next->s.code != (BPF_LDX|BPF_MSH|BPF_B))
716 add = this_op(next->next);
717 if (add == 0 || add->s.code != (BPF_ALU|BPF_ADD|BPF_X))
720 tax = this_op(add->next);
721 if (tax == 0 || tax->s.code != (BPF_MISC|BPF_TAX))
724 ild = this_op(tax->next);
725 if (ild == 0 || BPF_CLASS(ild->s.code) != BPF_LD ||
726 BPF_MODE(ild->s.code) != BPF_IND)
729 * XXX We need to check that X is not
730 * subsequently used. We know we can eliminate the
731 * accumulator modifications since it is defined
732 * by the last stmt of this sequence.
734 * We want to turn this sequence:
737 * (005) ldxms [14] {next} -- optional
740 * (008) ild [x+0] {ild}
742 * into this sequence:
760 * If we have a subtract to do a comparison, and the X register
761 * is a known constant, we can merge this value into the
764 if (last->s.code == (BPF_ALU|BPF_SUB|BPF_X) &&
765 !ATOMELEM(b->out_use, A_ATOM)) {
766 val = b->val[X_ATOM];
767 if (vmap[val].is_const) {
770 b->s.k += vmap[val].const_val;
771 op = BPF_OP(b->s.code);
772 if (op == BPF_JGT || op == BPF_JGE) {
773 struct block *t = JT(b);
776 b->s.k += 0x80000000;
780 } else if (b->s.k == 0) {
786 b->s.code = BPF_CLASS(b->s.code) | BPF_OP(b->s.code) |
792 * Likewise, a constant subtract can be simplified.
794 else if (last->s.code == (BPF_ALU|BPF_SUB|BPF_K) &&
795 !ATOMELEM(b->out_use, A_ATOM)) {
800 op = BPF_OP(b->s.code);
801 if (op == BPF_JGT || op == BPF_JGE) {
802 struct block *t = JT(b);
805 b->s.k += 0x80000000;
813 if (last->s.code == (BPF_ALU|BPF_AND|BPF_K) &&
814 !ATOMELEM(b->out_use, A_ATOM) && b->s.k == 0) {
816 b->s.code = BPF_JMP|BPF_K|BPF_JSET;
822 * If the accumulator is a known constant, we can compute the
825 val = b->val[A_ATOM];
826 if (vmap[val].is_const && BPF_SRC(b->s.code) == BPF_K) {
827 bpf_int32 v = vmap[val].const_val;
828 switch (BPF_OP(b->s.code)) {
835 v = (unsigned)v > b->s.k;
839 v = (unsigned)v >= b->s.k;
859 * Compute the symbolic value of expression of 's', and update
860 * anything it defines in the value table 'val'. If 'alter' is true,
861 * do various optimizations. This code would be cleaner if symbolic
862 * evaluation and code transformations weren't folded together.
865 opt_stmt(s, val, alter)
875 case BPF_LD|BPF_ABS|BPF_W:
876 case BPF_LD|BPF_ABS|BPF_H:
877 case BPF_LD|BPF_ABS|BPF_B:
878 v = F(s->code, s->k, 0L);
879 vstore(s, &val[A_ATOM], v, alter);
882 case BPF_LD|BPF_IND|BPF_W:
883 case BPF_LD|BPF_IND|BPF_H:
884 case BPF_LD|BPF_IND|BPF_B:
886 if (alter && vmap[v].is_const) {
887 s->code = BPF_LD|BPF_ABS|BPF_SIZE(s->code);
888 s->k += vmap[v].const_val;
889 v = F(s->code, s->k, 0L);
893 v = F(s->code, s->k, v);
894 vstore(s, &val[A_ATOM], v, alter);
898 v = F(s->code, 0L, 0L);
899 vstore(s, &val[A_ATOM], v, alter);
904 vstore(s, &val[A_ATOM], v, alter);
907 case BPF_LDX|BPF_IMM:
909 vstore(s, &val[X_ATOM], v, alter);
912 case BPF_LDX|BPF_MSH|BPF_B:
913 v = F(s->code, s->k, 0L);
914 vstore(s, &val[X_ATOM], v, alter);
917 case BPF_ALU|BPF_NEG:
918 if (alter && vmap[val[A_ATOM]].is_const) {
919 s->code = BPF_LD|BPF_IMM;
920 s->k = -vmap[val[A_ATOM]].const_val;
921 val[A_ATOM] = K(s->k);
924 val[A_ATOM] = F(s->code, val[A_ATOM], 0L);
927 case BPF_ALU|BPF_ADD|BPF_K:
928 case BPF_ALU|BPF_SUB|BPF_K:
929 case BPF_ALU|BPF_MUL|BPF_K:
930 case BPF_ALU|BPF_DIV|BPF_K:
931 case BPF_ALU|BPF_AND|BPF_K:
932 case BPF_ALU|BPF_OR|BPF_K:
933 case BPF_ALU|BPF_LSH|BPF_K:
934 case BPF_ALU|BPF_RSH|BPF_K:
935 op = BPF_OP(s->code);
938 if (op == BPF_ADD || op == BPF_SUB ||
939 op == BPF_LSH || op == BPF_RSH ||
944 if (op == BPF_MUL || op == BPF_AND) {
945 s->code = BPF_LD|BPF_IMM;
946 val[A_ATOM] = K(s->k);
950 if (vmap[val[A_ATOM]].is_const) {
951 fold_op(s, val[A_ATOM], K(s->k));
952 val[A_ATOM] = K(s->k);
956 val[A_ATOM] = F(s->code, val[A_ATOM], K(s->k));
959 case BPF_ALU|BPF_ADD|BPF_X:
960 case BPF_ALU|BPF_SUB|BPF_X:
961 case BPF_ALU|BPF_MUL|BPF_X:
962 case BPF_ALU|BPF_DIV|BPF_X:
963 case BPF_ALU|BPF_AND|BPF_X:
964 case BPF_ALU|BPF_OR|BPF_X:
965 case BPF_ALU|BPF_LSH|BPF_X:
966 case BPF_ALU|BPF_RSH|BPF_X:
967 op = BPF_OP(s->code);
968 if (alter && vmap[val[X_ATOM]].is_const) {
969 if (vmap[val[A_ATOM]].is_const) {
970 fold_op(s, val[A_ATOM], val[X_ATOM]);
971 val[A_ATOM] = K(s->k);
974 s->code = BPF_ALU|BPF_K|op;
975 s->k = vmap[val[X_ATOM]].const_val;
978 F(s->code, val[A_ATOM], K(s->k));
983 * Check if we're doing something to an accumulator
984 * that is 0, and simplify. This may not seem like
985 * much of a simplification but it could open up further
987 * XXX We could also check for mul by 1, and -1, etc.
989 if (alter && vmap[val[A_ATOM]].is_const
990 && vmap[val[A_ATOM]].const_val == 0) {
991 if (op == BPF_ADD || op == BPF_OR ||
992 op == BPF_LSH || op == BPF_RSH || op == BPF_SUB) {
993 s->code = BPF_MISC|BPF_TXA;
994 vstore(s, &val[A_ATOM], val[X_ATOM], alter);
997 else if (op == BPF_MUL || op == BPF_DIV ||
999 s->code = BPF_LD|BPF_IMM;
1001 vstore(s, &val[A_ATOM], K(s->k), alter);
1004 else if (op == BPF_NEG) {
1009 val[A_ATOM] = F(s->code, val[A_ATOM], val[X_ATOM]);
1012 case BPF_MISC|BPF_TXA:
1013 vstore(s, &val[A_ATOM], val[X_ATOM], alter);
1016 case BPF_LD|BPF_MEM:
1018 if (alter && vmap[v].is_const) {
1019 s->code = BPF_LD|BPF_IMM;
1020 s->k = vmap[v].const_val;
1023 vstore(s, &val[A_ATOM], v, alter);
1026 case BPF_MISC|BPF_TAX:
1027 vstore(s, &val[X_ATOM], val[A_ATOM], alter);
1030 case BPF_LDX|BPF_MEM:
1032 if (alter && vmap[v].is_const) {
1033 s->code = BPF_LDX|BPF_IMM;
1034 s->k = vmap[v].const_val;
1037 vstore(s, &val[X_ATOM], v, alter);
1041 vstore(s, &val[s->k], val[A_ATOM], alter);
1045 vstore(s, &val[s->k], val[X_ATOM], alter);
1052 register struct stmt *s;
1053 register struct stmt *last[];
1059 if (atom == AX_ATOM) {
1070 last[atom]->code = NOP;
1078 register struct block *b;
1080 register struct slist *s;
1082 struct stmt *last[N_ATOMS];
1084 memset((char *)last, 0, sizeof last);
1086 for (s = b->stmts; s != 0; s = s->next)
1087 deadstmt(&s->s, last);
1088 deadstmt(&b->s, last);
1090 for (atom = 0; atom < N_ATOMS; ++atom)
1091 if (last[atom] && !ATOMELEM(b->out_use, atom)) {
1092 last[atom]->code = NOP;
1098 opt_blk(b, do_stmts)
1108 * Initialize the atom values.
1109 * If we have no predecessors, everything is undefined.
1110 * Otherwise, we inherent our values from our predecessors.
1111 * If any register has an ambiguous value (i.e. control paths are
1112 * merging) give it the undefined value of 0.
1116 memset((char *)b->val, 0, sizeof(b->val));
1118 memcpy((char *)b->val, (char *)p->pred->val, sizeof(b->val));
1119 while ((p = p->next) != NULL) {
1120 for (i = 0; i < N_ATOMS; ++i)
1121 if (b->val[i] != p->pred->val[i])
1125 aval = b->val[A_ATOM];
1126 for (s = b->stmts; s; s = s->next)
1127 opt_stmt(&s->s, b->val, do_stmts);
1130 * This is a special case: if we don't use anything from this
1131 * block, and we load the accumulator with value that is
1132 * already there, or if this block is a return,
1133 * eliminate all the statements.
1136 ((b->out_use == 0 && aval != 0 &&b->val[A_ATOM] == aval) ||
1137 BPF_CLASS(b->s.code) == BPF_RET)) {
1138 if (b->stmts != 0) {
1147 * Set up values for branch optimizer.
1149 if (BPF_SRC(b->s.code) == BPF_K)
1150 b->oval = K(b->s.k);
1152 b->oval = b->val[X_ATOM];
1153 b->et.code = b->s.code;
1154 b->ef.code = -b->s.code;
1158 * Return true if any register that is used on exit from 'succ', has
1159 * an exit value that is different from the corresponding exit value
1163 use_conflict(b, succ)
1164 struct block *b, *succ;
1167 atomset use = succ->out_use;
1172 for (atom = 0; atom < N_ATOMS; ++atom)
1173 if (ATOMELEM(use, atom))
1174 if (b->val[atom] != succ->val[atom])
1179 static struct block *
1180 fold_edge(child, ep)
1181 struct block *child;
1185 int aval0, aval1, oval0, oval1;
1186 int code = ep->code;
1194 if (child->s.code != code)
1197 aval0 = child->val[A_ATOM];
1198 oval0 = child->oval;
1199 aval1 = ep->pred->val[A_ATOM];
1200 oval1 = ep->pred->oval;
1207 * The operands are identical, so the
1208 * result is true if a true branch was
1209 * taken to get here, otherwise false.
1211 return sense ? JT(child) : JF(child);
1213 if (sense && code == (BPF_JMP|BPF_JEQ|BPF_K))
1215 * At this point, we only know the comparison if we
1216 * came down the true branch, and it was an equality
1217 * comparison with a constant. We rely on the fact that
1218 * distinct constants have distinct value numbers.
1230 register struct block *target;
1232 if (JT(ep->succ) == 0)
1235 if (JT(ep->succ) == JF(ep->succ)) {
1237 * Common branch targets can be eliminated, provided
1238 * there is no data dependency.
1240 if (!use_conflict(ep->pred, ep->succ->et.succ)) {
1242 ep->succ = JT(ep->succ);
1246 * For each edge dominator that matches the successor of this
1247 * edge, promote the edge successor to the its grandchild.
1249 * XXX We violate the set abstraction here in favor a reasonably
1253 for (i = 0; i < edgewords; ++i) {
1254 register bpf_u_int32 x = ep->edom[i];
1259 k += i * BITS_PER_WORD;
1261 target = fold_edge(ep->succ, edges[k]);
1263 * Check that there is no data dependency between
1264 * nodes that will be violated if we move the edge.
1266 if (target != 0 && !use_conflict(ep->pred, target)) {
1269 if (JT(target) != 0)
1271 * Start over unless we hit a leaf.
1287 struct block **diffp, **samep;
1295 * Make sure each predecessor loads the same value.
1298 val = ep->pred->val[A_ATOM];
1299 for (ep = ep->next; ep != 0; ep = ep->next)
1300 if (val != ep->pred->val[A_ATOM])
1303 if (JT(b->in_edges->pred) == b)
1304 diffp = &JT(b->in_edges->pred);
1306 diffp = &JF(b->in_edges->pred);
1313 if (JT(*diffp) != JT(b))
1316 if (!SET_MEMBER((*diffp)->dom, b->id))
1319 if ((*diffp)->val[A_ATOM] != val)
1322 diffp = &JF(*diffp);
1325 samep = &JF(*diffp);
1330 if (JT(*samep) != JT(b))
1333 if (!SET_MEMBER((*samep)->dom, b->id))
1336 if ((*samep)->val[A_ATOM] == val)
1339 /* XXX Need to check that there are no data dependencies
1340 between dp0 and dp1. Currently, the code generator
1341 will not produce such dependencies. */
1342 samep = &JF(*samep);
1345 /* XXX This doesn't cover everything. */
1346 for (i = 0; i < N_ATOMS; ++i)
1347 if ((*samep)->val[i] != pred->val[i])
1350 /* Pull up the node. */
1356 * At the top of the chain, each predecessor needs to point at the
1357 * pulled up node. Inside the chain, there is only one predecessor
1361 for (ep = b->in_edges; ep != 0; ep = ep->next) {
1362 if (JT(ep->pred) == b)
1363 JT(ep->pred) = pull;
1365 JF(ep->pred) = pull;
1380 struct block **diffp, **samep;
1388 * Make sure each predecessor loads the same value.
1390 val = ep->pred->val[A_ATOM];
1391 for (ep = ep->next; ep != 0; ep = ep->next)
1392 if (val != ep->pred->val[A_ATOM])
1395 if (JT(b->in_edges->pred) == b)
1396 diffp = &JT(b->in_edges->pred);
1398 diffp = &JF(b->in_edges->pred);
1405 if (JF(*diffp) != JF(b))
1408 if (!SET_MEMBER((*diffp)->dom, b->id))
1411 if ((*diffp)->val[A_ATOM] != val)
1414 diffp = &JT(*diffp);
1417 samep = &JT(*diffp);
1422 if (JF(*samep) != JF(b))
1425 if (!SET_MEMBER((*samep)->dom, b->id))
1428 if ((*samep)->val[A_ATOM] == val)
1431 /* XXX Need to check that there are no data dependencies
1432 between diffp and samep. Currently, the code generator
1433 will not produce such dependencies. */
1434 samep = &JT(*samep);
1437 /* XXX This doesn't cover everything. */
1438 for (i = 0; i < N_ATOMS; ++i)
1439 if ((*samep)->val[i] != pred->val[i])
1442 /* Pull up the node. */
1448 * At the top of the chain, each predecessor needs to point at the
1449 * pulled up node. Inside the chain, there is only one predecessor
1453 for (ep = b->in_edges; ep != 0; ep = ep->next) {
1454 if (JT(ep->pred) == b)
1455 JT(ep->pred) = pull;
1457 JF(ep->pred) = pull;
1467 opt_blks(root, do_stmts)
1475 maxlevel = root->level;
1476 for (i = maxlevel; i >= 0; --i)
1477 for (p = levels[i]; p; p = p->link)
1478 opt_blk(p, do_stmts);
1482 * No point trying to move branches; it can't possibly
1483 * make a difference at this point.
1487 for (i = 1; i <= maxlevel; ++i) {
1488 for (p = levels[i]; p; p = p->link) {
1493 for (i = 1; i <= maxlevel; ++i) {
1494 for (p = levels[i]; p; p = p->link) {
1502 link_inedge(parent, child)
1503 struct edge *parent;
1504 struct block *child;
1506 parent->next = child->in_edges;
1507 child->in_edges = parent;
1517 for (i = 0; i < n_blocks; ++i)
1518 blocks[i]->in_edges = 0;
1521 * Traverse the graph, adding each edge to the predecessor
1522 * list of its successors. Skip the leaves (i.e. level 0).
1524 for (i = root->level; i > 0; --i) {
1525 for (b = levels[i]; b != 0; b = b->link) {
1526 link_inedge(&b->et, JT(b));
1527 link_inedge(&b->ef, JF(b));
1536 struct slist *tmp, *s;
1540 while (BPF_CLASS((*b)->s.code) == BPF_JMP && JT(*b) == JF(*b))
1549 * If the root node is a return, then there is no
1550 * point executing any statements (since the bpf machine
1551 * has no side effects).
1553 if (BPF_CLASS((*b)->s.code) == BPF_RET)
1558 opt_loop(root, do_stmts)
1575 opt_blks(root, do_stmts);
1584 * Optimize the filter code in its dag representation.
1588 struct block **rootp;
1597 intern_blocks(root);
1608 if (BPF_CLASS(p->s.code) != BPF_RET) {
1616 * Mark code array such that isMarked(i) is true
1617 * only for nodes that are alive.
1628 * True iff the two stmt lists load the same value from the packet into
1633 struct slist *x, *y;
1636 while (x && x->s.code == NOP)
1638 while (y && y->s.code == NOP)
1644 if (x->s.code != y->s.code || x->s.k != y->s.k)
1653 struct block *b0, *b1;
1655 if (b0->s.code == b1->s.code &&
1656 b0->s.k == b1->s.k &&
1657 b0->et.succ == b1->et.succ &&
1658 b0->ef.succ == b1->ef.succ)
1659 return eq_slist(b0->stmts, b1->stmts);
1672 for (i = 0; i < n_blocks; ++i)
1673 blocks[i]->link = 0;
1677 for (i = n_blocks - 1; --i >= 0; ) {
1678 if (!isMarked(blocks[i]))
1680 for (j = i + 1; j < n_blocks; ++j) {
1681 if (!isMarked(blocks[j]))
1683 if (eq_blk(blocks[i], blocks[j])) {
1684 blocks[i]->link = blocks[j]->link ?
1685 blocks[j]->link : blocks[j];
1690 for (i = 0; i < n_blocks; ++i) {
1696 JT(p) = JT(p)->link;
1700 JF(p) = JF(p)->link;
1710 free((void *)vnode_base);
1712 free((void *)edges);
1713 free((void *)space);
1714 free((void *)levels);
1715 free((void *)blocks);
1719 * Return the number of stmts in 's'.
1727 for (; s; s = s->next)
1728 if (s->s.code != NOP)
1734 * Return the number of nodes reachable by 'p'.
1735 * All nodes should be initially unmarked.
1741 if (p == 0 || isMarked(p))
1744 return count_blocks(JT(p)) + count_blocks(JF(p)) + 1;
1748 * Do a depth first search on the flow graph, numbering the
1749 * the basic blocks, and entering them into the 'blocks' array.`
1757 if (p == 0 || isMarked(p))
1765 number_blks_r(JT(p));
1766 number_blks_r(JF(p));
1770 * Return the number of stmts in the flowgraph reachable by 'p'.
1771 * The nodes should be unmarked before calling.
1779 if (p == 0 || isMarked(p))
1782 n = count_stmts(JT(p)) + count_stmts(JF(p));
1783 return slength(p->stmts) + n + 1;
1787 * Allocate memory. All allocation is done before optimization
1788 * is begun. A linear bound on the size of all data structures is computed
1789 * from the total number of blocks and/or statements.
1796 int i, n, max_stmts;
1799 * First, count the blocks, so we can malloc an array to map
1800 * block number to block. Then, put the blocks into the array.
1803 n = count_blocks(root);
1804 blocks = (struct block **)malloc(n * sizeof(*blocks));
1807 number_blks_r(root);
1809 n_edges = 2 * n_blocks;
1810 edges = (struct edge **)malloc(n_edges * sizeof(*edges));
1813 * The number of levels is bounded by the number of nodes.
1815 levels = (struct block **)malloc(n_blocks * sizeof(*levels));
1817 edgewords = n_edges / (8 * sizeof(bpf_u_int32)) + 1;
1818 nodewords = n_blocks / (8 * sizeof(bpf_u_int32)) + 1;
1821 space = (bpf_u_int32 *)malloc(2 * n_blocks * nodewords * sizeof(*space)
1822 + n_edges * edgewords * sizeof(*space));
1825 for (i = 0; i < n; ++i) {
1829 all_closure_sets = p;
1830 for (i = 0; i < n; ++i) {
1831 blocks[i]->closure = p;
1835 for (i = 0; i < n; ++i) {
1836 register struct block *b = blocks[i];
1844 b->ef.id = n_blocks + i;
1845 edges[n_blocks + i] = &b->ef;
1850 for (i = 0; i < n; ++i)
1851 max_stmts += slength(blocks[i]->stmts) + 1;
1853 * We allocate at most 3 value numbers per statement,
1854 * so this is an upper bound on the number of valnodes
1857 maxval = 3 * max_stmts;
1858 vmap = (struct vmapinfo *)malloc(maxval * sizeof(*vmap));
1859 vnode_base = (struct valnode *)malloc(maxval * sizeof(*vmap));
1863 * Some pointers used to convert the basic block form of the code,
1864 * into the array form that BPF requires. 'fstart' will point to
1865 * the malloc'd array while 'ftail' is used during the recursive traversal.
1867 static struct bpf_insn *fstart;
1868 static struct bpf_insn *ftail;
1875 * Returns true if successful. Returns false if a branch has
1876 * an offset that is too large. If so, we have marked that
1877 * branch so that on a subsequent iteration, it will be treated
1884 struct bpf_insn *dst;
1888 int extrajmps; /* number of extra jumps inserted */
1890 if (p == 0 || isMarked(p))
1894 if (convert_code_r(JF(p)) == 0)
1896 if (convert_code_r(JT(p)) == 0)
1899 slen = slength(p->stmts);
1900 dst = ftail -= (slen + 1 + p->longjt + p->longjf);
1901 /* inflate length by any extra jumps */
1903 p->offset = dst - fstart;
1905 for (src = p->stmts; src; src = src->next) {
1906 if (src->s.code == NOP)
1908 dst->code = (u_short)src->s.code;
1913 bids[dst - fstart] = p->id + 1;
1915 dst->code = (u_short)p->s.code;
1919 off = JT(p)->offset - (p->offset + slen) - 1;
1921 /* offset too large for branch, must add a jump */
1922 if (p->longjt == 0) {
1923 /* mark this instruction and retry */
1927 /* branch if T to following jump */
1928 dst->jt = extrajmps;
1930 dst[extrajmps].code = BPF_JMP|BPF_JA;
1931 dst[extrajmps].k = off - extrajmps;
1935 off = JF(p)->offset - (p->offset + slen) - 1;
1937 /* offset too large for branch, must add a jump */
1938 if (p->longjf == 0) {
1939 /* mark this instruction and retry */
1943 /* branch if F to following jump */
1944 /* if two jumps are inserted, F goes to second one */
1945 dst->jf = extrajmps;
1947 dst[extrajmps].code = BPF_JMP|BPF_JA;
1948 dst[extrajmps].k = off - extrajmps;
1958 * Convert flowgraph intermediate representation to the
1959 * BPF array representation. Set *lenp to the number of instructions.
1962 icode_to_fcode(root, lenp)
1967 struct bpf_insn *fp;
1970 * Loop doing convert_codr_r() until no branches remain
1971 * with too-large offsets.
1975 n = *lenp = count_stmts(root);
1977 fp = (struct bpf_insn *)malloc(sizeof(*fp) * n);
1978 memset((char *)fp, 0, sizeof(*fp) * n);
1983 if (convert_code_r(root))
1996 struct bpf_program f;
1998 memset(bids, 0, sizeof bids);
1999 f.bf_insns = icode_to_fcode(root, &f.bf_len);
2002 free((char *)f.bf_insns);