]>
The Tcpdump Group git mirrors - libpcap/blob - optimize.c
2fefbef0c6f8a6969ee0891f0bd175cb98748a2c
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
[] =
25 "@(#) $Header: /tcpdump/master/libpcap/optimize.c,v 1.73 2002-06-11 05:30:40 itojun Exp $ (LBL)";
42 #ifdef HAVE_OS_PROTO_H
50 #define A_ATOM BPF_MEMWORDS
51 #define X_ATOM (BPF_MEMWORDS+1)
56 * This define is used to represent *both* the accumulator and
57 * x register in use-def computations.
58 * Currently, the use-def code assumes only one definition per instruction.
60 #define AX_ATOM N_ATOMS
63 * A flag to indicate that further optimization is needed.
64 * Iterative passes are continued until a given pass yields no
70 * A block is marked if only if its mark equals the current mark.
71 * Rather than traverse the code array, marking each item, 'cur_mark' is
72 * incremented. This automatically makes each element unmarked.
75 #define isMarked(p) ((p)->mark == cur_mark)
76 #define unMarkAll() cur_mark += 1
77 #define Mark(p) ((p)->mark = cur_mark)
79 static void opt_init(struct block
*);
80 static void opt_cleanup(void);
82 static void make_marks(struct block
*);
83 static void mark_code(struct block
*);
85 static void intern_blocks(struct block
*);
87 static int eq_slist(struct slist
*, struct slist
*);
89 static void find_levels_r(struct block
*);
91 static void find_levels(struct block
*);
92 static void find_dom(struct block
*);
93 static void propedom(struct edge
*);
94 static void find_edom(struct block
*);
95 static void find_closure(struct block
*);
96 static int atomuse(struct stmt
*);
97 static int atomdef(struct stmt
*);
98 static void compute_local_ud(struct block
*);
99 static void find_ud(struct block
*);
100 static void init_val(void);
101 static int F(int, int, int);
102 static inline void vstore(struct stmt
*, int *, int, int);
103 static void opt_blk(struct block
*, int);
104 static int use_conflict(struct block
*, struct block
*);
105 static void opt_j(struct edge
*);
106 static void or_pullup(struct block
*);
107 static void and_pullup(struct block
*);
108 static void opt_blks(struct block
*, int);
109 static inline void link_inedge(struct edge
*, struct block
*);
110 static void find_inedges(struct block
*);
111 static void opt_root(struct block
**);
112 static void opt_loop(struct block
*, int);
113 static void fold_op(struct stmt
*, int, int);
114 static inline struct slist
*this_op(struct slist
*);
115 static void opt_not(struct block
*);
116 static void opt_peep(struct block
*);
117 static void opt_stmt(struct stmt
*, int[], int);
118 static void deadstmt(struct stmt
*, struct stmt
*[]);
119 static void opt_deadstores(struct block
*);
120 static struct block
*fold_edge(struct block
*, struct edge
*);
121 static inline int eq_blk(struct block
*, struct block
*);
122 static int slength(struct slist
*);
123 static int count_blocks(struct block
*);
124 static void number_blks_r(struct block
*);
125 static int count_stmts(struct block
*);
126 static int convert_code_r(struct block
*);
128 static void opt_dump(struct block
*);
132 struct block
**blocks
;
137 * A bit vector set representation of the dominators.
138 * We round up the set size to the next power of two.
140 static int nodewords
;
141 static int edgewords
;
142 struct block
**levels
;
144 #define BITS_PER_WORD (8*sizeof(bpf_u_int32))
146 * True if a is in uset {p}
148 #define SET_MEMBER(p, a) \
149 ((p)[(unsigned)(a) / BITS_PER_WORD] & (1 << ((unsigned)(a) % BITS_PER_WORD)))
154 #define SET_INSERT(p, a) \
155 (p)[(unsigned)(a) / BITS_PER_WORD] |= (1 << ((unsigned)(a) % BITS_PER_WORD))
158 * Delete 'a' from uset p.
160 #define SET_DELETE(p, a) \
161 (p)[(unsigned)(a) / BITS_PER_WORD] &= ~(1 << ((unsigned)(a) % BITS_PER_WORD))
166 #define SET_INTERSECT(a, b, n)\
168 register bpf_u_int32 *_x = a, *_y = b;\
169 register int _n = n;\
170 while (--_n >= 0) *_x++ &= *_y++;\
176 #define SET_SUBTRACT(a, b, n)\
178 register bpf_u_int32 *_x = a, *_y = b;\
179 register int _n = n;\
180 while (--_n >= 0) *_x++ &=~ *_y++;\
186 #define SET_UNION(a, b, n)\
188 register bpf_u_int32 *_x = a, *_y = b;\
189 register int _n = n;\
190 while (--_n >= 0) *_x++ |= *_y++;\
193 static uset all_dom_sets
;
194 static uset all_closure_sets
;
195 static uset all_edge_sets
;
198 #define MAX(a,b) ((a)>(b)?(a):(b))
214 find_levels_r(JT(b
));
215 find_levels_r(JF(b
));
216 level
= MAX(JT(b
)->level
, JF(b
)->level
) + 1;
220 b
->link
= levels
[level
];
225 * Level graph. The levels go from 0 at the leaves to
226 * N_LEVELS at the root. The levels[] array points to the
227 * first node of the level list, whose elements are linked
228 * with the 'link' field of the struct block.
234 memset((char *)levels
, 0, n_blocks
* sizeof(*levels
));
240 * Find dominator relationships.
241 * Assumes graph has been leveled.
252 * Initialize sets to contain all nodes.
255 i
= n_blocks
* nodewords
;
258 /* Root starts off empty. */
259 for (i
= nodewords
; --i
>= 0;)
262 /* root->level is the highest level no found. */
263 for (i
= root
->level
; i
>= 0; --i
) {
264 for (b
= levels
[i
]; b
; b
= b
->link
) {
265 SET_INSERT(b
->dom
, b
->id
);
268 SET_INTERSECT(JT(b
)->dom
, b
->dom
, nodewords
);
269 SET_INTERSECT(JF(b
)->dom
, b
->dom
, nodewords
);
278 SET_INSERT(ep
->edom
, ep
->id
);
280 SET_INTERSECT(ep
->succ
->et
.edom
, ep
->edom
, edgewords
);
281 SET_INTERSECT(ep
->succ
->ef
.edom
, ep
->edom
, edgewords
);
286 * Compute edge dominators.
287 * Assumes graph has been leveled and predecessors established.
298 for (i
= n_edges
* edgewords
; --i
>= 0; )
301 /* root->level is the highest level no found. */
302 memset(root
->et
.edom
, 0, edgewords
* sizeof(*(uset
)0));
303 memset(root
->ef
.edom
, 0, edgewords
* sizeof(*(uset
)0));
304 for (i
= root
->level
; i
>= 0; --i
) {
305 for (b
= levels
[i
]; b
!= 0; b
= b
->link
) {
313 * Find the backwards transitive closure of the flow graph. These sets
314 * are backwards in the sense that we find the set of nodes that reach
315 * a given node, not the set of nodes that can be reached by a node.
317 * Assumes graph has been leveled.
327 * Initialize sets to contain no nodes.
329 memset((char *)all_closure_sets
, 0,
330 n_blocks
* nodewords
* sizeof(*all_closure_sets
));
332 /* root->level is the highest level no found. */
333 for (i
= root
->level
; i
>= 0; --i
) {
334 for (b
= levels
[i
]; b
; b
= b
->link
) {
335 SET_INSERT(b
->closure
, b
->id
);
338 SET_UNION(JT(b
)->closure
, b
->closure
, nodewords
);
339 SET_UNION(JF(b
)->closure
, b
->closure
, nodewords
);
345 * Return the register number that is used by s. If A and X are both
346 * used, return AX_ATOM. If no register is used, return -1.
348 * The implementation should probably change to an array access.
354 register int c
= s
->code
;
359 switch (BPF_CLASS(c
)) {
362 return (BPF_RVAL(c
) == BPF_A
) ? A_ATOM
:
363 (BPF_RVAL(c
) == BPF_X
) ? X_ATOM
: -1;
367 return (BPF_MODE(c
) == BPF_IND
) ? X_ATOM
:
368 (BPF_MODE(c
) == BPF_MEM
) ? s
->k
: -1;
378 if (BPF_SRC(c
) == BPF_X
)
383 return BPF_MISCOP(c
) == BPF_TXA
? X_ATOM
: A_ATOM
;
390 * Return the register number that is defined by 's'. We assume that
391 * a single stmt cannot define more than one register. If no register
392 * is defined, return -1.
394 * The implementation should probably change to an array access.
403 switch (BPF_CLASS(s
->code
)) {
417 return BPF_MISCOP(s
->code
) == BPF_TAX
? X_ATOM
: A_ATOM
;
427 atomset def
= 0, use
= 0, kill
= 0;
430 for (s
= b
->stmts
; s
; s
= s
->next
) {
431 if (s
->s
.code
== NOP
)
433 atom
= atomuse(&s
->s
);
435 if (atom
== AX_ATOM
) {
436 if (!ATOMELEM(def
, X_ATOM
))
437 use
|= ATOMMASK(X_ATOM
);
438 if (!ATOMELEM(def
, A_ATOM
))
439 use
|= ATOMMASK(A_ATOM
);
441 else if (atom
< N_ATOMS
) {
442 if (!ATOMELEM(def
, atom
))
443 use
|= ATOMMASK(atom
);
448 atom
= atomdef(&s
->s
);
450 if (!ATOMELEM(use
, atom
))
451 kill
|= ATOMMASK(atom
);
452 def
|= ATOMMASK(atom
);
455 if (!ATOMELEM(def
, A_ATOM
) && BPF_CLASS(b
->s
.code
) == BPF_JMP
)
456 use
|= ATOMMASK(A_ATOM
);
464 * Assume graph is already leveled.
474 * root->level is the highest level no found;
475 * count down from there.
477 maxlevel
= root
->level
;
478 for (i
= maxlevel
; i
>= 0; --i
)
479 for (p
= levels
[i
]; p
; p
= p
->link
) {
484 for (i
= 1; i
<= maxlevel
; ++i
) {
485 for (p
= levels
[i
]; p
; p
= p
->link
) {
486 p
->out_use
|= JT(p
)->in_use
| JF(p
)->in_use
;
487 p
->in_use
|= p
->out_use
&~ p
->kill
;
493 * These data structures are used in a Cocke and Shwarz style
494 * value numbering scheme. Since the flowgraph is acyclic,
495 * exit values can be propagated from a node's predecessors
496 * provided it is uniquely defined.
502 struct valnode
*next
;
506 static struct valnode
*hashtbl
[MODULUS
];
510 /* Integer constants mapped with the load immediate opcode. */
511 #define K(i) F(BPF_LD|BPF_IMM|BPF_W, i, 0L)
518 struct vmapinfo
*vmap
;
519 struct valnode
*vnode_base
;
520 struct valnode
*next_vnode
;
526 next_vnode
= vnode_base
;
527 memset((char *)vmap
, 0, maxval
* sizeof(*vmap
));
528 memset((char *)hashtbl
, 0, sizeof hashtbl
);
531 /* Because we really don't have an IR, this stuff is a little messy. */
541 hash
= (u_int
)code
^ (v0
<< 4) ^ (v1
<< 8);
544 for (p
= hashtbl
[hash
]; p
; p
= p
->next
)
545 if (p
->code
== code
&& p
->v0
== v0
&& p
->v1
== v1
)
549 if (BPF_MODE(code
) == BPF_IMM
&&
550 (BPF_CLASS(code
) == BPF_LD
|| BPF_CLASS(code
) == BPF_LDX
)) {
551 vmap
[val
].const_val
= v0
;
552 vmap
[val
].is_const
= 1;
559 p
->next
= hashtbl
[hash
];
566 vstore(s
, valp
, newval
, alter
)
572 if (alter
&& *valp
== newval
)
585 a
= vmap
[v0
].const_val
;
586 b
= vmap
[v1
].const_val
;
588 switch (BPF_OP(s
->code
)) {
603 bpf_error("division by zero");
631 s
->code
= BPF_LD
|BPF_IMM
;
635 static inline struct slist
*
639 while (s
!= 0 && s
->s
.code
== NOP
)
648 struct block
*tmp
= JT(b
);
659 struct slist
*next
, *last
;
667 for (/*empty*/; /*empty*/; s
= next
) {
671 next
= this_op(s
->next
);
677 * st M[k] --> st M[k]
680 if (s
->s
.code
== BPF_ST
&&
681 next
->s
.code
== (BPF_LDX
|BPF_MEM
) &&
682 s
->s
.k
== next
->s
.k
) {
684 next
->s
.code
= BPF_MISC
|BPF_TAX
;
690 if (s
->s
.code
== (BPF_LD
|BPF_IMM
) &&
691 next
->s
.code
== (BPF_MISC
|BPF_TAX
)) {
692 s
->s
.code
= BPF_LDX
|BPF_IMM
;
693 next
->s
.code
= BPF_MISC
|BPF_TXA
;
697 * This is an ugly special case, but it happens
698 * when you say tcp[k] or udp[k] where k is a constant.
700 if (s
->s
.code
== (BPF_LD
|BPF_IMM
)) {
701 struct slist
*add
, *tax
, *ild
;
704 * Check that X isn't used on exit from this
705 * block (which the optimizer might cause).
706 * We know the code generator won't generate
707 * any local dependencies.
709 if (ATOMELEM(b
->out_use
, X_ATOM
))
712 if (next
->s
.code
!= (BPF_LDX
|BPF_MSH
|BPF_B
))
715 add
= this_op(next
->next
);
716 if (add
== 0 || add
->s
.code
!= (BPF_ALU
|BPF_ADD
|BPF_X
))
719 tax
= this_op(add
->next
);
720 if (tax
== 0 || tax
->s
.code
!= (BPF_MISC
|BPF_TAX
))
723 ild
= this_op(tax
->next
);
724 if (ild
== 0 || BPF_CLASS(ild
->s
.code
) != BPF_LD
||
725 BPF_MODE(ild
->s
.code
) != BPF_IND
)
728 * XXX We need to check that X is not
729 * subsequently used. We know we can eliminate the
730 * accumulator modifications since it is defined
731 * by the last stmt of this sequence.
733 * We want to turn this sequence:
736 * (005) ldxms [14] {next} -- optional
739 * (008) ild [x+0] {ild}
741 * into this sequence:
758 * If we have a subtract to do a comparison, and the X register
759 * is a known constant, we can merge this value into the
762 if (BPF_OP(b
->s
.code
) == BPF_JEQ
) {
763 if (last
->s
.code
== (BPF_ALU
|BPF_SUB
|BPF_X
) &&
764 !ATOMELEM(b
->out_use
, A_ATOM
)) {
765 val
= b
->val
[X_ATOM
];
766 if (vmap
[val
].is_const
) {
771 b
->s
.k
+= vmap
[val
].const_val
;
774 } else if (b
->s
.k
== 0) {
780 b
->s
.code
= BPF_CLASS(b
->s
.code
) |
781 BPF_OP(b
->s
.code
) | BPF_X
;
786 * Likewise, a constant subtract can be simplified.
788 else if (last
->s
.code
== (BPF_ALU
|BPF_SUB
|BPF_K
) &&
789 !ATOMELEM(b
->out_use
, A_ATOM
)) {
800 if (last
->s
.code
== (BPF_ALU
|BPF_AND
|BPF_K
) &&
801 !ATOMELEM(b
->out_use
, A_ATOM
) && b
->s
.k
== 0) {
803 b
->s
.code
= BPF_JMP
|BPF_K
|BPF_JSET
;
810 * jset #ffffffff -> always
812 if (b
->s
.code
== (BPF_JMP
|BPF_K
|BPF_JSET
)) {
815 if (b
->s
.k
== 0xffffffff)
819 * If the accumulator is a known constant, we can compute the
822 val
= b
->val
[A_ATOM
];
823 if (vmap
[val
].is_const
&& BPF_SRC(b
->s
.code
) == BPF_K
) {
824 bpf_int32 v
= vmap
[val
].const_val
;
825 switch (BPF_OP(b
->s
.code
)) {
832 v
= (unsigned)v
> b
->s
.k
;
836 v
= (unsigned)v
>= b
->s
.k
;
856 * Compute the symbolic value of expression of 's', and update
857 * anything it defines in the value table 'val'. If 'alter' is true,
858 * do various optimizations. This code would be cleaner if symbolic
859 * evaluation and code transformations weren't folded together.
862 opt_stmt(s
, val
, alter
)
872 case BPF_LD
|BPF_ABS
|BPF_W
:
873 case BPF_LD
|BPF_ABS
|BPF_H
:
874 case BPF_LD
|BPF_ABS
|BPF_B
:
875 v
= F(s
->code
, s
->k
, 0L);
876 vstore(s
, &val
[A_ATOM
], v
, alter
);
879 case BPF_LD
|BPF_IND
|BPF_W
:
880 case BPF_LD
|BPF_IND
|BPF_H
:
881 case BPF_LD
|BPF_IND
|BPF_B
:
883 if (alter
&& vmap
[v
].is_const
) {
884 s
->code
= BPF_LD
|BPF_ABS
|BPF_SIZE(s
->code
);
885 s
->k
+= vmap
[v
].const_val
;
886 v
= F(s
->code
, s
->k
, 0L);
890 v
= F(s
->code
, s
->k
, v
);
891 vstore(s
, &val
[A_ATOM
], v
, alter
);
895 v
= F(s
->code
, 0L, 0L);
896 vstore(s
, &val
[A_ATOM
], v
, alter
);
901 vstore(s
, &val
[A_ATOM
], v
, alter
);
904 case BPF_LDX
|BPF_IMM
:
906 vstore(s
, &val
[X_ATOM
], v
, alter
);
909 case BPF_LDX
|BPF_MSH
|BPF_B
:
910 v
= F(s
->code
, s
->k
, 0L);
911 vstore(s
, &val
[X_ATOM
], v
, alter
);
914 case BPF_ALU
|BPF_NEG
:
915 if (alter
&& vmap
[val
[A_ATOM
]].is_const
) {
916 s
->code
= BPF_LD
|BPF_IMM
;
917 s
->k
= -vmap
[val
[A_ATOM
]].const_val
;
918 val
[A_ATOM
] = K(s
->k
);
921 val
[A_ATOM
] = F(s
->code
, val
[A_ATOM
], 0L);
924 case BPF_ALU
|BPF_ADD
|BPF_K
:
925 case BPF_ALU
|BPF_SUB
|BPF_K
:
926 case BPF_ALU
|BPF_MUL
|BPF_K
:
927 case BPF_ALU
|BPF_DIV
|BPF_K
:
928 case BPF_ALU
|BPF_AND
|BPF_K
:
929 case BPF_ALU
|BPF_OR
|BPF_K
:
930 case BPF_ALU
|BPF_LSH
|BPF_K
:
931 case BPF_ALU
|BPF_RSH
|BPF_K
:
932 op
= BPF_OP(s
->code
);
935 /* don't optimize away "sub #0"
936 * as it may be needed later to
937 * fixup the generated math code */
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, 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 s
->code
= BPF_MISC
|BPF_TXA
;
993 vstore(s
, &val
[A_ATOM
], val
[X_ATOM
], alter
);
996 else if (op
== BPF_MUL
|| op
== BPF_DIV
||
997 op
== BPF_AND
|| op
== BPF_LSH
|| op
== BPF_RSH
) {
998 s
->code
= BPF_LD
|BPF_IMM
;
1000 vstore(s
, &val
[A_ATOM
], K(s
->k
), alter
);
1003 else if (op
== BPF_NEG
) {
1008 val
[A_ATOM
] = F(s
->code
, val
[A_ATOM
], val
[X_ATOM
]);
1011 case BPF_MISC
|BPF_TXA
:
1012 vstore(s
, &val
[A_ATOM
], val
[X_ATOM
], alter
);
1015 case BPF_LD
|BPF_MEM
:
1017 if (alter
&& vmap
[v
].is_const
) {
1018 s
->code
= BPF_LD
|BPF_IMM
;
1019 s
->k
= vmap
[v
].const_val
;
1022 vstore(s
, &val
[A_ATOM
], v
, alter
);
1025 case BPF_MISC
|BPF_TAX
:
1026 vstore(s
, &val
[X_ATOM
], val
[A_ATOM
], alter
);
1029 case BPF_LDX
|BPF_MEM
:
1031 if (alter
&& vmap
[v
].is_const
) {
1032 s
->code
= BPF_LDX
|BPF_IMM
;
1033 s
->k
= vmap
[v
].const_val
;
1036 vstore(s
, &val
[X_ATOM
], v
, alter
);
1040 vstore(s
, &val
[s
->k
], val
[A_ATOM
], alter
);
1044 vstore(s
, &val
[s
->k
], val
[X_ATOM
], alter
);
1051 register struct stmt
*s
;
1052 register struct stmt
*last
[];
1058 if (atom
== AX_ATOM
) {
1069 last
[atom
]->code
= NOP
;
1077 register struct block
*b
;
1079 register struct slist
*s
;
1081 struct stmt
*last
[N_ATOMS
];
1083 memset((char *)last
, 0, sizeof last
);
1085 for (s
= b
->stmts
; s
!= 0; s
= s
->next
)
1086 deadstmt(&s
->s
, last
);
1087 deadstmt(&b
->s
, last
);
1089 for (atom
= 0; atom
< N_ATOMS
; ++atom
)
1090 if (last
[atom
] && !ATOMELEM(b
->out_use
, atom
)) {
1091 last
[atom
]->code
= NOP
;
1097 opt_blk(b
, do_stmts
)
1107 for (s
= b
->stmts
; s
&& s
->next
; s
= s
->next
)
1108 if (BPF_CLASS(s
->s
.code
) == BPF_JMP
) {
1115 * Initialize the atom values.
1116 * If we have no predecessors, everything is undefined.
1117 * Otherwise, we inherent our values from our predecessors.
1118 * If any register has an ambiguous value (i.e. control paths are
1119 * merging) give it the undefined value of 0.
1123 memset((char *)b
->val
, 0, sizeof(b
->val
));
1125 memcpy((char *)b
->val
, (char *)p
->pred
->val
, sizeof(b
->val
));
1126 while ((p
= p
->next
) != NULL
) {
1127 for (i
= 0; i
< N_ATOMS
; ++i
)
1128 if (b
->val
[i
] != p
->pred
->val
[i
])
1132 aval
= b
->val
[A_ATOM
];
1133 for (s
= b
->stmts
; s
; s
= s
->next
)
1134 opt_stmt(&s
->s
, b
->val
, do_stmts
);
1137 * This is a special case: if we don't use anything from this
1138 * block, and we load the accumulator with value that is
1139 * already there, or if this block is a return,
1140 * eliminate all the statements.
1143 ((b
->out_use
== 0 && aval
!= 0 &&b
->val
[A_ATOM
] == aval
) ||
1144 BPF_CLASS(b
->s
.code
) == BPF_RET
)) {
1145 if (b
->stmts
!= 0) {
1154 * Set up values for branch optimizer.
1156 if (BPF_SRC(b
->s
.code
) == BPF_K
)
1157 b
->oval
= K(b
->s
.k
);
1159 b
->oval
= b
->val
[X_ATOM
];
1160 b
->et
.code
= b
->s
.code
;
1161 b
->ef
.code
= -b
->s
.code
;
1165 * Return true if any register that is used on exit from 'succ', has
1166 * an exit value that is different from the corresponding exit value
1170 use_conflict(b
, succ
)
1171 struct block
*b
, *succ
;
1174 atomset use
= succ
->out_use
;
1179 for (atom
= 0; atom
< N_ATOMS
; ++atom
)
1180 if (ATOMELEM(use
, atom
))
1181 if (b
->val
[atom
] != succ
->val
[atom
])
1186 static struct block
*
1187 fold_edge(child
, ep
)
1188 struct block
*child
;
1192 int aval0
, aval1
, oval0
, oval1
;
1193 int code
= ep
->code
;
1201 if (child
->s
.code
!= code
)
1204 aval0
= child
->val
[A_ATOM
];
1205 oval0
= child
->oval
;
1206 aval1
= ep
->pred
->val
[A_ATOM
];
1207 oval1
= ep
->pred
->oval
;
1214 * The operands are identical, so the
1215 * result is true if a true branch was
1216 * taken to get here, otherwise false.
1218 return sense
? JT(child
) : JF(child
);
1220 if (sense
&& code
== (BPF_JMP
|BPF_JEQ
|BPF_K
))
1222 * At this point, we only know the comparison if we
1223 * came down the true branch, and it was an equality
1224 * comparison with a constant. We rely on the fact that
1225 * distinct constants have distinct value numbers.
1237 register struct block
*target
;
1239 if (JT(ep
->succ
) == 0)
1242 if (JT(ep
->succ
) == JF(ep
->succ
)) {
1244 * Common branch targets can be eliminated, provided
1245 * there is no data dependency.
1247 if (!use_conflict(ep
->pred
, ep
->succ
->et
.succ
)) {
1249 ep
->succ
= JT(ep
->succ
);
1253 * For each edge dominator that matches the successor of this
1254 * edge, promote the edge successor to the its grandchild.
1256 * XXX We violate the set abstraction here in favor a reasonably
1260 for (i
= 0; i
< edgewords
; ++i
) {
1261 register bpf_u_int32 x
= ep
->edom
[i
];
1266 k
+= i
* BITS_PER_WORD
;
1268 target
= fold_edge(ep
->succ
, edges
[k
]);
1270 * Check that there is no data dependency between
1271 * nodes that will be violated if we move the edge.
1273 if (target
!= 0 && !use_conflict(ep
->pred
, target
)) {
1276 if (JT(target
) != 0)
1278 * Start over unless we hit a leaf.
1294 struct block
**diffp
, **samep
;
1302 * Make sure each predecessor loads the same value.
1305 val
= ep
->pred
->val
[A_ATOM
];
1306 for (ep
= ep
->next
; ep
!= 0; ep
= ep
->next
)
1307 if (val
!= ep
->pred
->val
[A_ATOM
])
1310 if (JT(b
->in_edges
->pred
) == b
)
1311 diffp
= &JT(b
->in_edges
->pred
);
1313 diffp
= &JF(b
->in_edges
->pred
);
1320 if (JT(*diffp
) != JT(b
))
1323 if (!SET_MEMBER((*diffp
)->dom
, b
->id
))
1326 if ((*diffp
)->val
[A_ATOM
] != val
)
1329 diffp
= &JF(*diffp
);
1332 samep
= &JF(*diffp
);
1337 if (JT(*samep
) != JT(b
))
1340 if (!SET_MEMBER((*samep
)->dom
, b
->id
))
1343 if ((*samep
)->val
[A_ATOM
] == val
)
1346 /* XXX Need to check that there are no data dependencies
1347 between dp0 and dp1. Currently, the code generator
1348 will not produce such dependencies. */
1349 samep
= &JF(*samep
);
1352 /* XXX This doesn't cover everything. */
1353 for (i
= 0; i
< N_ATOMS
; ++i
)
1354 if ((*samep
)->val
[i
] != pred
->val
[i
])
1357 /* Pull up the node. */
1363 * At the top of the chain, each predecessor needs to point at the
1364 * pulled up node. Inside the chain, there is only one predecessor
1368 for (ep
= b
->in_edges
; ep
!= 0; ep
= ep
->next
) {
1369 if (JT(ep
->pred
) == b
)
1370 JT(ep
->pred
) = pull
;
1372 JF(ep
->pred
) = pull
;
1387 struct block
**diffp
, **samep
;
1395 * Make sure each predecessor loads the same value.
1397 val
= ep
->pred
->val
[A_ATOM
];
1398 for (ep
= ep
->next
; ep
!= 0; ep
= ep
->next
)
1399 if (val
!= ep
->pred
->val
[A_ATOM
])
1402 if (JT(b
->in_edges
->pred
) == b
)
1403 diffp
= &JT(b
->in_edges
->pred
);
1405 diffp
= &JF(b
->in_edges
->pred
);
1412 if (JF(*diffp
) != JF(b
))
1415 if (!SET_MEMBER((*diffp
)->dom
, b
->id
))
1418 if ((*diffp
)->val
[A_ATOM
] != val
)
1421 diffp
= &JT(*diffp
);
1424 samep
= &JT(*diffp
);
1429 if (JF(*samep
) != JF(b
))
1432 if (!SET_MEMBER((*samep
)->dom
, b
->id
))
1435 if ((*samep
)->val
[A_ATOM
] == val
)
1438 /* XXX Need to check that there are no data dependencies
1439 between diffp and samep. Currently, the code generator
1440 will not produce such dependencies. */
1441 samep
= &JT(*samep
);
1444 /* XXX This doesn't cover everything. */
1445 for (i
= 0; i
< N_ATOMS
; ++i
)
1446 if ((*samep
)->val
[i
] != pred
->val
[i
])
1449 /* Pull up the node. */
1455 * At the top of the chain, each predecessor needs to point at the
1456 * pulled up node. Inside the chain, there is only one predecessor
1460 for (ep
= b
->in_edges
; ep
!= 0; ep
= ep
->next
) {
1461 if (JT(ep
->pred
) == b
)
1462 JT(ep
->pred
) = pull
;
1464 JF(ep
->pred
) = pull
;
1474 opt_blks(root
, do_stmts
)
1482 maxlevel
= root
->level
;
1485 for (i
= maxlevel
; i
>= 0; --i
)
1486 for (p
= levels
[i
]; p
; p
= p
->link
)
1487 opt_blk(p
, do_stmts
);
1491 * No point trying to move branches; it can't possibly
1492 * make a difference at this point.
1496 for (i
= 1; i
<= maxlevel
; ++i
) {
1497 for (p
= levels
[i
]; p
; p
= p
->link
) {
1504 for (i
= 1; i
<= maxlevel
; ++i
) {
1505 for (p
= levels
[i
]; p
; p
= p
->link
) {
1513 link_inedge(parent
, child
)
1514 struct edge
*parent
;
1515 struct block
*child
;
1517 parent
->next
= child
->in_edges
;
1518 child
->in_edges
= parent
;
1528 for (i
= 0; i
< n_blocks
; ++i
)
1529 blocks
[i
]->in_edges
= 0;
1532 * Traverse the graph, adding each edge to the predecessor
1533 * list of its successors. Skip the leaves (i.e. level 0).
1535 for (i
= root
->level
; i
> 0; --i
) {
1536 for (b
= levels
[i
]; b
!= 0; b
= b
->link
) {
1537 link_inedge(&b
->et
, JT(b
));
1538 link_inedge(&b
->ef
, JF(b
));
1547 struct slist
*tmp
, *s
;
1551 while (BPF_CLASS((*b
)->s
.code
) == BPF_JMP
&& JT(*b
) == JF(*b
))
1560 * If the root node is a return, then there is no
1561 * point executing any statements (since the bpf machine
1562 * has no side effects).
1564 if (BPF_CLASS((*b
)->s
.code
) == BPF_RET
)
1569 opt_loop(root
, do_stmts
)
1576 printf("opt_loop(root, %d) begin\n", do_stmts
);
1587 opt_blks(root
, do_stmts
);
1590 printf("opt_loop(root, %d) bottom, done=%d\n", do_stmts
, done
);
1598 * Optimize the filter code in its dag representation.
1602 struct block
**rootp
;
1611 intern_blocks(root
);
1614 printf("after intern_blocks()\n");
1621 printf("after opt_root()\n");
1634 if (BPF_CLASS(p
->s
.code
) != BPF_RET
) {
1642 * Mark code array such that isMarked(i) is true
1643 * only for nodes that are alive.
1654 * True iff the two stmt lists load the same value from the packet into
1659 struct slist
*x
, *y
;
1662 while (x
&& x
->s
.code
== NOP
)
1664 while (y
&& y
->s
.code
== NOP
)
1670 if (x
->s
.code
!= y
->s
.code
|| x
->s
.k
!= y
->s
.k
)
1679 struct block
*b0
, *b1
;
1681 if (b0
->s
.code
== b1
->s
.code
&&
1682 b0
->s
.k
== b1
->s
.k
&&
1683 b0
->et
.succ
== b1
->et
.succ
&&
1684 b0
->ef
.succ
== b1
->ef
.succ
)
1685 return eq_slist(b0
->stmts
, b1
->stmts
);
1698 for (i
= 0; i
< n_blocks
; ++i
)
1699 blocks
[i
]->link
= 0;
1703 for (i
= n_blocks
- 1; --i
>= 0; ) {
1704 if (!isMarked(blocks
[i
]))
1706 for (j
= i
+ 1; j
< n_blocks
; ++j
) {
1707 if (!isMarked(blocks
[j
]))
1709 if (eq_blk(blocks
[i
], blocks
[j
])) {
1710 blocks
[i
]->link
= blocks
[j
]->link
?
1711 blocks
[j
]->link
: blocks
[j
];
1716 for (i
= 0; i
< n_blocks
; ++i
) {
1722 JT(p
) = JT(p
)->link
;
1726 JF(p
) = JF(p
)->link
;
1736 free((void *)vnode_base
);
1738 free((void *)edges
);
1739 free((void *)space
);
1740 free((void *)levels
);
1741 free((void *)blocks
);
1745 * Return the number of stmts in 's'.
1753 for (; s
; s
= s
->next
)
1754 if (s
->s
.code
!= NOP
)
1760 * Return the number of nodes reachable by 'p'.
1761 * All nodes should be initially unmarked.
1767 if (p
== 0 || isMarked(p
))
1770 return count_blocks(JT(p
)) + count_blocks(JF(p
)) + 1;
1774 * Do a depth first search on the flow graph, numbering the
1775 * the basic blocks, and entering them into the 'blocks' array.`
1783 if (p
== 0 || isMarked(p
))
1791 number_blks_r(JT(p
));
1792 number_blks_r(JF(p
));
1796 * Return the number of stmts in the flowgraph reachable by 'p'.
1797 * The nodes should be unmarked before calling.
1799 * Note that "stmts" means "instructions", and that this includes
1801 * side-effect statements in 'p' (slength(p->stmts));
1803 * statements in the true branch from 'p' (count_stmts(JT(p)));
1805 * statements in the false branch from 'p' (count_stmts(JF(p)));
1807 * the conditional jump itself (1);
1809 * an extra long jump if the true branch requires it (p->longjt);
1811 * an extra long jump if the false branch requires it (p->longjf).
1819 if (p
== 0 || isMarked(p
))
1822 n
= count_stmts(JT(p
)) + count_stmts(JF(p
));
1823 return slength(p
->stmts
) + n
+ 1 + p
->longjt
+ p
->longjf
;
1827 * Allocate memory. All allocation is done before optimization
1828 * is begun. A linear bound on the size of all data structures is computed
1829 * from the total number of blocks and/or statements.
1836 int i
, n
, max_stmts
;
1839 * First, count the blocks, so we can malloc an array to map
1840 * block number to block. Then, put the blocks into the array.
1843 n
= count_blocks(root
);
1844 blocks
= (struct block
**)malloc(n
* sizeof(*blocks
));
1847 number_blks_r(root
);
1849 n_edges
= 2 * n_blocks
;
1850 edges
= (struct edge
**)malloc(n_edges
* sizeof(*edges
));
1853 * The number of levels is bounded by the number of nodes.
1855 levels
= (struct block
**)malloc(n_blocks
* sizeof(*levels
));
1857 edgewords
= n_edges
/ (8 * sizeof(bpf_u_int32
)) + 1;
1858 nodewords
= n_blocks
/ (8 * sizeof(bpf_u_int32
)) + 1;
1861 space
= (bpf_u_int32
*)malloc(2 * n_blocks
* nodewords
* sizeof(*space
)
1862 + n_edges
* edgewords
* sizeof(*space
));
1865 for (i
= 0; i
< n
; ++i
) {
1869 all_closure_sets
= p
;
1870 for (i
= 0; i
< n
; ++i
) {
1871 blocks
[i
]->closure
= p
;
1875 for (i
= 0; i
< n
; ++i
) {
1876 register struct block
*b
= blocks
[i
];
1884 b
->ef
.id
= n_blocks
+ i
;
1885 edges
[n_blocks
+ i
] = &b
->ef
;
1890 for (i
= 0; i
< n
; ++i
)
1891 max_stmts
+= slength(blocks
[i
]->stmts
) + 1;
1893 * We allocate at most 3 value numbers per statement,
1894 * so this is an upper bound on the number of valnodes
1897 maxval
= 3 * max_stmts
;
1898 vmap
= (struct vmapinfo
*)malloc(maxval
* sizeof(*vmap
));
1899 vnode_base
= (struct valnode
*)malloc(maxval
* sizeof(*vnode_base
));
1903 * Some pointers used to convert the basic block form of the code,
1904 * into the array form that BPF requires. 'fstart' will point to
1905 * the malloc'd array while 'ftail' is used during the recursive traversal.
1907 static struct bpf_insn
*fstart
;
1908 static struct bpf_insn
*ftail
;
1915 * Returns true if successful. Returns false if a branch has
1916 * an offset that is too large. If so, we have marked that
1917 * branch so that on a subsequent iteration, it will be treated
1924 struct bpf_insn
*dst
;
1928 int extrajmps
; /* number of extra jumps inserted */
1929 struct slist
**offset
= NULL
;
1931 if (p
== 0 || isMarked(p
))
1935 if (convert_code_r(JF(p
)) == 0)
1937 if (convert_code_r(JT(p
)) == 0)
1940 slen
= slength(p
->stmts
);
1941 dst
= ftail
-= (slen
+ 1 + p
->longjt
+ p
->longjf
);
1942 /* inflate length by any extra jumps */
1944 p
->offset
= dst
- fstart
;
1946 /* generate offset[] for convenience */
1948 offset
= (struct slist
**)calloc(sizeof(struct slist
*), slen
);
1950 bpf_error("not enough core");
1955 for (off
= 0; off
< slen
&& src
; off
++) {
1957 printf("off=%d src=%x\n", off
, src
);
1964 for (src
= p
->stmts
; src
; src
= src
->next
) {
1965 if (src
->s
.code
== NOP
)
1967 dst
->code
= (u_short
)src
->s
.code
;
1970 /* fill block-local relative jump */
1971 if (BPF_CLASS(src
->s
.code
) != BPF_JMP
|| src
->s
.code
== (BPF_JMP
|BPF_JA
)) {
1973 if (src
->s
.jt
|| src
->s
.jf
) {
1974 bpf_error("illegal jmp destination");
1980 if (off
== slen
- 2) /*???*/
1986 char *ljerr
= "%s for block-local relative jump: off=%d";
1989 printf("code=%x off=%d %x %x\n", src
->s
.code
,
1990 off
, src
->s
.jt
, src
->s
.jf
);
1993 if (!src
->s
.jt
|| !src
->s
.jf
) {
1994 bpf_error(ljerr
, "no jmp destination", off
);
1999 for (i
= 0; i
< slen
; i
++) {
2000 if (offset
[i
] == src
->s
.jt
) {
2002 bpf_error(ljerr
, "multiple matches", off
);
2006 dst
->jt
= i
- off
- 1;
2009 if (offset
[i
] == src
->s
.jf
) {
2011 bpf_error(ljerr
, "multiple matches", off
);
2014 dst
->jf
= i
- off
- 1;
2019 bpf_error(ljerr
, "no destination found", off
);
2031 bids
[dst
- fstart
] = p
->id
+ 1;
2033 dst
->code
= (u_short
)p
->s
.code
;
2037 off
= JT(p
)->offset
- (p
->offset
+ slen
) - 1;
2039 /* offset too large for branch, must add a jump */
2040 if (p
->longjt
== 0) {
2041 /* mark this instruction and retry */
2045 /* branch if T to following jump */
2046 dst
->jt
= extrajmps
;
2048 dst
[extrajmps
].code
= BPF_JMP
|BPF_JA
;
2049 dst
[extrajmps
].k
= off
- extrajmps
;
2053 off
= JF(p
)->offset
- (p
->offset
+ slen
) - 1;
2055 /* offset too large for branch, must add a jump */
2056 if (p
->longjf
== 0) {
2057 /* mark this instruction and retry */
2061 /* branch if F to following jump */
2062 /* if two jumps are inserted, F goes to second one */
2063 dst
->jf
= extrajmps
;
2065 dst
[extrajmps
].code
= BPF_JMP
|BPF_JA
;
2066 dst
[extrajmps
].k
= off
- extrajmps
;
2076 * Convert flowgraph intermediate representation to the
2077 * BPF array representation. Set *lenp to the number of instructions.
2080 icode_to_fcode(root
, lenp
)
2085 struct bpf_insn
*fp
;
2088 * Loop doing convert_code_r() until no branches remain
2089 * with too-large offsets.
2093 n
= *lenp
= count_stmts(root
);
2095 fp
= (struct bpf_insn
*)malloc(sizeof(*fp
) * n
);
2096 memset((char *)fp
, 0, sizeof(*fp
) * n
);
2101 if (convert_code_r(root
))
2110 * Make a copy of a BPF program and put it in the "fcode" member of
2113 * If we fail to allocate memory for the copy, fill in the "errbuf"
2114 * member of the "pcap_t" with an error message, and return -1;
2115 * otherwise, return 0.
2118 install_bpf_program(pcap_t
*p
, struct bpf_program
*fp
)
2123 * Free up any already installed program.
2125 pcap_freecode(&p
->fcode
);
2127 prog_size
= sizeof(*fp
->bf_insns
) * fp
->bf_len
;
2128 p
->fcode
.bf_len
= fp
->bf_len
;
2129 p
->fcode
.bf_insns
= (struct bpf_insn
*)malloc(prog_size
);
2130 if (p
->fcode
.bf_insns
== NULL
) {
2131 snprintf(p
->errbuf
, sizeof(p
->errbuf
),
2132 "malloc: %s", pcap_strerror(errno
));
2135 memcpy(p
->fcode
.bf_insns
, fp
->bf_insns
, prog_size
);
2144 struct bpf_program f
;
2146 memset(bids
, 0, sizeof bids
);
2147 f
.bf_insns
= icode_to_fcode(root
, &f
.bf_len
);
2150 free((char *)f
.bf_insns
);