]>
The Tcpdump Group git mirrors - libpcap/blob - optimize.c
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.82 2004-11-14 00:28:18 guy Exp $ (LBL)";
42 #ifdef HAVE_OS_PROTO_H
51 * Represents a deleted instruction.
56 * Register numbers for use-def values.
57 * 0 through BPF_MEMWORDS-1 represent the corresponding scratch memory
58 * location. A_ATOM is the accumulator and X_ATOM is the index
61 #define A_ATOM BPF_MEMWORDS
62 #define X_ATOM (BPF_MEMWORDS+1)
65 * This define is used to represent *both* the accumulator and
66 * x register in use-def computations.
67 * Currently, the use-def code assumes only one definition per instruction.
69 #define AX_ATOM N_ATOMS
72 * A flag to indicate that further optimization is needed.
73 * Iterative passes are continued until a given pass yields no
79 * A block is marked if only if its mark equals the current mark.
80 * Rather than traverse the code array, marking each item, 'cur_mark' is
81 * incremented. This automatically makes each element unmarked.
84 #define isMarked(p) ((p)->mark == cur_mark)
85 #define unMarkAll() cur_mark += 1
86 #define Mark(p) ((p)->mark = cur_mark)
88 static void opt_init(struct block
*);
89 static void opt_cleanup(void);
91 static void make_marks(struct block
*);
92 static void mark_code(struct block
*);
94 static void intern_blocks(struct block
*);
96 static int eq_slist(struct slist
*, struct slist
*);
98 static void find_levels_r(struct block
*);
100 static void find_levels(struct block
*);
101 static void find_dom(struct block
*);
102 static void propedom(struct edge
*);
103 static void find_edom(struct block
*);
104 static void find_closure(struct block
*);
105 static int atomuse(struct stmt
*);
106 static int atomdef(struct stmt
*);
107 static void compute_local_ud(struct block
*);
108 static void find_ud(struct block
*);
109 static void init_val(void);
110 static int F(int, int, int);
111 static inline void vstore(struct stmt
*, int *, int, int);
112 static void opt_blk(struct block
*, int);
113 static int use_conflict(struct block
*, struct block
*);
114 static void opt_j(struct edge
*);
115 static void or_pullup(struct block
*);
116 static void and_pullup(struct block
*);
117 static void opt_blks(struct block
*, int);
118 static inline void link_inedge(struct edge
*, struct block
*);
119 static void find_inedges(struct block
*);
120 static void opt_root(struct block
**);
121 static void opt_loop(struct block
*, int);
122 static void fold_op(struct stmt
*, int, int);
123 static inline struct slist
*this_op(struct slist
*);
124 static void opt_not(struct block
*);
125 static void opt_peep(struct block
*);
126 static void opt_stmt(struct stmt
*, int[], int);
127 static void deadstmt(struct stmt
*, struct stmt
*[]);
128 static void opt_deadstores(struct block
*);
129 static struct block
*fold_edge(struct block
*, struct edge
*);
130 static inline int eq_blk(struct block
*, struct block
*);
131 static int slength(struct slist
*);
132 static int count_blocks(struct block
*);
133 static void number_blks_r(struct block
*);
134 static int count_stmts(struct block
*);
135 static int convert_code_r(struct block
*);
137 static void opt_dump(struct block
*);
141 struct block
**blocks
;
146 * A bit vector set representation of the dominators.
147 * We round up the set size to the next power of two.
149 static int nodewords
;
150 static int edgewords
;
151 struct block
**levels
;
153 #define BITS_PER_WORD (8*sizeof(bpf_u_int32))
155 * True if a is in uset {p}
157 #define SET_MEMBER(p, a) \
158 ((p)[(unsigned)(a) / BITS_PER_WORD] & (1 << ((unsigned)(a) % BITS_PER_WORD)))
163 #define SET_INSERT(p, a) \
164 (p)[(unsigned)(a) / BITS_PER_WORD] |= (1 << ((unsigned)(a) % BITS_PER_WORD))
167 * Delete 'a' from uset p.
169 #define SET_DELETE(p, a) \
170 (p)[(unsigned)(a) / BITS_PER_WORD] &= ~(1 << ((unsigned)(a) % BITS_PER_WORD))
175 #define SET_INTERSECT(a, b, n)\
177 register bpf_u_int32 *_x = a, *_y = b;\
178 register int _n = n;\
179 while (--_n >= 0) *_x++ &= *_y++;\
185 #define SET_SUBTRACT(a, b, n)\
187 register bpf_u_int32 *_x = a, *_y = b;\
188 register int _n = n;\
189 while (--_n >= 0) *_x++ &=~ *_y++;\
195 #define SET_UNION(a, b, n)\
197 register bpf_u_int32 *_x = a, *_y = b;\
198 register int _n = n;\
199 while (--_n >= 0) *_x++ |= *_y++;\
202 static uset all_dom_sets
;
203 static uset all_closure_sets
;
204 static uset all_edge_sets
;
207 #define MAX(a,b) ((a)>(b)?(a):(b))
223 find_levels_r(JT(b
));
224 find_levels_r(JF(b
));
225 level
= MAX(JT(b
)->level
, JF(b
)->level
) + 1;
229 b
->link
= levels
[level
];
234 * Level graph. The levels go from 0 at the leaves to
235 * N_LEVELS at the root. The levels[] array points to the
236 * first node of the level list, whose elements are linked
237 * with the 'link' field of the struct block.
243 memset((char *)levels
, 0, n_blocks
* sizeof(*levels
));
249 * Find dominator relationships.
250 * Assumes graph has been leveled.
261 * Initialize sets to contain all nodes.
264 i
= n_blocks
* nodewords
;
267 /* Root starts off empty. */
268 for (i
= nodewords
; --i
>= 0;)
271 /* root->level is the highest level no found. */
272 for (i
= root
->level
; i
>= 0; --i
) {
273 for (b
= levels
[i
]; b
; b
= b
->link
) {
274 SET_INSERT(b
->dom
, b
->id
);
277 SET_INTERSECT(JT(b
)->dom
, b
->dom
, nodewords
);
278 SET_INTERSECT(JF(b
)->dom
, b
->dom
, nodewords
);
287 SET_INSERT(ep
->edom
, ep
->id
);
289 SET_INTERSECT(ep
->succ
->et
.edom
, ep
->edom
, edgewords
);
290 SET_INTERSECT(ep
->succ
->ef
.edom
, ep
->edom
, edgewords
);
295 * Compute edge dominators.
296 * Assumes graph has been leveled and predecessors established.
307 for (i
= n_edges
* edgewords
; --i
>= 0; )
310 /* root->level is the highest level no found. */
311 memset(root
->et
.edom
, 0, edgewords
* sizeof(*(uset
)0));
312 memset(root
->ef
.edom
, 0, edgewords
* sizeof(*(uset
)0));
313 for (i
= root
->level
; i
>= 0; --i
) {
314 for (b
= levels
[i
]; b
!= 0; b
= b
->link
) {
322 * Find the backwards transitive closure of the flow graph. These sets
323 * are backwards in the sense that we find the set of nodes that reach
324 * a given node, not the set of nodes that can be reached by a node.
326 * Assumes graph has been leveled.
336 * Initialize sets to contain no nodes.
338 memset((char *)all_closure_sets
, 0,
339 n_blocks
* nodewords
* sizeof(*all_closure_sets
));
341 /* root->level is the highest level no found. */
342 for (i
= root
->level
; i
>= 0; --i
) {
343 for (b
= levels
[i
]; b
; b
= b
->link
) {
344 SET_INSERT(b
->closure
, b
->id
);
347 SET_UNION(JT(b
)->closure
, b
->closure
, nodewords
);
348 SET_UNION(JF(b
)->closure
, b
->closure
, nodewords
);
354 * Return the register number that is used by s. If A and X are both
355 * used, return AX_ATOM. If no register is used, return -1.
357 * The implementation should probably change to an array access.
363 register int c
= s
->code
;
368 switch (BPF_CLASS(c
)) {
371 return (BPF_RVAL(c
) == BPF_A
) ? A_ATOM
:
372 (BPF_RVAL(c
) == BPF_X
) ? X_ATOM
: -1;
376 return (BPF_MODE(c
) == BPF_IND
) ? X_ATOM
:
377 (BPF_MODE(c
) == BPF_MEM
) ? s
->k
: -1;
387 if (BPF_SRC(c
) == BPF_X
)
392 return BPF_MISCOP(c
) == BPF_TXA
? X_ATOM
: A_ATOM
;
399 * Return the register number that is defined by 's'. We assume that
400 * a single stmt cannot define more than one register. If no register
401 * is defined, return -1.
403 * The implementation should probably change to an array access.
412 switch (BPF_CLASS(s
->code
)) {
426 return BPF_MISCOP(s
->code
) == BPF_TAX
? X_ATOM
: A_ATOM
;
432 * Compute the sets of registers used, defined, and killed by 'b'.
434 * "Used" means that a statement in 'b' uses the register before any
435 * statement in 'b' defines it.
436 * "Defined" means that a statement in 'b' defines it.
437 * "Killed" means that a statement in 'b' defines it before any
438 * statement in 'b' uses it.
445 atomset def
= 0, use
= 0, kill
= 0;
448 for (s
= b
->stmts
; s
; s
= s
->next
) {
449 if (s
->s
.code
== NOP
)
451 atom
= atomuse(&s
->s
);
453 if (atom
== AX_ATOM
) {
454 if (!ATOMELEM(def
, X_ATOM
))
455 use
|= ATOMMASK(X_ATOM
);
456 if (!ATOMELEM(def
, A_ATOM
))
457 use
|= ATOMMASK(A_ATOM
);
459 else if (atom
< N_ATOMS
) {
460 if (!ATOMELEM(def
, atom
))
461 use
|= ATOMMASK(atom
);
466 atom
= atomdef(&s
->s
);
468 if (!ATOMELEM(use
, atom
))
469 kill
|= ATOMMASK(atom
);
470 def
|= ATOMMASK(atom
);
473 if (BPF_CLASS(b
->s
.code
) == BPF_JMP
) {
475 * XXX - what about RET?
477 atom
= atomuse(&b
->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
);
500 * Assume graph is already leveled.
510 * root->level is the highest level no found;
511 * count down from there.
513 maxlevel
= root
->level
;
514 for (i
= maxlevel
; i
>= 0; --i
)
515 for (p
= levels
[i
]; p
; p
= p
->link
) {
520 for (i
= 1; i
<= maxlevel
; ++i
) {
521 for (p
= levels
[i
]; p
; p
= p
->link
) {
522 p
->out_use
|= JT(p
)->in_use
| JF(p
)->in_use
;
523 p
->in_use
|= p
->out_use
&~ p
->kill
;
529 * These data structures are used in a Cocke and Shwarz style
530 * value numbering scheme. Since the flowgraph is acyclic,
531 * exit values can be propagated from a node's predecessors
532 * provided it is uniquely defined.
538 struct valnode
*next
;
542 static struct valnode
*hashtbl
[MODULUS
];
546 /* Integer constants mapped with the load immediate opcode. */
547 #define K(i) F(BPF_LD|BPF_IMM|BPF_W, i, 0L)
554 struct vmapinfo
*vmap
;
555 struct valnode
*vnode_base
;
556 struct valnode
*next_vnode
;
562 next_vnode
= vnode_base
;
563 memset((char *)vmap
, 0, maxval
* sizeof(*vmap
));
564 memset((char *)hashtbl
, 0, sizeof hashtbl
);
567 /* Because we really don't have an IR, this stuff is a little messy. */
577 hash
= (u_int
)code
^ (v0
<< 4) ^ (v1
<< 8);
580 for (p
= hashtbl
[hash
]; p
; p
= p
->next
)
581 if (p
->code
== code
&& p
->v0
== v0
&& p
->v1
== v1
)
585 if (BPF_MODE(code
) == BPF_IMM
&&
586 (BPF_CLASS(code
) == BPF_LD
|| BPF_CLASS(code
) == BPF_LDX
)) {
587 vmap
[val
].const_val
= v0
;
588 vmap
[val
].is_const
= 1;
595 p
->next
= hashtbl
[hash
];
602 vstore(s
, valp
, newval
, alter
)
608 if (alter
&& *valp
== newval
)
621 a
= vmap
[v0
].const_val
;
622 b
= vmap
[v1
].const_val
;
624 switch (BPF_OP(s
->code
)) {
639 bpf_error("division by zero");
667 s
->code
= BPF_LD
|BPF_IMM
;
671 static inline struct slist
*
675 while (s
!= 0 && s
->s
.code
== NOP
)
684 struct block
*tmp
= JT(b
);
695 struct slist
*next
, *last
;
703 for (/*empty*/; /*empty*/; s
= next
) {
709 break; /* nothing left in the block */
712 * Find the next real instruction after that one
715 next
= this_op(s
->next
);
717 break; /* no next instruction */
721 * st M[k] --> st M[k]
724 if (s
->s
.code
== BPF_ST
&&
725 next
->s
.code
== (BPF_LDX
|BPF_MEM
) &&
726 s
->s
.k
== next
->s
.k
) {
728 next
->s
.code
= BPF_MISC
|BPF_TAX
;
734 if (s
->s
.code
== (BPF_LD
|BPF_IMM
) &&
735 next
->s
.code
== (BPF_MISC
|BPF_TAX
)) {
736 s
->s
.code
= BPF_LDX
|BPF_IMM
;
737 next
->s
.code
= BPF_MISC
|BPF_TXA
;
741 * This is an ugly special case, but it happens
742 * when you say tcp[k] or udp[k] where k is a constant.
744 if (s
->s
.code
== (BPF_LD
|BPF_IMM
)) {
745 struct slist
*add
, *tax
, *ild
;
748 * Check that X isn't used on exit from this
749 * block (which the optimizer might cause).
750 * We know the code generator won't generate
751 * any local dependencies.
753 if (ATOMELEM(b
->out_use
, X_ATOM
))
757 * Check that the instruction following the ldi
758 * is an addx, or it's an ldxms with an addx
759 * following it (with 0 or more nops between the
762 if (next
->s
.code
!= (BPF_LDX
|BPF_MSH
|BPF_B
))
765 add
= this_op(next
->next
);
766 if (add
== 0 || add
->s
.code
!= (BPF_ALU
|BPF_ADD
|BPF_X
))
770 * Check that a tax follows that (with 0 or more
771 * nops between them).
773 tax
= this_op(add
->next
);
774 if (tax
== 0 || tax
->s
.code
!= (BPF_MISC
|BPF_TAX
))
778 * Check that an ild follows that (with 0 or more
779 * nops between them).
781 ild
= this_op(tax
->next
);
782 if (ild
== 0 || BPF_CLASS(ild
->s
.code
) != BPF_LD
||
783 BPF_MODE(ild
->s
.code
) != BPF_IND
)
786 * We want to turn this sequence:
789 * (005) ldxms [14] {next} -- optional
792 * (008) ild [x+0] {ild}
794 * into this sequence:
802 * XXX We need to check that X is not
803 * subsequently used, because we want to change
804 * what'll be in it after this sequence.
806 * We know we can eliminate the accumulator
807 * modifications earlier in the sequence since
808 * it is defined by the last stmt of this sequence
809 * (i.e., the last statement of the sequence loads
810 * a value into the accumulator, so we can eliminate
811 * earlier operations on the accumulator).
821 * If the comparison at the end of a block is an equality
822 * comparison against a constant, and nobody uses the value
823 * we leave in the A register at the end of a block, and
824 * the operation preceding the comparison is an arithmetic
825 * operation, we can sometime optimize it away.
827 if (b
->s
.code
== (BPF_JMP
|BPF_JEQ
|BPF_K
) &&
828 !ATOMELEM(b
->out_use
, A_ATOM
)) {
830 * We can optimize away certain subtractions of the
833 if (last
->s
.code
== (BPF_ALU
|BPF_SUB
|BPF_X
)) {
834 val
= b
->val
[X_ATOM
];
835 if (vmap
[val
].is_const
) {
837 * If we have a subtract to do a comparison,
838 * and the X register is a known constant,
839 * we can merge this value into the
845 b
->s
.k
+= vmap
[val
].const_val
;
848 } else if (b
->s
.k
== 0) {
850 * If the X register isn't a constant,
851 * and the comparison in the test is
852 * against 0, we can compare with the
853 * X register, instead:
859 b
->s
.code
= BPF_JMP
|BPF_JEQ
|BPF_X
;
864 * Likewise, a constant subtract can be simplified:
867 * jeq #y -> jeq #(x+y)
869 else if (last
->s
.code
== (BPF_ALU
|BPF_SUB
|BPF_K
)) {
875 * And, similarly, a constant AND can be simplified
876 * if we're testing against 0, i.e.:
881 else if (last
->s
.code
== (BPF_ALU
|BPF_AND
|BPF_K
) &&
884 b
->s
.code
= BPF_JMP
|BPF_K
|BPF_JSET
;
892 * jset #ffffffff -> always
894 if (b
->s
.code
== (BPF_JMP
|BPF_K
|BPF_JSET
)) {
897 if (b
->s
.k
== 0xffffffff)
901 * If the accumulator is a known constant, we can compute the
904 val
= b
->val
[A_ATOM
];
905 if (vmap
[val
].is_const
&& BPF_SRC(b
->s
.code
) == BPF_K
) {
906 bpf_int32 v
= vmap
[val
].const_val
;
907 switch (BPF_OP(b
->s
.code
)) {
914 v
= (unsigned)v
> b
->s
.k
;
918 v
= (unsigned)v
>= b
->s
.k
;
938 * Compute the symbolic value of expression of 's', and update
939 * anything it defines in the value table 'val'. If 'alter' is true,
940 * do various optimizations. This code would be cleaner if symbolic
941 * evaluation and code transformations weren't folded together.
944 opt_stmt(s
, val
, alter
)
954 case BPF_LD
|BPF_ABS
|BPF_W
:
955 case BPF_LD
|BPF_ABS
|BPF_H
:
956 case BPF_LD
|BPF_ABS
|BPF_B
:
957 v
= F(s
->code
, s
->k
, 0L);
958 vstore(s
, &val
[A_ATOM
], v
, alter
);
961 case BPF_LD
|BPF_IND
|BPF_W
:
962 case BPF_LD
|BPF_IND
|BPF_H
:
963 case BPF_LD
|BPF_IND
|BPF_B
:
965 if (alter
&& vmap
[v
].is_const
) {
966 s
->code
= BPF_LD
|BPF_ABS
|BPF_SIZE(s
->code
);
967 s
->k
+= vmap
[v
].const_val
;
968 v
= F(s
->code
, s
->k
, 0L);
972 v
= F(s
->code
, s
->k
, v
);
973 vstore(s
, &val
[A_ATOM
], v
, alter
);
977 v
= F(s
->code
, 0L, 0L);
978 vstore(s
, &val
[A_ATOM
], v
, alter
);
983 vstore(s
, &val
[A_ATOM
], v
, alter
);
986 case BPF_LDX
|BPF_IMM
:
988 vstore(s
, &val
[X_ATOM
], v
, alter
);
991 case BPF_LDX
|BPF_MSH
|BPF_B
:
992 v
= F(s
->code
, s
->k
, 0L);
993 vstore(s
, &val
[X_ATOM
], v
, alter
);
996 case BPF_ALU
|BPF_NEG
:
997 if (alter
&& vmap
[val
[A_ATOM
]].is_const
) {
998 s
->code
= BPF_LD
|BPF_IMM
;
999 s
->k
= -vmap
[val
[A_ATOM
]].const_val
;
1000 val
[A_ATOM
] = K(s
->k
);
1003 val
[A_ATOM
] = F(s
->code
, val
[A_ATOM
], 0L);
1006 case BPF_ALU
|BPF_ADD
|BPF_K
:
1007 case BPF_ALU
|BPF_SUB
|BPF_K
:
1008 case BPF_ALU
|BPF_MUL
|BPF_K
:
1009 case BPF_ALU
|BPF_DIV
|BPF_K
:
1010 case BPF_ALU
|BPF_AND
|BPF_K
:
1011 case BPF_ALU
|BPF_OR
|BPF_K
:
1012 case BPF_ALU
|BPF_LSH
|BPF_K
:
1013 case BPF_ALU
|BPF_RSH
|BPF_K
:
1014 op
= BPF_OP(s
->code
);
1017 /* don't optimize away "sub #0"
1018 * as it may be needed later to
1019 * fixup the generated math code */
1020 if (op
== BPF_ADD
||
1021 op
== BPF_LSH
|| op
== BPF_RSH
||
1026 if (op
== BPF_MUL
|| op
== BPF_AND
) {
1027 s
->code
= BPF_LD
|BPF_IMM
;
1028 val
[A_ATOM
] = K(s
->k
);
1032 if (vmap
[val
[A_ATOM
]].is_const
) {
1033 fold_op(s
, val
[A_ATOM
], K(s
->k
));
1034 val
[A_ATOM
] = K(s
->k
);
1038 val
[A_ATOM
] = F(s
->code
, val
[A_ATOM
], K(s
->k
));
1041 case BPF_ALU
|BPF_ADD
|BPF_X
:
1042 case BPF_ALU
|BPF_SUB
|BPF_X
:
1043 case BPF_ALU
|BPF_MUL
|BPF_X
:
1044 case BPF_ALU
|BPF_DIV
|BPF_X
:
1045 case BPF_ALU
|BPF_AND
|BPF_X
:
1046 case BPF_ALU
|BPF_OR
|BPF_X
:
1047 case BPF_ALU
|BPF_LSH
|BPF_X
:
1048 case BPF_ALU
|BPF_RSH
|BPF_X
:
1049 op
= BPF_OP(s
->code
);
1050 if (alter
&& vmap
[val
[X_ATOM
]].is_const
) {
1051 if (vmap
[val
[A_ATOM
]].is_const
) {
1052 fold_op(s
, val
[A_ATOM
], val
[X_ATOM
]);
1053 val
[A_ATOM
] = K(s
->k
);
1056 s
->code
= BPF_ALU
|BPF_K
|op
;
1057 s
->k
= vmap
[val
[X_ATOM
]].const_val
;
1060 F(s
->code
, val
[A_ATOM
], K(s
->k
));
1065 * Check if we're doing something to an accumulator
1066 * that is 0, and simplify. This may not seem like
1067 * much of a simplification but it could open up further
1069 * XXX We could also check for mul by 1, etc.
1071 if (alter
&& vmap
[val
[A_ATOM
]].is_const
1072 && vmap
[val
[A_ATOM
]].const_val
== 0) {
1073 if (op
== BPF_ADD
|| op
== BPF_OR
) {
1074 s
->code
= BPF_MISC
|BPF_TXA
;
1075 vstore(s
, &val
[A_ATOM
], val
[X_ATOM
], alter
);
1078 else if (op
== BPF_MUL
|| op
== BPF_DIV
||
1079 op
== BPF_AND
|| op
== BPF_LSH
|| op
== BPF_RSH
) {
1080 s
->code
= BPF_LD
|BPF_IMM
;
1082 vstore(s
, &val
[A_ATOM
], K(s
->k
), alter
);
1085 else if (op
== BPF_NEG
) {
1090 val
[A_ATOM
] = F(s
->code
, val
[A_ATOM
], val
[X_ATOM
]);
1093 case BPF_MISC
|BPF_TXA
:
1094 vstore(s
, &val
[A_ATOM
], val
[X_ATOM
], alter
);
1097 case BPF_LD
|BPF_MEM
:
1099 if (alter
&& vmap
[v
].is_const
) {
1100 s
->code
= BPF_LD
|BPF_IMM
;
1101 s
->k
= vmap
[v
].const_val
;
1104 vstore(s
, &val
[A_ATOM
], v
, alter
);
1107 case BPF_MISC
|BPF_TAX
:
1108 vstore(s
, &val
[X_ATOM
], val
[A_ATOM
], alter
);
1111 case BPF_LDX
|BPF_MEM
:
1113 if (alter
&& vmap
[v
].is_const
) {
1114 s
->code
= BPF_LDX
|BPF_IMM
;
1115 s
->k
= vmap
[v
].const_val
;
1118 vstore(s
, &val
[X_ATOM
], v
, alter
);
1122 vstore(s
, &val
[s
->k
], val
[A_ATOM
], alter
);
1126 vstore(s
, &val
[s
->k
], val
[X_ATOM
], alter
);
1133 register struct stmt
*s
;
1134 register struct stmt
*last
[];
1140 if (atom
== AX_ATOM
) {
1151 last
[atom
]->code
= NOP
;
1159 register struct block
*b
;
1161 register struct slist
*s
;
1163 struct stmt
*last
[N_ATOMS
];
1165 memset((char *)last
, 0, sizeof last
);
1167 for (s
= b
->stmts
; s
!= 0; s
= s
->next
)
1168 deadstmt(&s
->s
, last
);
1169 deadstmt(&b
->s
, last
);
1171 for (atom
= 0; atom
< N_ATOMS
; ++atom
)
1172 if (last
[atom
] && !ATOMELEM(b
->out_use
, atom
)) {
1173 last
[atom
]->code
= NOP
;
1179 opt_blk(b
, do_stmts
)
1186 bpf_int32 aval
, xval
;
1189 for (s
= b
->stmts
; s
&& s
->next
; s
= s
->next
)
1190 if (BPF_CLASS(s
->s
.code
) == BPF_JMP
) {
1197 * Initialize the atom values.
1202 * We have no predecessors, so everything is undefined
1203 * upon entry to this block.
1205 memset((char *)b
->val
, 0, sizeof(b
->val
));
1208 * Inherit values from our predecessors.
1210 memcpy((char *)b
->val
, (char *)p
->pred
->val
, sizeof(b
->val
));
1212 * If any register has an ambiguous value (i.e., control
1213 * paths are merging), give it the undefined value of 0.
1215 while ((p
= p
->next
) != NULL
) {
1216 for (i
= 0; i
< N_ATOMS
; ++i
)
1217 if (b
->val
[i
] != p
->pred
->val
[i
])
1221 aval
= b
->val
[A_ATOM
];
1222 xval
= b
->val
[X_ATOM
];
1223 for (s
= b
->stmts
; s
; s
= s
->next
)
1224 opt_stmt(&s
->s
, b
->val
, do_stmts
);
1227 * This is a special case: if we don't use anything from this
1228 * block, and we load the accumulator or index register with a
1229 * value that is already there, or if this block is a return,
1230 * eliminate all the statements.
1232 * XXX - what if it does a store?
1234 * XXX - why does it matter whether we use anything from this
1235 * block? If the accumulator or index register doesn't change
1236 * its value, isn't that OK even if we use that value?
1238 * XXX - if we load the accumulator with a different value,
1239 * and the block ends with a conditional branch, we obviously
1240 * can't eliminate it, as the branch depends on that value.
1241 * For the index register, the conditional branch only depends
1242 * on the index register value if the test is against the index
1243 * register value rather than a constant; if nothing uses the
1244 * value we put into the index register, and we're not testing
1245 * against the index register's value, and there aren't any
1246 * other problems that would keep us from eliminating this
1247 * block, can we eliminate it?
1250 ((b
->out_use
== 0 && aval
!= 0 && b
->val
[A_ATOM
] == aval
&&
1251 xval
!= 0 && b
->val
[X_ATOM
] == xval
) ||
1252 BPF_CLASS(b
->s
.code
) == BPF_RET
)) {
1253 if (b
->stmts
!= 0) {
1262 * Set up values for branch optimizer.
1264 if (BPF_SRC(b
->s
.code
) == BPF_K
)
1265 b
->oval
= K(b
->s
.k
);
1267 b
->oval
= b
->val
[X_ATOM
];
1268 b
->et
.code
= b
->s
.code
;
1269 b
->ef
.code
= -b
->s
.code
;
1273 * Return true if any register that is used on exit from 'succ', has
1274 * an exit value that is different from the corresponding exit value
1278 use_conflict(b
, succ
)
1279 struct block
*b
, *succ
;
1282 atomset use
= succ
->out_use
;
1287 for (atom
= 0; atom
< N_ATOMS
; ++atom
)
1288 if (ATOMELEM(use
, atom
))
1289 if (b
->val
[atom
] != succ
->val
[atom
])
1294 static struct block
*
1295 fold_edge(child
, ep
)
1296 struct block
*child
;
1300 int aval0
, aval1
, oval0
, oval1
;
1301 int code
= ep
->code
;
1309 if (child
->s
.code
!= code
)
1312 aval0
= child
->val
[A_ATOM
];
1313 oval0
= child
->oval
;
1314 aval1
= ep
->pred
->val
[A_ATOM
];
1315 oval1
= ep
->pred
->oval
;
1322 * The operands of the branch instructions are
1323 * identical, so the result is true if a true
1324 * branch was taken to get here, otherwise false.
1326 return sense
? JT(child
) : JF(child
);
1328 if (sense
&& code
== (BPF_JMP
|BPF_JEQ
|BPF_K
))
1330 * At this point, we only know the comparison if we
1331 * came down the true branch, and it was an equality
1332 * comparison with a constant.
1334 * I.e., if we came down the true branch, and the branch
1335 * was an equality comparison with a constant, we know the
1336 * accumulator contains that constant. If we came down
1337 * the false branch, or the comparison wasn't with a
1338 * constant, we don't know what was in the accumulator.
1340 * We rely on the fact that distinct constants have distinct
1353 register struct block
*target
;
1355 if (JT(ep
->succ
) == 0)
1358 if (JT(ep
->succ
) == JF(ep
->succ
)) {
1360 * Common branch targets can be eliminated, provided
1361 * there is no data dependency.
1363 if (!use_conflict(ep
->pred
, ep
->succ
->et
.succ
)) {
1365 ep
->succ
= JT(ep
->succ
);
1369 * For each edge dominator that matches the successor of this
1370 * edge, promote the edge successor to the its grandchild.
1372 * XXX We violate the set abstraction here in favor a reasonably
1376 for (i
= 0; i
< edgewords
; ++i
) {
1377 register bpf_u_int32 x
= ep
->edom
[i
];
1382 k
+= i
* BITS_PER_WORD
;
1384 target
= fold_edge(ep
->succ
, edges
[k
]);
1386 * Check that there is no data dependency between
1387 * nodes that will be violated if we move the edge.
1389 if (target
!= 0 && !use_conflict(ep
->pred
, target
)) {
1392 if (JT(target
) != 0)
1394 * Start over unless we hit a leaf.
1410 struct block
**diffp
, **samep
;
1418 * Make sure each predecessor loads the same value.
1421 val
= ep
->pred
->val
[A_ATOM
];
1422 for (ep
= ep
->next
; ep
!= 0; ep
= ep
->next
)
1423 if (val
!= ep
->pred
->val
[A_ATOM
])
1426 if (JT(b
->in_edges
->pred
) == b
)
1427 diffp
= &JT(b
->in_edges
->pred
);
1429 diffp
= &JF(b
->in_edges
->pred
);
1436 if (JT(*diffp
) != JT(b
))
1439 if (!SET_MEMBER((*diffp
)->dom
, b
->id
))
1442 if ((*diffp
)->val
[A_ATOM
] != val
)
1445 diffp
= &JF(*diffp
);
1448 samep
= &JF(*diffp
);
1453 if (JT(*samep
) != JT(b
))
1456 if (!SET_MEMBER((*samep
)->dom
, b
->id
))
1459 if ((*samep
)->val
[A_ATOM
] == val
)
1462 /* XXX Need to check that there are no data dependencies
1463 between dp0 and dp1. Currently, the code generator
1464 will not produce such dependencies. */
1465 samep
= &JF(*samep
);
1468 /* XXX This doesn't cover everything. */
1469 for (i
= 0; i
< N_ATOMS
; ++i
)
1470 if ((*samep
)->val
[i
] != pred
->val
[i
])
1473 /* Pull up the node. */
1479 * At the top of the chain, each predecessor needs to point at the
1480 * pulled up node. Inside the chain, there is only one predecessor
1484 for (ep
= b
->in_edges
; ep
!= 0; ep
= ep
->next
) {
1485 if (JT(ep
->pred
) == b
)
1486 JT(ep
->pred
) = pull
;
1488 JF(ep
->pred
) = pull
;
1503 struct block
**diffp
, **samep
;
1511 * Make sure each predecessor loads the same value.
1513 val
= ep
->pred
->val
[A_ATOM
];
1514 for (ep
= ep
->next
; ep
!= 0; ep
= ep
->next
)
1515 if (val
!= ep
->pred
->val
[A_ATOM
])
1518 if (JT(b
->in_edges
->pred
) == b
)
1519 diffp
= &JT(b
->in_edges
->pred
);
1521 diffp
= &JF(b
->in_edges
->pred
);
1528 if (JF(*diffp
) != JF(b
))
1531 if (!SET_MEMBER((*diffp
)->dom
, b
->id
))
1534 if ((*diffp
)->val
[A_ATOM
] != val
)
1537 diffp
= &JT(*diffp
);
1540 samep
= &JT(*diffp
);
1545 if (JF(*samep
) != JF(b
))
1548 if (!SET_MEMBER((*samep
)->dom
, b
->id
))
1551 if ((*samep
)->val
[A_ATOM
] == val
)
1554 /* XXX Need to check that there are no data dependencies
1555 between diffp and samep. Currently, the code generator
1556 will not produce such dependencies. */
1557 samep
= &JT(*samep
);
1560 /* XXX This doesn't cover everything. */
1561 for (i
= 0; i
< N_ATOMS
; ++i
)
1562 if ((*samep
)->val
[i
] != pred
->val
[i
])
1565 /* Pull up the node. */
1571 * At the top of the chain, each predecessor needs to point at the
1572 * pulled up node. Inside the chain, there is only one predecessor
1576 for (ep
= b
->in_edges
; ep
!= 0; ep
= ep
->next
) {
1577 if (JT(ep
->pred
) == b
)
1578 JT(ep
->pred
) = pull
;
1580 JF(ep
->pred
) = pull
;
1590 opt_blks(root
, do_stmts
)
1598 maxlevel
= root
->level
;
1601 for (i
= maxlevel
; i
>= 0; --i
)
1602 for (p
= levels
[i
]; p
; p
= p
->link
)
1603 opt_blk(p
, do_stmts
);
1607 * No point trying to move branches; it can't possibly
1608 * make a difference at this point.
1612 for (i
= 1; i
<= maxlevel
; ++i
) {
1613 for (p
= levels
[i
]; p
; p
= p
->link
) {
1620 for (i
= 1; i
<= maxlevel
; ++i
) {
1621 for (p
= levels
[i
]; p
; p
= p
->link
) {
1629 link_inedge(parent
, child
)
1630 struct edge
*parent
;
1631 struct block
*child
;
1633 parent
->next
= child
->in_edges
;
1634 child
->in_edges
= parent
;
1644 for (i
= 0; i
< n_blocks
; ++i
)
1645 blocks
[i
]->in_edges
= 0;
1648 * Traverse the graph, adding each edge to the predecessor
1649 * list of its successors. Skip the leaves (i.e. level 0).
1651 for (i
= root
->level
; i
> 0; --i
) {
1652 for (b
= levels
[i
]; b
!= 0; b
= b
->link
) {
1653 link_inedge(&b
->et
, JT(b
));
1654 link_inedge(&b
->ef
, JF(b
));
1663 struct slist
*tmp
, *s
;
1667 while (BPF_CLASS((*b
)->s
.code
) == BPF_JMP
&& JT(*b
) == JF(*b
))
1676 * If the root node is a return, then there is no
1677 * point executing any statements (since the bpf machine
1678 * has no side effects).
1680 if (BPF_CLASS((*b
)->s
.code
) == BPF_RET
)
1685 opt_loop(root
, do_stmts
)
1692 printf("opt_loop(root, %d) begin\n", do_stmts
);
1703 opt_blks(root
, do_stmts
);
1706 printf("opt_loop(root, %d) bottom, done=%d\n", do_stmts
, done
);
1714 * Optimize the filter code in its dag representation.
1718 struct block
**rootp
;
1727 intern_blocks(root
);
1730 printf("after intern_blocks()\n");
1737 printf("after opt_root()\n");
1750 if (BPF_CLASS(p
->s
.code
) != BPF_RET
) {
1758 * Mark code array such that isMarked(i) is true
1759 * only for nodes that are alive.
1770 * True iff the two stmt lists load the same value from the packet into
1775 struct slist
*x
, *y
;
1778 while (x
&& x
->s
.code
== NOP
)
1780 while (y
&& y
->s
.code
== NOP
)
1786 if (x
->s
.code
!= y
->s
.code
|| x
->s
.k
!= y
->s
.k
)
1795 struct block
*b0
, *b1
;
1797 if (b0
->s
.code
== b1
->s
.code
&&
1798 b0
->s
.k
== b1
->s
.k
&&
1799 b0
->et
.succ
== b1
->et
.succ
&&
1800 b0
->ef
.succ
== b1
->ef
.succ
)
1801 return eq_slist(b0
->stmts
, b1
->stmts
);
1814 for (i
= 0; i
< n_blocks
; ++i
)
1815 blocks
[i
]->link
= 0;
1819 for (i
= n_blocks
- 1; --i
>= 0; ) {
1820 if (!isMarked(blocks
[i
]))
1822 for (j
= i
+ 1; j
< n_blocks
; ++j
) {
1823 if (!isMarked(blocks
[j
]))
1825 if (eq_blk(blocks
[i
], blocks
[j
])) {
1826 blocks
[i
]->link
= blocks
[j
]->link
?
1827 blocks
[j
]->link
: blocks
[j
];
1832 for (i
= 0; i
< n_blocks
; ++i
) {
1838 JT(p
) = JT(p
)->link
;
1842 JF(p
) = JF(p
)->link
;
1852 free((void *)vnode_base
);
1854 free((void *)edges
);
1855 free((void *)space
);
1856 free((void *)levels
);
1857 free((void *)blocks
);
1861 * Return the number of stmts in 's'.
1869 for (; s
; s
= s
->next
)
1870 if (s
->s
.code
!= NOP
)
1876 * Return the number of nodes reachable by 'p'.
1877 * All nodes should be initially unmarked.
1883 if (p
== 0 || isMarked(p
))
1886 return count_blocks(JT(p
)) + count_blocks(JF(p
)) + 1;
1890 * Do a depth first search on the flow graph, numbering the
1891 * the basic blocks, and entering them into the 'blocks' array.`
1899 if (p
== 0 || isMarked(p
))
1907 number_blks_r(JT(p
));
1908 number_blks_r(JF(p
));
1912 * Return the number of stmts in the flowgraph reachable by 'p'.
1913 * The nodes should be unmarked before calling.
1915 * Note that "stmts" means "instructions", and that this includes
1917 * side-effect statements in 'p' (slength(p->stmts));
1919 * statements in the true branch from 'p' (count_stmts(JT(p)));
1921 * statements in the false branch from 'p' (count_stmts(JF(p)));
1923 * the conditional jump itself (1);
1925 * an extra long jump if the true branch requires it (p->longjt);
1927 * an extra long jump if the false branch requires it (p->longjf).
1935 if (p
== 0 || isMarked(p
))
1938 n
= count_stmts(JT(p
)) + count_stmts(JF(p
));
1939 return slength(p
->stmts
) + n
+ 1 + p
->longjt
+ p
->longjf
;
1943 * Allocate memory. All allocation is done before optimization
1944 * is begun. A linear bound on the size of all data structures is computed
1945 * from the total number of blocks and/or statements.
1952 int i
, n
, max_stmts
;
1955 * First, count the blocks, so we can malloc an array to map
1956 * block number to block. Then, put the blocks into the array.
1959 n
= count_blocks(root
);
1960 blocks
= (struct block
**)malloc(n
* sizeof(*blocks
));
1962 bpf_error("malloc");
1965 number_blks_r(root
);
1967 n_edges
= 2 * n_blocks
;
1968 edges
= (struct edge
**)malloc(n_edges
* sizeof(*edges
));
1970 bpf_error("malloc");
1973 * The number of levels is bounded by the number of nodes.
1975 levels
= (struct block
**)malloc(n_blocks
* sizeof(*levels
));
1977 bpf_error("malloc");
1979 edgewords
= n_edges
/ (8 * sizeof(bpf_u_int32
)) + 1;
1980 nodewords
= n_blocks
/ (8 * sizeof(bpf_u_int32
)) + 1;
1983 space
= (bpf_u_int32
*)malloc(2 * n_blocks
* nodewords
* sizeof(*space
)
1984 + n_edges
* edgewords
* sizeof(*space
));
1986 bpf_error("malloc");
1989 for (i
= 0; i
< n
; ++i
) {
1993 all_closure_sets
= p
;
1994 for (i
= 0; i
< n
; ++i
) {
1995 blocks
[i
]->closure
= p
;
1999 for (i
= 0; i
< n
; ++i
) {
2000 register struct block
*b
= blocks
[i
];
2008 b
->ef
.id
= n_blocks
+ i
;
2009 edges
[n_blocks
+ i
] = &b
->ef
;
2014 for (i
= 0; i
< n
; ++i
)
2015 max_stmts
+= slength(blocks
[i
]->stmts
) + 1;
2017 * We allocate at most 3 value numbers per statement,
2018 * so this is an upper bound on the number of valnodes
2021 maxval
= 3 * max_stmts
;
2022 vmap
= (struct vmapinfo
*)malloc(maxval
* sizeof(*vmap
));
2023 vnode_base
= (struct valnode
*)malloc(maxval
* sizeof(*vnode_base
));
2024 if (vmap
== NULL
|| vnode_base
== NULL
)
2025 bpf_error("malloc");
2029 * Some pointers used to convert the basic block form of the code,
2030 * into the array form that BPF requires. 'fstart' will point to
2031 * the malloc'd array while 'ftail' is used during the recursive traversal.
2033 static struct bpf_insn
*fstart
;
2034 static struct bpf_insn
*ftail
;
2041 * Returns true if successful. Returns false if a branch has
2042 * an offset that is too large. If so, we have marked that
2043 * branch so that on a subsequent iteration, it will be treated
2050 struct bpf_insn
*dst
;
2054 int extrajmps
; /* number of extra jumps inserted */
2055 struct slist
**offset
= NULL
;
2057 if (p
== 0 || isMarked(p
))
2061 if (convert_code_r(JF(p
)) == 0)
2063 if (convert_code_r(JT(p
)) == 0)
2066 slen
= slength(p
->stmts
);
2067 dst
= ftail
-= (slen
+ 1 + p
->longjt
+ p
->longjf
);
2068 /* inflate length by any extra jumps */
2070 p
->offset
= dst
- fstart
;
2072 /* generate offset[] for convenience */
2074 offset
= (struct slist
**)calloc(slen
, sizeof(struct slist
*));
2076 bpf_error("not enough core");
2081 for (off
= 0; off
< slen
&& src
; off
++) {
2083 printf("off=%d src=%x\n", off
, src
);
2090 for (src
= p
->stmts
; src
; src
= src
->next
) {
2091 if (src
->s
.code
== NOP
)
2093 dst
->code
= (u_short
)src
->s
.code
;
2096 /* fill block-local relative jump */
2097 if (BPF_CLASS(src
->s
.code
) != BPF_JMP
|| src
->s
.code
== (BPF_JMP
|BPF_JA
)) {
2099 if (src
->s
.jt
|| src
->s
.jf
) {
2100 bpf_error("illegal jmp destination");
2106 if (off
== slen
- 2) /*???*/
2112 char *ljerr
= "%s for block-local relative jump: off=%d";
2115 printf("code=%x off=%d %x %x\n", src
->s
.code
,
2116 off
, src
->s
.jt
, src
->s
.jf
);
2119 if (!src
->s
.jt
|| !src
->s
.jf
) {
2120 bpf_error(ljerr
, "no jmp destination", off
);
2125 for (i
= 0; i
< slen
; i
++) {
2126 if (offset
[i
] == src
->s
.jt
) {
2128 bpf_error(ljerr
, "multiple matches", off
);
2132 dst
->jt
= i
- off
- 1;
2135 if (offset
[i
] == src
->s
.jf
) {
2137 bpf_error(ljerr
, "multiple matches", off
);
2140 dst
->jf
= i
- off
- 1;
2145 bpf_error(ljerr
, "no destination found", off
);
2157 bids
[dst
- fstart
] = p
->id
+ 1;
2159 dst
->code
= (u_short
)p
->s
.code
;
2163 off
= JT(p
)->offset
- (p
->offset
+ slen
) - 1;
2165 /* offset too large for branch, must add a jump */
2166 if (p
->longjt
== 0) {
2167 /* mark this instruction and retry */
2171 /* branch if T to following jump */
2172 dst
->jt
= extrajmps
;
2174 dst
[extrajmps
].code
= BPF_JMP
|BPF_JA
;
2175 dst
[extrajmps
].k
= off
- extrajmps
;
2179 off
= JF(p
)->offset
- (p
->offset
+ slen
) - 1;
2181 /* offset too large for branch, must add a jump */
2182 if (p
->longjf
== 0) {
2183 /* mark this instruction and retry */
2187 /* branch if F to following jump */
2188 /* if two jumps are inserted, F goes to second one */
2189 dst
->jf
= extrajmps
;
2191 dst
[extrajmps
].code
= BPF_JMP
|BPF_JA
;
2192 dst
[extrajmps
].k
= off
- extrajmps
;
2202 * Convert flowgraph intermediate representation to the
2203 * BPF array representation. Set *lenp to the number of instructions.
2206 icode_to_fcode(root
, lenp
)
2211 struct bpf_insn
*fp
;
2214 * Loop doing convert_code_r() until no branches remain
2215 * with too-large offsets.
2219 n
= *lenp
= count_stmts(root
);
2221 fp
= (struct bpf_insn
*)malloc(sizeof(*fp
) * n
);
2223 bpf_error("malloc");
2224 memset((char *)fp
, 0, sizeof(*fp
) * n
);
2229 if (convert_code_r(root
))
2238 * Make a copy of a BPF program and put it in the "fcode" member of
2241 * If we fail to allocate memory for the copy, fill in the "errbuf"
2242 * member of the "pcap_t" with an error message, and return -1;
2243 * otherwise, return 0.
2246 install_bpf_program(pcap_t
*p
, struct bpf_program
*fp
)
2251 * Free up any already installed program.
2253 pcap_freecode(&p
->fcode
);
2255 prog_size
= sizeof(*fp
->bf_insns
) * fp
->bf_len
;
2256 p
->fcode
.bf_len
= fp
->bf_len
;
2257 p
->fcode
.bf_insns
= (struct bpf_insn
*)malloc(prog_size
);
2258 if (p
->fcode
.bf_insns
== NULL
) {
2259 snprintf(p
->errbuf
, sizeof(p
->errbuf
),
2260 "malloc: %s", pcap_strerror(errno
));
2263 memcpy(p
->fcode
.bf_insns
, fp
->bf_insns
, prog_size
);
2272 struct bpf_program f
;
2274 memset(bids
, 0, sizeof bids
);
2275 f
.bf_insns
= icode_to_fcode(root
, &f
.bf_len
);
2278 free((char *)f
.bf_insns
);