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.
24 static const char rcsid[] _U_ =
25 "@(#) $Header: /tcpdump/master/libpcap/optimize.c,v 1.91 2008-01-02 04:16:46 guy Exp $ (LBL)";
33 #include <pcap-stdinc.h>
40 #ifdef HAVE_SYS_BITYPES_H
41 #include <sys/bitypes.h>
43 #include <sys/types.h>
57 #ifdef HAVE_OS_PROTO_H
65 #if defined(MSDOS) && !defined(__DJGPP__)
66 extern int _w32_ffs (int mask);
70 #if defined(WIN32) && defined (_MSC_VER)
75 * Represents a deleted instruction.
80 * Register numbers for use-def values.
81 * 0 through BPF_MEMWORDS-1 represent the corresponding scratch memory
82 * location. A_ATOM is the accumulator and X_ATOM is the index
85 #define A_ATOM BPF_MEMWORDS
86 #define X_ATOM (BPF_MEMWORDS+1)
89 * This define is used to represent *both* the accumulator and
90 * x register in use-def computations.
91 * Currently, the use-def code assumes only one definition per instruction.
93 #define AX_ATOM N_ATOMS
96 * A flag to indicate that further optimization is needed.
97 * Iterative passes are continued until a given pass yields no
103 * A block is marked if only if its mark equals the current mark.
104 * Rather than traverse the code array, marking each item, 'cur_mark' is
105 * incremented. This automatically makes each element unmarked.
108 #define isMarked(p) ((p)->mark == cur_mark)
109 #define unMarkAll() cur_mark += 1
110 #define Mark(p) ((p)->mark = cur_mark)
112 static void opt_init(struct block *);
113 static void opt_cleanup(void);
115 static void make_marks(struct block *);
116 static void mark_code(struct block *);
118 static void intern_blocks(struct block *);
120 static int eq_slist(struct slist *, struct slist *);
122 static void find_levels_r(struct block *);
124 static void find_levels(struct block *);
125 static void find_dom(struct block *);
126 static void propedom(struct edge *);
127 static void find_edom(struct block *);
128 static void find_closure(struct block *);
129 static int atomuse(struct stmt *);
130 static int atomdef(struct stmt *);
131 static void compute_local_ud(struct block *);
132 static void find_ud(struct block *);
133 static void init_val(void);
134 static int F(int, int, int);
135 static inline void vstore(struct stmt *, int *, int, int);
136 static void opt_blk(struct block *, int);
137 static int use_conflict(struct block *, struct block *);
138 static void opt_j(struct edge *);
139 static void or_pullup(struct block *);
140 static void and_pullup(struct block *);
141 static void opt_blks(struct block *, int);
142 static inline void link_inedge(struct edge *, struct block *);
143 static void find_inedges(struct block *);
144 static void opt_root(struct block **);
145 static void opt_loop(struct block *, int);
146 static void fold_op(struct stmt *, int, int);
147 static inline struct slist *this_op(struct slist *);
148 static void opt_not(struct block *);
149 static void opt_peep(struct block *);
150 static void opt_stmt(struct stmt *, int[], int);
151 static void deadstmt(struct stmt *, struct stmt *[]);
152 static void opt_deadstores(struct block *);
153 static struct block *fold_edge(struct block *, struct edge *);
154 static inline int eq_blk(struct block *, struct block *);
155 static u_int slength(struct slist *);
156 static int count_blocks(struct block *);
157 static void number_blks_r(struct block *);
158 static u_int count_stmts(struct block *);
159 static int convert_code_r(struct block *);
161 static void opt_dump(struct block *);
165 struct block **blocks;
170 * A bit vector set representation of the dominators.
171 * We round up the set size to the next power of two.
173 static int nodewords;
174 static int edgewords;
175 struct block **levels;
177 #define BITS_PER_WORD (8*sizeof(bpf_u_int32))
179 * True if a is in uset {p}
181 #define SET_MEMBER(p, a) \
182 ((p)[(unsigned)(a) / BITS_PER_WORD] & (1 << ((unsigned)(a) % BITS_PER_WORD)))
187 #define SET_INSERT(p, a) \
188 (p)[(unsigned)(a) / BITS_PER_WORD] |= (1 << ((unsigned)(a) % BITS_PER_WORD))
191 * Delete 'a' from uset p.
193 #define SET_DELETE(p, a) \
194 (p)[(unsigned)(a) / BITS_PER_WORD] &= ~(1 << ((unsigned)(a) % BITS_PER_WORD))
199 #define SET_INTERSECT(a, b, n)\
201 register bpf_u_int32 *_x = a, *_y = b;\
202 register int _n = n;\
203 while (--_n >= 0) *_x++ &= *_y++;\
209 #define SET_SUBTRACT(a, b, n)\
211 register bpf_u_int32 *_x = a, *_y = b;\
212 register int _n = n;\
213 while (--_n >= 0) *_x++ &=~ *_y++;\
219 #define SET_UNION(a, b, n)\
221 register bpf_u_int32 *_x = a, *_y = b;\
222 register int _n = n;\
223 while (--_n >= 0) *_x++ |= *_y++;\
226 static uset all_dom_sets;
227 static uset all_closure_sets;
228 static uset all_edge_sets;
231 #define MAX(a,b) ((a)>(b)?(a):(b))
247 find_levels_r(JT(b));
248 find_levels_r(JF(b));
249 level = MAX(JT(b)->level, JF(b)->level) + 1;
253 b->link = levels[level];
258 * Level graph. The levels go from 0 at the leaves to
259 * N_LEVELS at the root. The levels[] array points to the
260 * first node of the level list, whose elements are linked
261 * with the 'link' field of the struct block.
267 memset((char *)levels, 0, n_blocks * sizeof(*levels));
273 * Find dominator relationships.
274 * Assumes graph has been leveled.
285 * Initialize sets to contain all nodes.
288 i = n_blocks * nodewords;
291 /* Root starts off empty. */
292 for (i = nodewords; --i >= 0;)
295 /* root->level is the highest level no found. */
296 for (i = root->level; i >= 0; --i) {
297 for (b = levels[i]; b; b = b->link) {
298 SET_INSERT(b->dom, b->id);
301 SET_INTERSECT(JT(b)->dom, b->dom, nodewords);
302 SET_INTERSECT(JF(b)->dom, b->dom, nodewords);
311 SET_INSERT(ep->edom, ep->id);
313 SET_INTERSECT(ep->succ->et.edom, ep->edom, edgewords);
314 SET_INTERSECT(ep->succ->ef.edom, ep->edom, edgewords);
319 * Compute edge dominators.
320 * Assumes graph has been leveled and predecessors established.
331 for (i = n_edges * edgewords; --i >= 0; )
334 /* root->level is the highest level no found. */
335 memset(root->et.edom, 0, edgewords * sizeof(*(uset)0));
336 memset(root->ef.edom, 0, edgewords * sizeof(*(uset)0));
337 for (i = root->level; i >= 0; --i) {
338 for (b = levels[i]; b != 0; b = b->link) {
346 * Find the backwards transitive closure of the flow graph. These sets
347 * are backwards in the sense that we find the set of nodes that reach
348 * a given node, not the set of nodes that can be reached by a node.
350 * Assumes graph has been leveled.
360 * Initialize sets to contain no nodes.
362 memset((char *)all_closure_sets, 0,
363 n_blocks * nodewords * sizeof(*all_closure_sets));
365 /* root->level is the highest level no found. */
366 for (i = root->level; i >= 0; --i) {
367 for (b = levels[i]; b; b = b->link) {
368 SET_INSERT(b->closure, b->id);
371 SET_UNION(JT(b)->closure, b->closure, nodewords);
372 SET_UNION(JF(b)->closure, b->closure, nodewords);
378 * Return the register number that is used by s. If A and X are both
379 * used, return AX_ATOM. If no register is used, return -1.
381 * The implementation should probably change to an array access.
387 register int c = s->code;
392 switch (BPF_CLASS(c)) {
395 return (BPF_RVAL(c) == BPF_A) ? A_ATOM :
396 (BPF_RVAL(c) == BPF_X) ? X_ATOM : -1;
400 return (BPF_MODE(c) == BPF_IND) ? X_ATOM :
401 (BPF_MODE(c) == BPF_MEM) ? s->k : -1;
411 if (BPF_SRC(c) == BPF_X)
416 return BPF_MISCOP(c) == BPF_TXA ? X_ATOM : A_ATOM;
423 * Return the register number that is defined by 's'. We assume that
424 * a single stmt cannot define more than one register. If no register
425 * is defined, return -1.
427 * The implementation should probably change to an array access.
436 switch (BPF_CLASS(s->code)) {
450 return BPF_MISCOP(s->code) == BPF_TAX ? X_ATOM : A_ATOM;
456 * Compute the sets of registers used, defined, and killed by 'b'.
458 * "Used" means that a statement in 'b' uses the register before any
459 * statement in 'b' defines it, i.e. it uses the value left in
460 * that register by a predecessor block of this block.
461 * "Defined" means that a statement in 'b' defines it.
462 * "Killed" means that a statement in 'b' defines it before any
463 * statement in 'b' uses it, i.e. it kills the value left in that
464 * register by a predecessor block of this block.
471 atomset def = 0, use = 0, kill = 0;
474 for (s = b->stmts; s; s = s->next) {
475 if (s->s.code == NOP)
477 atom = atomuse(&s->s);
479 if (atom == AX_ATOM) {
480 if (!ATOMELEM(def, X_ATOM))
481 use |= ATOMMASK(X_ATOM);
482 if (!ATOMELEM(def, A_ATOM))
483 use |= ATOMMASK(A_ATOM);
485 else if (atom < N_ATOMS) {
486 if (!ATOMELEM(def, atom))
487 use |= ATOMMASK(atom);
492 atom = atomdef(&s->s);
494 if (!ATOMELEM(use, atom))
495 kill |= ATOMMASK(atom);
496 def |= ATOMMASK(atom);
499 if (BPF_CLASS(b->s.code) == BPF_JMP) {
501 * XXX - what about RET?
503 atom = atomuse(&b->s);
505 if (atom == AX_ATOM) {
506 if (!ATOMELEM(def, X_ATOM))
507 use |= ATOMMASK(X_ATOM);
508 if (!ATOMELEM(def, A_ATOM))
509 use |= ATOMMASK(A_ATOM);
511 else if (atom < N_ATOMS) {
512 if (!ATOMELEM(def, atom))
513 use |= ATOMMASK(atom);
526 * Assume graph is already leveled.
536 * root->level is the highest level no found;
537 * count down from there.
539 maxlevel = root->level;
540 for (i = maxlevel; i >= 0; --i)
541 for (p = levels[i]; p; p = p->link) {
546 for (i = 1; i <= maxlevel; ++i) {
547 for (p = levels[i]; p; p = p->link) {
548 p->out_use |= JT(p)->in_use | JF(p)->in_use;
549 p->in_use |= p->out_use &~ p->kill;
555 * These data structures are used in a Cocke and Shwarz style
556 * value numbering scheme. Since the flowgraph is acyclic,
557 * exit values can be propagated from a node's predecessors
558 * provided it is uniquely defined.
564 struct valnode *next;
568 static struct valnode *hashtbl[MODULUS];
572 /* Integer constants mapped with the load immediate opcode. */
573 #define K(i) F(BPF_LD|BPF_IMM|BPF_W, i, 0L)
580 struct vmapinfo *vmap;
581 struct valnode *vnode_base;
582 struct valnode *next_vnode;
588 next_vnode = vnode_base;
589 memset((char *)vmap, 0, maxval * sizeof(*vmap));
590 memset((char *)hashtbl, 0, sizeof hashtbl);
593 /* Because we really don't have an IR, this stuff is a little messy. */
603 hash = (u_int)code ^ (v0 << 4) ^ (v1 << 8);
606 for (p = hashtbl[hash]; p; p = p->next)
607 if (p->code == code && p->v0 == v0 && p->v1 == v1)
611 if (BPF_MODE(code) == BPF_IMM &&
612 (BPF_CLASS(code) == BPF_LD || BPF_CLASS(code) == BPF_LDX)) {
613 vmap[val].const_val = v0;
614 vmap[val].is_const = 1;
621 p->next = hashtbl[hash];
628 vstore(s, valp, newval, alter)
634 if (alter && *valp == newval)
647 a = vmap[v0].const_val;
648 b = vmap[v1].const_val;
650 switch (BPF_OP(s->code)) {
665 bpf_error("division by zero");
693 s->code = BPF_LD|BPF_IMM;
697 static inline struct slist *
701 while (s != 0 && s->s.code == NOP)
710 struct block *tmp = JT(b);
721 struct slist *next, *last;
729 for (/*empty*/; /*empty*/; s = next) {
735 break; /* nothing left in the block */
738 * Find the next real instruction after that one
741 next = this_op(s->next);
743 break; /* no next instruction */
747 * st M[k] --> st M[k]
750 if (s->s.code == BPF_ST &&
751 next->s.code == (BPF_LDX|BPF_MEM) &&
752 s->s.k == next->s.k) {
754 next->s.code = BPF_MISC|BPF_TAX;
760 if (s->s.code == (BPF_LD|BPF_IMM) &&
761 next->s.code == (BPF_MISC|BPF_TAX)) {
762 s->s.code = BPF_LDX|BPF_IMM;
763 next->s.code = BPF_MISC|BPF_TXA;
767 * This is an ugly special case, but it happens
768 * when you say tcp[k] or udp[k] where k is a constant.
770 if (s->s.code == (BPF_LD|BPF_IMM)) {
771 struct slist *add, *tax, *ild;
774 * Check that X isn't used on exit from this
775 * block (which the optimizer might cause).
776 * We know the code generator won't generate
777 * any local dependencies.
779 if (ATOMELEM(b->out_use, X_ATOM))
783 * Check that the instruction following the ldi
784 * is an addx, or it's an ldxms with an addx
785 * following it (with 0 or more nops between the
788 if (next->s.code != (BPF_LDX|BPF_MSH|BPF_B))
791 add = this_op(next->next);
792 if (add == 0 || add->s.code != (BPF_ALU|BPF_ADD|BPF_X))
796 * Check that a tax follows that (with 0 or more
797 * nops between them).
799 tax = this_op(add->next);
800 if (tax == 0 || tax->s.code != (BPF_MISC|BPF_TAX))
804 * Check that an ild follows that (with 0 or more
805 * nops between them).
807 ild = this_op(tax->next);
808 if (ild == 0 || BPF_CLASS(ild->s.code) != BPF_LD ||
809 BPF_MODE(ild->s.code) != BPF_IND)
812 * We want to turn this sequence:
815 * (005) ldxms [14] {next} -- optional
818 * (008) ild [x+0] {ild}
820 * into this sequence:
828 * XXX We need to check that X is not
829 * subsequently used, because we want to change
830 * what'll be in it after this sequence.
832 * We know we can eliminate the accumulator
833 * modifications earlier in the sequence since
834 * it is defined by the last stmt of this sequence
835 * (i.e., the last statement of the sequence loads
836 * a value into the accumulator, so we can eliminate
837 * earlier operations on the accumulator).
847 * If the comparison at the end of a block is an equality
848 * comparison against a constant, and nobody uses the value
849 * we leave in the A register at the end of a block, and
850 * the operation preceding the comparison is an arithmetic
851 * operation, we can sometime optimize it away.
853 if (b->s.code == (BPF_JMP|BPF_JEQ|BPF_K) &&
854 !ATOMELEM(b->out_use, A_ATOM)) {
856 * We can optimize away certain subtractions of the
859 if (last->s.code == (BPF_ALU|BPF_SUB|BPF_X)) {
860 val = b->val[X_ATOM];
861 if (vmap[val].is_const) {
863 * If we have a subtract to do a comparison,
864 * and the X register is a known constant,
865 * we can merge this value into the
871 b->s.k += vmap[val].const_val;
874 } else if (b->s.k == 0) {
876 * If the X register isn't a constant,
877 * and the comparison in the test is
878 * against 0, we can compare with the
879 * X register, instead:
885 b->s.code = BPF_JMP|BPF_JEQ|BPF_X;
890 * Likewise, a constant subtract can be simplified:
893 * jeq #y -> jeq #(x+y)
895 else if (last->s.code == (BPF_ALU|BPF_SUB|BPF_K)) {
901 * And, similarly, a constant AND can be simplified
902 * if we're testing against 0, i.e.:
907 else if (last->s.code == (BPF_ALU|BPF_AND|BPF_K) &&
910 b->s.code = BPF_JMP|BPF_K|BPF_JSET;
918 * jset #ffffffff -> always
920 if (b->s.code == (BPF_JMP|BPF_K|BPF_JSET)) {
923 if (b->s.k == 0xffffffff)
927 * If we're comparing against the index register, and the index
928 * register is a known constant, we can just compare against that
931 val = b->val[X_ATOM];
932 if (vmap[val].is_const && BPF_SRC(b->s.code) == BPF_X) {
933 bpf_int32 v = vmap[val].const_val;
938 * If the accumulator is a known constant, we can compute the
941 val = b->val[A_ATOM];
942 if (vmap[val].is_const && BPF_SRC(b->s.code) == BPF_K) {
943 bpf_int32 v = vmap[val].const_val;
944 switch (BPF_OP(b->s.code)) {
951 v = (unsigned)v > b->s.k;
955 v = (unsigned)v >= b->s.k;
975 * Compute the symbolic value of expression of 's', and update
976 * anything it defines in the value table 'val'. If 'alter' is true,
977 * do various optimizations. This code would be cleaner if symbolic
978 * evaluation and code transformations weren't folded together.
981 opt_stmt(s, val, alter)
991 case BPF_LD|BPF_ABS|BPF_W:
992 case BPF_LD|BPF_ABS|BPF_H:
993 case BPF_LD|BPF_ABS|BPF_B:
994 v = F(s->code, s->k, 0L);
995 vstore(s, &val[A_ATOM], v, alter);
998 case BPF_LD|BPF_IND|BPF_W:
999 case BPF_LD|BPF_IND|BPF_H:
1000 case BPF_LD|BPF_IND|BPF_B:
1002 if (alter && vmap[v].is_const) {
1003 s->code = BPF_LD|BPF_ABS|BPF_SIZE(s->code);
1004 s->k += vmap[v].const_val;
1005 v = F(s->code, s->k, 0L);
1009 v = F(s->code, s->k, v);
1010 vstore(s, &val[A_ATOM], v, alter);
1013 case BPF_LD|BPF_LEN:
1014 v = F(s->code, 0L, 0L);
1015 vstore(s, &val[A_ATOM], v, alter);
1018 case BPF_LD|BPF_IMM:
1020 vstore(s, &val[A_ATOM], v, alter);
1023 case BPF_LDX|BPF_IMM:
1025 vstore(s, &val[X_ATOM], v, alter);
1028 case BPF_LDX|BPF_MSH|BPF_B:
1029 v = F(s->code, s->k, 0L);
1030 vstore(s, &val[X_ATOM], v, alter);
1033 case BPF_ALU|BPF_NEG:
1034 if (alter && vmap[val[A_ATOM]].is_const) {
1035 s->code = BPF_LD|BPF_IMM;
1036 s->k = -vmap[val[A_ATOM]].const_val;
1037 val[A_ATOM] = K(s->k);
1040 val[A_ATOM] = F(s->code, val[A_ATOM], 0L);
1043 case BPF_ALU|BPF_ADD|BPF_K:
1044 case BPF_ALU|BPF_SUB|BPF_K:
1045 case BPF_ALU|BPF_MUL|BPF_K:
1046 case BPF_ALU|BPF_DIV|BPF_K:
1047 case BPF_ALU|BPF_AND|BPF_K:
1048 case BPF_ALU|BPF_OR|BPF_K:
1049 case BPF_ALU|BPF_LSH|BPF_K:
1050 case BPF_ALU|BPF_RSH|BPF_K:
1051 op = BPF_OP(s->code);
1054 /* don't optimize away "sub #0"
1055 * as it may be needed later to
1056 * fixup the generated math code */
1057 if (op == BPF_ADD ||
1058 op == BPF_LSH || op == BPF_RSH ||
1063 if (op == BPF_MUL || op == BPF_AND) {
1064 s->code = BPF_LD|BPF_IMM;
1065 val[A_ATOM] = K(s->k);
1069 if (vmap[val[A_ATOM]].is_const) {
1070 fold_op(s, val[A_ATOM], K(s->k));
1071 val[A_ATOM] = K(s->k);
1075 val[A_ATOM] = F(s->code, val[A_ATOM], K(s->k));
1078 case BPF_ALU|BPF_ADD|BPF_X:
1079 case BPF_ALU|BPF_SUB|BPF_X:
1080 case BPF_ALU|BPF_MUL|BPF_X:
1081 case BPF_ALU|BPF_DIV|BPF_X:
1082 case BPF_ALU|BPF_AND|BPF_X:
1083 case BPF_ALU|BPF_OR|BPF_X:
1084 case BPF_ALU|BPF_LSH|BPF_X:
1085 case BPF_ALU|BPF_RSH|BPF_X:
1086 op = BPF_OP(s->code);
1087 if (alter && vmap[val[X_ATOM]].is_const) {
1088 if (vmap[val[A_ATOM]].is_const) {
1089 fold_op(s, val[A_ATOM], val[X_ATOM]);
1090 val[A_ATOM] = K(s->k);
1093 s->code = BPF_ALU|BPF_K|op;
1094 s->k = vmap[val[X_ATOM]].const_val;
1097 F(s->code, val[A_ATOM], K(s->k));
1102 * Check if we're doing something to an accumulator
1103 * that is 0, and simplify. This may not seem like
1104 * much of a simplification but it could open up further
1106 * XXX We could also check for mul by 1, etc.
1108 if (alter && vmap[val[A_ATOM]].is_const
1109 && vmap[val[A_ATOM]].const_val == 0) {
1110 if (op == BPF_ADD || op == BPF_OR) {
1111 s->code = BPF_MISC|BPF_TXA;
1112 vstore(s, &val[A_ATOM], val[X_ATOM], alter);
1115 else if (op == BPF_MUL || op == BPF_DIV ||
1116 op == BPF_AND || op == BPF_LSH || op == BPF_RSH) {
1117 s->code = BPF_LD|BPF_IMM;
1119 vstore(s, &val[A_ATOM], K(s->k), alter);
1122 else if (op == BPF_NEG) {
1127 val[A_ATOM] = F(s->code, val[A_ATOM], val[X_ATOM]);
1130 case BPF_MISC|BPF_TXA:
1131 vstore(s, &val[A_ATOM], val[X_ATOM], alter);
1134 case BPF_LD|BPF_MEM:
1136 if (alter && vmap[v].is_const) {
1137 s->code = BPF_LD|BPF_IMM;
1138 s->k = vmap[v].const_val;
1141 vstore(s, &val[A_ATOM], v, alter);
1144 case BPF_MISC|BPF_TAX:
1145 vstore(s, &val[X_ATOM], val[A_ATOM], alter);
1148 case BPF_LDX|BPF_MEM:
1150 if (alter && vmap[v].is_const) {
1151 s->code = BPF_LDX|BPF_IMM;
1152 s->k = vmap[v].const_val;
1155 vstore(s, &val[X_ATOM], v, alter);
1159 vstore(s, &val[s->k], val[A_ATOM], alter);
1163 vstore(s, &val[s->k], val[X_ATOM], alter);
1170 register struct stmt *s;
1171 register struct stmt *last[];
1177 if (atom == AX_ATOM) {
1188 last[atom]->code = NOP;
1196 register struct block *b;
1198 register struct slist *s;
1200 struct stmt *last[N_ATOMS];
1202 memset((char *)last, 0, sizeof last);
1204 for (s = b->stmts; s != 0; s = s->next)
1205 deadstmt(&s->s, last);
1206 deadstmt(&b->s, last);
1208 for (atom = 0; atom < N_ATOMS; ++atom)
1209 if (last[atom] && !ATOMELEM(b->out_use, atom)) {
1210 last[atom]->code = NOP;
1216 opt_blk(b, do_stmts)
1223 bpf_int32 aval, xval;
1226 for (s = b->stmts; s && s->next; s = s->next)
1227 if (BPF_CLASS(s->s.code) == BPF_JMP) {
1234 * Initialize the atom values.
1239 * We have no predecessors, so everything is undefined
1240 * upon entry to this block.
1242 memset((char *)b->val, 0, sizeof(b->val));
1245 * Inherit values from our predecessors.
1247 * First, get the values from the predecessor along the
1248 * first edge leading to this node.
1250 memcpy((char *)b->val, (char *)p->pred->val, sizeof(b->val));
1252 * Now look at all the other nodes leading to this node.
1253 * If, for the predecessor along that edge, a register
1254 * has a different value from the one we have (i.e.,
1255 * control paths are merging, and the merging paths
1256 * assign different values to that register), give the
1257 * register the undefined value of 0.
1259 while ((p = p->next) != NULL) {
1260 for (i = 0; i < N_ATOMS; ++i)
1261 if (b->val[i] != p->pred->val[i])
1265 aval = b->val[A_ATOM];
1266 xval = b->val[X_ATOM];
1267 for (s = b->stmts; s; s = s->next)
1268 opt_stmt(&s->s, b->val, do_stmts);
1271 * This is a special case: if we don't use anything from this
1272 * block, and we load the accumulator or index register with a
1273 * value that is already there, or if this block is a return,
1274 * eliminate all the statements.
1276 * XXX - what if it does a store?
1278 * XXX - why does it matter whether we use anything from this
1279 * block? If the accumulator or index register doesn't change
1280 * its value, isn't that OK even if we use that value?
1282 * XXX - if we load the accumulator with a different value,
1283 * and the block ends with a conditional branch, we obviously
1284 * can't eliminate it, as the branch depends on that value.
1285 * For the index register, the conditional branch only depends
1286 * on the index register value if the test is against the index
1287 * register value rather than a constant; if nothing uses the
1288 * value we put into the index register, and we're not testing
1289 * against the index register's value, and there aren't any
1290 * other problems that would keep us from eliminating this
1291 * block, can we eliminate it?
1294 ((b->out_use == 0 && aval != 0 && b->val[A_ATOM] == aval &&
1295 xval != 0 && b->val[X_ATOM] == xval) ||
1296 BPF_CLASS(b->s.code) == BPF_RET)) {
1297 if (b->stmts != 0) {
1306 * Set up values for branch optimizer.
1308 if (BPF_SRC(b->s.code) == BPF_K)
1309 b->oval = K(b->s.k);
1311 b->oval = b->val[X_ATOM];
1312 b->et.code = b->s.code;
1313 b->ef.code = -b->s.code;
1317 * Return true if any register that is used on exit from 'succ', has
1318 * an exit value that is different from the corresponding exit value
1322 use_conflict(b, succ)
1323 struct block *b, *succ;
1326 atomset use = succ->out_use;
1331 for (atom = 0; atom < N_ATOMS; ++atom)
1332 if (ATOMELEM(use, atom))
1333 if (b->val[atom] != succ->val[atom])
1338 static struct block *
1339 fold_edge(child, ep)
1340 struct block *child;
1344 int aval0, aval1, oval0, oval1;
1345 int code = ep->code;
1353 if (child->s.code != code)
1356 aval0 = child->val[A_ATOM];
1357 oval0 = child->oval;
1358 aval1 = ep->pred->val[A_ATOM];
1359 oval1 = ep->pred->oval;
1366 * The operands of the branch instructions are
1367 * identical, so the result is true if a true
1368 * branch was taken to get here, otherwise false.
1370 return sense ? JT(child) : JF(child);
1372 if (sense && code == (BPF_JMP|BPF_JEQ|BPF_K))
1374 * At this point, we only know the comparison if we
1375 * came down the true branch, and it was an equality
1376 * comparison with a constant.
1378 * I.e., if we came down the true branch, and the branch
1379 * was an equality comparison with a constant, we know the
1380 * accumulator contains that constant. If we came down
1381 * the false branch, or the comparison wasn't with a
1382 * constant, we don't know what was in the accumulator.
1384 * We rely on the fact that distinct constants have distinct
1397 register struct block *target;
1399 if (JT(ep->succ) == 0)
1402 if (JT(ep->succ) == JF(ep->succ)) {
1404 * Common branch targets can be eliminated, provided
1405 * there is no data dependency.
1407 if (!use_conflict(ep->pred, ep->succ->et.succ)) {
1409 ep->succ = JT(ep->succ);
1413 * For each edge dominator that matches the successor of this
1414 * edge, promote the edge successor to the its grandchild.
1416 * XXX We violate the set abstraction here in favor a reasonably
1420 for (i = 0; i < edgewords; ++i) {
1421 register bpf_u_int32 x = ep->edom[i];
1426 k += i * BITS_PER_WORD;
1428 target = fold_edge(ep->succ, edges[k]);
1430 * Check that there is no data dependency between
1431 * nodes that will be violated if we move the edge.
1433 if (target != 0 && !use_conflict(ep->pred, target)) {
1436 if (JT(target) != 0)
1438 * Start over unless we hit a leaf.
1454 struct block **diffp, **samep;
1462 * Make sure each predecessor loads the same value.
1465 val = ep->pred->val[A_ATOM];
1466 for (ep = ep->next; ep != 0; ep = ep->next)
1467 if (val != ep->pred->val[A_ATOM])
1470 if (JT(b->in_edges->pred) == b)
1471 diffp = &JT(b->in_edges->pred);
1473 diffp = &JF(b->in_edges->pred);
1480 if (JT(*diffp) != JT(b))
1483 if (!SET_MEMBER((*diffp)->dom, b->id))
1486 if ((*diffp)->val[A_ATOM] != val)
1489 diffp = &JF(*diffp);
1492 samep = &JF(*diffp);
1497 if (JT(*samep) != JT(b))
1500 if (!SET_MEMBER((*samep)->dom, b->id))
1503 if ((*samep)->val[A_ATOM] == val)
1506 /* XXX Need to check that there are no data dependencies
1507 between dp0 and dp1. Currently, the code generator
1508 will not produce such dependencies. */
1509 samep = &JF(*samep);
1512 /* XXX This doesn't cover everything. */
1513 for (i = 0; i < N_ATOMS; ++i)
1514 if ((*samep)->val[i] != pred->val[i])
1517 /* Pull up the node. */
1523 * At the top of the chain, each predecessor needs to point at the
1524 * pulled up node. Inside the chain, there is only one predecessor
1528 for (ep = b->in_edges; ep != 0; ep = ep->next) {
1529 if (JT(ep->pred) == b)
1530 JT(ep->pred) = pull;
1532 JF(ep->pred) = pull;
1547 struct block **diffp, **samep;
1555 * Make sure each predecessor loads the same value.
1557 val = ep->pred->val[A_ATOM];
1558 for (ep = ep->next; ep != 0; ep = ep->next)
1559 if (val != ep->pred->val[A_ATOM])
1562 if (JT(b->in_edges->pred) == b)
1563 diffp = &JT(b->in_edges->pred);
1565 diffp = &JF(b->in_edges->pred);
1572 if (JF(*diffp) != JF(b))
1575 if (!SET_MEMBER((*diffp)->dom, b->id))
1578 if ((*diffp)->val[A_ATOM] != val)
1581 diffp = &JT(*diffp);
1584 samep = &JT(*diffp);
1589 if (JF(*samep) != JF(b))
1592 if (!SET_MEMBER((*samep)->dom, b->id))
1595 if ((*samep)->val[A_ATOM] == val)
1598 /* XXX Need to check that there are no data dependencies
1599 between diffp and samep. Currently, the code generator
1600 will not produce such dependencies. */
1601 samep = &JT(*samep);
1604 /* XXX This doesn't cover everything. */
1605 for (i = 0; i < N_ATOMS; ++i)
1606 if ((*samep)->val[i] != pred->val[i])
1609 /* Pull up the node. */
1615 * At the top of the chain, each predecessor needs to point at the
1616 * pulled up node. Inside the chain, there is only one predecessor
1620 for (ep = b->in_edges; ep != 0; ep = ep->next) {
1621 if (JT(ep->pred) == b)
1622 JT(ep->pred) = pull;
1624 JF(ep->pred) = pull;
1634 opt_blks(root, do_stmts)
1642 maxlevel = root->level;
1645 for (i = maxlevel; i >= 0; --i)
1646 for (p = levels[i]; p; p = p->link)
1647 opt_blk(p, do_stmts);
1651 * No point trying to move branches; it can't possibly
1652 * make a difference at this point.
1656 for (i = 1; i <= maxlevel; ++i) {
1657 for (p = levels[i]; p; p = p->link) {
1664 for (i = 1; i <= maxlevel; ++i) {
1665 for (p = levels[i]; p; p = p->link) {
1673 link_inedge(parent, child)
1674 struct edge *parent;
1675 struct block *child;
1677 parent->next = child->in_edges;
1678 child->in_edges = parent;
1688 for (i = 0; i < n_blocks; ++i)
1689 blocks[i]->in_edges = 0;
1692 * Traverse the graph, adding each edge to the predecessor
1693 * list of its successors. Skip the leaves (i.e. level 0).
1695 for (i = root->level; i > 0; --i) {
1696 for (b = levels[i]; b != 0; b = b->link) {
1697 link_inedge(&b->et, JT(b));
1698 link_inedge(&b->ef, JF(b));
1707 struct slist *tmp, *s;
1711 while (BPF_CLASS((*b)->s.code) == BPF_JMP && JT(*b) == JF(*b))
1720 * If the root node is a return, then there is no
1721 * point executing any statements (since the bpf machine
1722 * has no side effects).
1724 if (BPF_CLASS((*b)->s.code) == BPF_RET)
1729 opt_loop(root, do_stmts)
1736 printf("opt_loop(root, %d) begin\n", do_stmts);
1747 opt_blks(root, do_stmts);
1750 printf("opt_loop(root, %d) bottom, done=%d\n", do_stmts, done);
1758 * Optimize the filter code in its dag representation.
1762 struct block **rootp;
1771 intern_blocks(root);
1774 printf("after intern_blocks()\n");
1781 printf("after opt_root()\n");
1794 if (BPF_CLASS(p->s.code) != BPF_RET) {
1802 * Mark code array such that isMarked(i) is true
1803 * only for nodes that are alive.
1814 * True iff the two stmt lists load the same value from the packet into
1819 struct slist *x, *y;
1822 while (x && x->s.code == NOP)
1824 while (y && y->s.code == NOP)
1830 if (x->s.code != y->s.code || x->s.k != y->s.k)
1839 struct block *b0, *b1;
1841 if (b0->s.code == b1->s.code &&
1842 b0->s.k == b1->s.k &&
1843 b0->et.succ == b1->et.succ &&
1844 b0->ef.succ == b1->ef.succ)
1845 return eq_slist(b0->stmts, b1->stmts);
1855 int done1; /* don't shadow global */
1858 for (i = 0; i < n_blocks; ++i)
1859 blocks[i]->link = 0;
1863 for (i = n_blocks - 1; --i >= 0; ) {
1864 if (!isMarked(blocks[i]))
1866 for (j = i + 1; j < n_blocks; ++j) {
1867 if (!isMarked(blocks[j]))
1869 if (eq_blk(blocks[i], blocks[j])) {
1870 blocks[i]->link = blocks[j]->link ?
1871 blocks[j]->link : blocks[j];
1876 for (i = 0; i < n_blocks; ++i) {
1882 JT(p) = JT(p)->link;
1886 JF(p) = JF(p)->link;
1896 free((void *)vnode_base);
1898 free((void *)edges);
1899 free((void *)space);
1900 free((void *)levels);
1901 free((void *)blocks);
1905 * Return the number of stmts in 's'.
1913 for (; s; s = s->next)
1914 if (s->s.code != NOP)
1920 * Return the number of nodes reachable by 'p'.
1921 * All nodes should be initially unmarked.
1927 if (p == 0 || isMarked(p))
1930 return count_blocks(JT(p)) + count_blocks(JF(p)) + 1;
1934 * Do a depth first search on the flow graph, numbering the
1935 * the basic blocks, and entering them into the 'blocks' array.`
1943 if (p == 0 || isMarked(p))
1951 number_blks_r(JT(p));
1952 number_blks_r(JF(p));
1956 * Return the number of stmts in the flowgraph reachable by 'p'.
1957 * The nodes should be unmarked before calling.
1959 * Note that "stmts" means "instructions", and that this includes
1961 * side-effect statements in 'p' (slength(p->stmts));
1963 * statements in the true branch from 'p' (count_stmts(JT(p)));
1965 * statements in the false branch from 'p' (count_stmts(JF(p)));
1967 * the conditional jump itself (1);
1969 * an extra long jump if the true branch requires it (p->longjt);
1971 * an extra long jump if the false branch requires it (p->longjf).
1979 if (p == 0 || isMarked(p))
1982 n = count_stmts(JT(p)) + count_stmts(JF(p));
1983 return slength(p->stmts) + n + 1 + p->longjt + p->longjf;
1987 * Allocate memory. All allocation is done before optimization
1988 * is begun. A linear bound on the size of all data structures is computed
1989 * from the total number of blocks and/or statements.
1996 int i, n, max_stmts;
1999 * First, count the blocks, so we can malloc an array to map
2000 * block number to block. Then, put the blocks into the array.
2003 n = count_blocks(root);
2004 blocks = (struct block **)calloc(n, sizeof(*blocks));
2006 bpf_error("malloc");
2009 number_blks_r(root);
2011 n_edges = 2 * n_blocks;
2012 edges = (struct edge **)calloc(n_edges, sizeof(*edges));
2014 bpf_error("malloc");
2017 * The number of levels is bounded by the number of nodes.
2019 levels = (struct block **)calloc(n_blocks, sizeof(*levels));
2021 bpf_error("malloc");
2023 edgewords = n_edges / (8 * sizeof(bpf_u_int32)) + 1;
2024 nodewords = n_blocks / (8 * sizeof(bpf_u_int32)) + 1;
2027 space = (bpf_u_int32 *)malloc(2 * n_blocks * nodewords * sizeof(*space)
2028 + n_edges * edgewords * sizeof(*space));
2030 bpf_error("malloc");
2033 for (i = 0; i < n; ++i) {
2037 all_closure_sets = p;
2038 for (i = 0; i < n; ++i) {
2039 blocks[i]->closure = p;
2043 for (i = 0; i < n; ++i) {
2044 register struct block *b = blocks[i];
2052 b->ef.id = n_blocks + i;
2053 edges[n_blocks + i] = &b->ef;
2058 for (i = 0; i < n; ++i)
2059 max_stmts += slength(blocks[i]->stmts) + 1;
2061 * We allocate at most 3 value numbers per statement,
2062 * so this is an upper bound on the number of valnodes
2065 maxval = 3 * max_stmts;
2066 vmap = (struct vmapinfo *)calloc(maxval, sizeof(*vmap));
2067 vnode_base = (struct valnode *)calloc(maxval, sizeof(*vnode_base));
2068 if (vmap == NULL || vnode_base == NULL)
2069 bpf_error("malloc");
2073 * Some pointers used to convert the basic block form of the code,
2074 * into the array form that BPF requires. 'fstart' will point to
2075 * the malloc'd array while 'ftail' is used during the recursive traversal.
2077 static struct bpf_insn *fstart;
2078 static struct bpf_insn *ftail;
2085 * Returns true if successful. Returns false if a branch has
2086 * an offset that is too large. If so, we have marked that
2087 * branch so that on a subsequent iteration, it will be treated
2094 struct bpf_insn *dst;
2098 int extrajmps; /* number of extra jumps inserted */
2099 struct slist **offset = NULL;
2101 if (p == 0 || isMarked(p))
2105 if (convert_code_r(JF(p)) == 0)
2107 if (convert_code_r(JT(p)) == 0)
2110 slen = slength(p->stmts);
2111 dst = ftail -= (slen + 1 + p->longjt + p->longjf);
2112 /* inflate length by any extra jumps */
2114 p->offset = dst - fstart;
2116 /* generate offset[] for convenience */
2118 offset = (struct slist **)calloc(slen, sizeof(struct slist *));
2120 bpf_error("not enough core");
2125 for (off = 0; off < slen && src; off++) {
2127 printf("off=%d src=%x\n", off, src);
2134 for (src = p->stmts; src; src = src->next) {
2135 if (src->s.code == NOP)
2137 dst->code = (u_short)src->s.code;
2140 /* fill block-local relative jump */
2141 if (BPF_CLASS(src->s.code) != BPF_JMP || src->s.code == (BPF_JMP|BPF_JA)) {
2143 if (src->s.jt || src->s.jf) {
2144 bpf_error("illegal jmp destination");
2150 if (off == slen - 2) /*???*/
2156 const char *ljerr = "%s for block-local relative jump: off=%d";
2159 printf("code=%x off=%d %x %x\n", src->s.code,
2160 off, src->s.jt, src->s.jf);
2163 if (!src->s.jt || !src->s.jf) {
2164 bpf_error(ljerr, "no jmp destination", off);
2169 for (i = 0; i < slen; i++) {
2170 if (offset[i] == src->s.jt) {
2172 bpf_error(ljerr, "multiple matches", off);
2176 dst->jt = i - off - 1;
2179 if (offset[i] == src->s.jf) {
2181 bpf_error(ljerr, "multiple matches", off);
2184 dst->jf = i - off - 1;
2189 bpf_error(ljerr, "no destination found", off);
2201 bids[dst - fstart] = p->id + 1;
2203 dst->code = (u_short)p->s.code;
2207 off = JT(p)->offset - (p->offset + slen) - 1;
2209 /* offset too large for branch, must add a jump */
2210 if (p->longjt == 0) {
2211 /* mark this instruction and retry */
2215 /* branch if T to following jump */
2216 dst->jt = extrajmps;
2218 dst[extrajmps].code = BPF_JMP|BPF_JA;
2219 dst[extrajmps].k = off - extrajmps;
2223 off = JF(p)->offset - (p->offset + slen) - 1;
2225 /* offset too large for branch, must add a jump */
2226 if (p->longjf == 0) {
2227 /* mark this instruction and retry */
2231 /* branch if F to following jump */
2232 /* if two jumps are inserted, F goes to second one */
2233 dst->jf = extrajmps;
2235 dst[extrajmps].code = BPF_JMP|BPF_JA;
2236 dst[extrajmps].k = off - extrajmps;
2246 * Convert flowgraph intermediate representation to the
2247 * BPF array representation. Set *lenp to the number of instructions.
2249 * This routine does *NOT* leak the memory pointed to by fp. It *must
2250 * not* do free(fp) before returning fp; doing so would make no sense,
2251 * as the BPF array pointed to by the return value of icode_to_fcode()
2252 * must be valid - it's being returned for use in a bpf_program structure.
2254 * If it appears that icode_to_fcode() is leaking, the problem is that
2255 * the program using pcap_compile() is failing to free the memory in
2256 * the BPF program when it's done - the leak is in the program, not in
2257 * the routine that happens to be allocating the memory. (By analogy, if
2258 * a program calls fopen() without ever calling fclose() on the FILE *,
2259 * it will leak the FILE structure; the leak is not in fopen(), it's in
2260 * the program.) Change the program to use pcap_freecode() when it's
2261 * done with the filter program. See the pcap man page.
2264 icode_to_fcode(root, lenp)
2269 struct bpf_insn *fp;
2272 * Loop doing convert_code_r() until no branches remain
2273 * with too-large offsets.
2277 n = *lenp = count_stmts(root);
2279 fp = (struct bpf_insn *)malloc(sizeof(*fp) * n);
2281 bpf_error("malloc");
2282 memset((char *)fp, 0, sizeof(*fp) * n);
2287 if (convert_code_r(root))
2296 * Make a copy of a BPF program and put it in the "fcode" member of
2299 * If we fail to allocate memory for the copy, fill in the "errbuf"
2300 * member of the "pcap_t" with an error message, and return -1;
2301 * otherwise, return 0.
2304 install_bpf_program(pcap_t *p, struct bpf_program *fp)
2309 * Validate the program.
2311 if (!bpf_validate(fp->bf_insns, fp->bf_len)) {
2312 snprintf(p->errbuf, sizeof(p->errbuf),
2313 "BPF program is not valid");
2318 * Free up any already installed program.
2320 pcap_freecode(&p->fcode);
2322 prog_size = sizeof(*fp->bf_insns) * fp->bf_len;
2323 p->fcode.bf_len = fp->bf_len;
2324 p->fcode.bf_insns = (struct bpf_insn *)malloc(prog_size);
2325 if (p->fcode.bf_insns == NULL) {
2326 snprintf(p->errbuf, sizeof(p->errbuf),
2327 "malloc: %s", pcap_strerror(errno));
2330 memcpy(p->fcode.bf_insns, fp->bf_insns, prog_size);
2339 struct bpf_program f;
2341 memset(bids, 0, sizeof bids);
2342 f.bf_insns = icode_to_fcode(root, &f.bf_len);
2345 free((char *)f.bf_insns);