1 /* $OpenBSD: optimize.c,v 1.21 2020/08/03 03:29:58 dlg Exp $ */ 2 3 /* 4 * Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994, 1995, 1996 5 * The Regents of the University of California. All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that: (1) source code distributions 9 * retain the above copyright notice and this paragraph in its entirety, (2) 10 * distributions including binary code include the above copyright notice and 11 * this paragraph in its entirety in the documentation or other materials 12 * provided with the distribution, and (3) all advertising materials mentioning 13 * features or use of this software display the following acknowledgement: 14 * ``This product includes software developed by the University of California, 15 * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of 16 * the University nor the names of its contributors may be used to endorse 17 * or promote products derived from this software without specific prior 18 * written permission. 19 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED 20 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF 21 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 22 * 23 * Optimization module for tcpdump intermediate representation. 24 */ 25 26 #include <sys/types.h> 27 #include <sys/time.h> 28 29 #include <stdio.h> 30 #include <stdlib.h> 31 #include <stdint.h> 32 #include <string.h> 33 34 #include "pcap-int.h" 35 36 #include "gencode.h" 37 38 #ifdef HAVE_OS_PROTO_H 39 #include "os-proto.h" 40 #endif 41 42 #ifdef BDEBUG 43 extern int dflag; 44 #endif 45 46 #define A_ATOM BPF_MEMWORDS 47 #define X_ATOM (BPF_MEMWORDS+1) 48 49 #define NOP -1 50 51 /* 52 * This define is used to represent *both* the accumulator and 53 * x register in use-def computations. 54 * Currently, the use-def code assumes only one definition per instruction. 55 */ 56 #define AX_ATOM N_ATOMS 57 58 /* 59 * A flag to indicate that further optimization is needed. 60 * Iterative passes are continued until a given pass yields no 61 * branch movement. 62 */ 63 static int done; 64 65 /* 66 * A block is marked if only if its mark equals the current mark. 67 * Rather than traverse the code array, marking each item, 'cur_mark' is 68 * incremented. This automatically makes each element unmarked. 69 */ 70 static int cur_mark; 71 #define isMarked(p) ((p)->mark == cur_mark) 72 #define unMarkAll() cur_mark += 1 73 #define Mark(p) ((p)->mark = cur_mark) 74 75 static void opt_init(struct block *); 76 static void opt_cleanup(void); 77 78 static void make_marks(struct block *); 79 static void mark_code(struct block *); 80 81 static void intern_blocks(struct block *); 82 83 static int eq_slist(struct slist *, struct slist *); 84 85 static void find_levels_r(struct block *); 86 87 static void find_levels(struct block *); 88 static void find_dom(struct block *); 89 static void propedom(struct edge *); 90 static void find_edom(struct block *); 91 static void find_closure(struct block *); 92 static int atomuse(struct stmt *); 93 static int atomdef(struct stmt *); 94 static void compute_local_ud(struct block *); 95 static void find_ud(struct block *); 96 static void init_val(void); 97 static int F(int, int, int); 98 static __inline void vstore(struct stmt *, int *, int, int); 99 static void opt_blk(struct block *, int); 100 static int use_conflict(struct block *, struct block *); 101 static void opt_j(struct edge *); 102 static void or_pullup(struct block *); 103 static void and_pullup(struct block *); 104 static void opt_blks(struct block *, int); 105 static __inline void link_inedge(struct edge *, struct block *); 106 static void find_inedges(struct block *); 107 static void opt_root(struct block **); 108 static void opt_loop(struct block *, int); 109 static void fold_op(struct stmt *, int, int); 110 static __inline struct slist *this_op(struct slist *); 111 static void opt_not(struct block *); 112 static void opt_peep(struct block *); 113 static void opt_stmt(struct stmt *, int[], int); 114 static void deadstmt(struct stmt *, struct stmt *[]); 115 static void opt_deadstores(struct block *); 116 static void opt_blk(struct block *, int); 117 static int use_conflict(struct block *, struct block *); 118 static void opt_j(struct edge *); 119 static struct block *fold_edge(struct block *, struct edge *); 120 static __inline int eq_blk(struct block *, struct block *); 121 static int slength(struct slist *); 122 static int count_blocks(struct block *); 123 static void number_blks_r(struct block *); 124 static int count_stmts(struct block *); 125 static int convert_code_r(struct block *); 126 #ifdef BDEBUG 127 static void opt_dump(struct block *); 128 #endif 129 130 static int n_blocks; 131 struct block **blocks; 132 static int n_edges; 133 struct edge **edges; 134 135 /* 136 * A bit vector set representation of the dominators. 137 * We round up the set size to the next power of two. 138 */ 139 static int nodewords; 140 static int edgewords; 141 struct block **levels; 142 bpf_u_int32 *space1; 143 bpf_u_int32 *space2; 144 #define BITS_PER_WORD (8*sizeof(bpf_u_int32)) 145 /* 146 * True if a is in uset {p} 147 */ 148 #define SET_MEMBER(p, a) \ 149 ((p)[(unsigned)(a) / BITS_PER_WORD] & (1 << ((unsigned)(a) % BITS_PER_WORD))) 150 151 /* 152 * Add 'a' to uset p. 153 */ 154 #define SET_INSERT(p, a) \ 155 (p)[(unsigned)(a) / BITS_PER_WORD] |= (1 << ((unsigned)(a) % BITS_PER_WORD)) 156 157 /* 158 * Delete 'a' from uset p. 159 */ 160 #define SET_DELETE(p, a) \ 161 (p)[(unsigned)(a) / BITS_PER_WORD] &= ~(1 << ((unsigned)(a) % BITS_PER_WORD)) 162 163 /* 164 * a := a intersect b 165 */ 166 #define SET_INTERSECT(a, b, n)\ 167 {\ 168 bpf_u_int32 *_x = a, *_y = b;\ 169 int _n = n;\ 170 while (--_n >= 0) *_x++ &= *_y++;\ 171 } 172 173 /* 174 * a := a - b 175 */ 176 #define SET_SUBTRACT(a, b, n)\ 177 {\ 178 bpf_u_int32 *_x = a, *_y = b;\ 179 int _n = n;\ 180 while (--_n >= 0) *_x++ &=~ *_y++;\ 181 } 182 183 /* 184 * a := a union b 185 */ 186 #define SET_UNION(a, b, n)\ 187 {\ 188 bpf_u_int32 *_x = a, *_y = b;\ 189 int _n = n;\ 190 while (--_n >= 0) *_x++ |= *_y++;\ 191 } 192 193 static uset all_dom_sets; 194 static uset all_closure_sets; 195 static uset all_edge_sets; 196 197 #ifndef MAX 198 #define MAX(a,b) ((a)>(b)?(a):(b)) 199 #endif 200 201 static void 202 find_levels_r(b) 203 struct block *b; 204 { 205 int level; 206 207 if (isMarked(b)) 208 return; 209 210 Mark(b); 211 b->link = 0; 212 213 if (JT(b)) { 214 find_levels_r(JT(b)); 215 find_levels_r(JF(b)); 216 level = MAX(JT(b)->level, JF(b)->level) + 1; 217 } else 218 level = 0; 219 b->level = level; 220 b->link = levels[level]; 221 levels[level] = b; 222 } 223 224 /* 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. 229 */ 230 static void 231 find_levels(root) 232 struct block *root; 233 { 234 memset((char *)levels, 0, n_blocks * sizeof(*levels)); 235 unMarkAll(); 236 find_levels_r(root); 237 } 238 239 /* 240 * Find dominator relationships. 241 * Assumes graph has been leveled. 242 */ 243 static void 244 find_dom(root) 245 struct block *root; 246 { 247 int i; 248 struct block *b; 249 bpf_u_int32 *x; 250 251 /* 252 * Initialize sets to contain all nodes. 253 */ 254 x = all_dom_sets; 255 i = n_blocks * nodewords; 256 while (--i >= 0) 257 *x++ = ~0; 258 /* Root starts off empty. */ 259 for (i = nodewords; --i >= 0;) 260 root->dom[i] = 0; 261 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); 266 if (JT(b) == 0) 267 continue; 268 SET_INTERSECT(JT(b)->dom, b->dom, nodewords); 269 SET_INTERSECT(JF(b)->dom, b->dom, nodewords); 270 } 271 } 272 } 273 274 static void 275 propedom(ep) 276 struct edge *ep; 277 { 278 SET_INSERT(ep->edom, ep->id); 279 if (ep->succ) { 280 SET_INTERSECT(ep->succ->et.edom, ep->edom, edgewords); 281 SET_INTERSECT(ep->succ->ef.edom, ep->edom, edgewords); 282 } 283 } 284 285 /* 286 * Compute edge dominators. 287 * Assumes graph has been leveled and predecessors established. 288 */ 289 static void 290 find_edom(root) 291 struct block *root; 292 { 293 int i; 294 uset x; 295 struct block *b; 296 297 x = all_edge_sets; 298 for (i = n_edges * edgewords; --i >= 0; ) 299 x[i] = ~0; 300 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) { 306 propedom(&b->et); 307 propedom(&b->ef); 308 } 309 } 310 } 311 312 /* 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. 316 * 317 * Assumes graph has been leveled. 318 */ 319 static void 320 find_closure(root) 321 struct block *root; 322 { 323 int i; 324 struct block *b; 325 326 /* 327 * Initialize sets to contain no nodes. 328 */ 329 memset((char *)all_closure_sets, 0, 330 n_blocks * nodewords * sizeof(*all_closure_sets)); 331 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); 336 if (JT(b) == 0) 337 continue; 338 SET_UNION(JT(b)->closure, b->closure, nodewords); 339 SET_UNION(JF(b)->closure, b->closure, nodewords); 340 } 341 } 342 } 343 344 /* 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. 347 * 348 * The implementation should probably change to an array access. 349 */ 350 static int 351 atomuse(s) 352 struct stmt *s; 353 { 354 int c = s->code; 355 356 if (c == NOP) 357 return -1; 358 359 switch (BPF_CLASS(c)) { 360 361 case BPF_RET: 362 return (BPF_RVAL(c) == BPF_A) ? A_ATOM : 363 (BPF_RVAL(c) == BPF_X) ? X_ATOM : -1; 364 365 case BPF_LD: 366 case BPF_LDX: 367 return (BPF_MODE(c) == BPF_IND) ? X_ATOM : 368 (BPF_MODE(c) == BPF_MEM) ? s->k : -1; 369 370 case BPF_ST: 371 return A_ATOM; 372 373 case BPF_STX: 374 return X_ATOM; 375 376 case BPF_JMP: 377 case BPF_ALU: 378 if (BPF_SRC(c) == BPF_X) 379 return AX_ATOM; 380 return A_ATOM; 381 382 case BPF_MISC: 383 return BPF_MISCOP(c) == BPF_TXA ? X_ATOM : A_ATOM; 384 } 385 abort(); 386 /* NOTREACHED */ 387 } 388 389 /* 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. 393 * 394 * The implementation should probably change to an array access. 395 */ 396 static int 397 atomdef(s) 398 struct stmt *s; 399 { 400 if (s->code == NOP) 401 return -1; 402 403 switch (BPF_CLASS(s->code)) { 404 405 case BPF_LD: 406 case BPF_ALU: 407 return A_ATOM; 408 409 case BPF_LDX: 410 return X_ATOM; 411 412 case BPF_ST: 413 case BPF_STX: 414 return s->k; 415 416 case BPF_MISC: 417 return BPF_MISCOP(s->code) == BPF_TAX ? X_ATOM : A_ATOM; 418 } 419 return -1; 420 } 421 422 static void 423 compute_local_ud(b) 424 struct block *b; 425 { 426 struct slist *s; 427 atomset def = 0, use = 0, kill = 0; 428 int atom; 429 430 for (s = b->stmts; s; s = s->next) { 431 if (s->s.code == NOP) 432 continue; 433 atom = atomuse(&s->s); 434 if (atom >= 0) { 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); 440 } 441 else if (atom < N_ATOMS) { 442 if (!ATOMELEM(def, atom)) 443 use |= ATOMMASK(atom); 444 } 445 else 446 abort(); 447 } 448 atom = atomdef(&s->s); 449 if (atom >= 0) { 450 if (!ATOMELEM(use, atom)) 451 kill |= ATOMMASK(atom); 452 def |= ATOMMASK(atom); 453 } 454 } 455 if (!ATOMELEM(def, A_ATOM) && BPF_CLASS(b->s.code) == BPF_JMP) 456 use |= ATOMMASK(A_ATOM); 457 458 b->def = def; 459 b->kill = kill; 460 b->in_use = use; 461 } 462 463 /* 464 * Assume graph is already leveled. 465 */ 466 static void 467 find_ud(root) 468 struct block *root; 469 { 470 int i, maxlevel; 471 struct block *p; 472 473 /* 474 * root->level is the highest level no found; 475 * count down from there. 476 */ 477 maxlevel = root->level; 478 for (i = maxlevel; i >= 0; --i) 479 for (p = levels[i]; p; p = p->link) { 480 compute_local_ud(p); 481 p->out_use = 0; 482 } 483 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; 488 } 489 } 490 } 491 492 /* 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. 497 */ 498 struct valnode { 499 int code; 500 int v0, v1; 501 int val; 502 struct valnode *next; 503 }; 504 505 #define MODULUS 213 506 static struct valnode *hashtbl[MODULUS]; 507 static int curval; 508 static int maxval; 509 510 /* Integer constants mapped with the load immediate opcode. */ 511 #define K(i) F(BPF_LD|BPF_IMM|BPF_W, i, 0L) 512 513 struct vmapinfo { 514 int is_const; 515 bpf_int32 const_val; 516 }; 517 518 struct vmapinfo *vmap; 519 struct valnode *vnode_base; 520 struct valnode *next_vnode; 521 522 static void 523 init_val() 524 { 525 curval = 0; 526 next_vnode = vnode_base; 527 memset((char *)vmap, 0, maxval * sizeof(*vmap)); 528 memset((char *)hashtbl, 0, sizeof hashtbl); 529 } 530 531 /* Because we really don't have an IR, this stuff is a little messy. */ 532 static int 533 F(code, v0, v1) 534 int code; 535 int v0, v1; 536 { 537 u_int hash; 538 int val; 539 struct valnode *p; 540 541 hash = (u_int)code ^ (v0 << 4) ^ (v1 << 8); 542 hash %= MODULUS; 543 544 for (p = hashtbl[hash]; p; p = p->next) 545 if (p->code == code && p->v0 == v0 && p->v1 == v1) 546 return p->val; 547 548 val = ++curval; 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; 553 } 554 p = next_vnode++; 555 p->val = val; 556 p->code = code; 557 p->v0 = v0; 558 p->v1 = v1; 559 p->next = hashtbl[hash]; 560 hashtbl[hash] = p; 561 562 return val; 563 } 564 565 static __inline void 566 vstore(s, valp, newval, alter) 567 struct stmt *s; 568 int *valp; 569 int newval; 570 int alter; 571 { 572 if (alter && *valp == newval) 573 s->code = NOP; 574 else 575 *valp = newval; 576 } 577 578 static void 579 fold_op(s, v0, v1) 580 struct stmt *s; 581 int v0, v1; 582 { 583 bpf_int32 a, b; 584 585 a = vmap[v0].const_val; 586 b = vmap[v1].const_val; 587 588 switch (BPF_OP(s->code)) { 589 case BPF_ADD: 590 a += b; 591 break; 592 593 case BPF_SUB: 594 a -= b; 595 break; 596 597 case BPF_MUL: 598 a *= b; 599 break; 600 601 case BPF_DIV: 602 if (b == 0) 603 bpf_error("division by zero"); 604 a /= b; 605 break; 606 607 case BPF_AND: 608 a &= b; 609 break; 610 611 case BPF_OR: 612 a |= b; 613 break; 614 615 case BPF_LSH: 616 a <<= b; 617 break; 618 619 case BPF_RSH: 620 a >>= b; 621 break; 622 623 case BPF_NEG: 624 a = -a; 625 break; 626 627 default: 628 abort(); 629 } 630 s->k = a; 631 s->code = BPF_LD|BPF_IMM; 632 done = 0; 633 } 634 635 static __inline struct slist * 636 this_op(s) 637 struct slist *s; 638 { 639 while (s != 0 && s->s.code == NOP) 640 s = s->next; 641 return s; 642 } 643 644 static void 645 opt_not(b) 646 struct block *b; 647 { 648 struct block *tmp = JT(b); 649 650 JT(b) = JF(b); 651 JF(b) = tmp; 652 } 653 654 static void 655 opt_peep(b) 656 struct block *b; 657 { 658 struct slist *s; 659 struct slist *next, *last; 660 int val; 661 662 s = b->stmts; 663 if (s == 0) 664 return; 665 666 last = s; 667 while (1) { 668 s = this_op(s); 669 if (s == 0) 670 break; 671 next = this_op(s->next); 672 if (next == 0) 673 break; 674 last = next; 675 676 /* 677 * st M[k] --> st M[k] 678 * ldx M[k] tax 679 */ 680 if (s->s.code == BPF_ST && 681 next->s.code == (BPF_LDX|BPF_MEM) && 682 s->s.k == next->s.k) { 683 done = 0; 684 next->s.code = BPF_MISC|BPF_TAX; 685 } 686 /* 687 * ld #k --> ldx #k 688 * tax txa 689 */ 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; 694 done = 0; 695 } 696 /* 697 * This is an ugly special case, but it happens 698 * when you say tcp[k] or udp[k] where k is a constant. 699 */ 700 if (s->s.code == (BPF_LD|BPF_IMM)) { 701 struct slist *add, *tax, *ild; 702 703 /* 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. 708 */ 709 if (ATOMELEM(b->out_use, X_ATOM)) 710 break; 711 712 if (next->s.code != (BPF_LDX|BPF_MSH|BPF_B)) 713 add = next; 714 else 715 add = this_op(next->next); 716 if (add == 0 || add->s.code != (BPF_ALU|BPF_ADD|BPF_X)) 717 break; 718 719 tax = this_op(add->next); 720 if (tax == 0 || tax->s.code != (BPF_MISC|BPF_TAX)) 721 break; 722 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) 726 break; 727 /* 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. 732 * 733 * We want to turn this sequence: 734 * 735 * (004) ldi #0x2 {s} 736 * (005) ldxms [14] {next} -- optional 737 * (006) addx {add} 738 * (007) tax {tax} 739 * (008) ild [x+0] {ild} 740 * 741 * into this sequence: 742 * 743 * (004) nop 744 * (005) ldxms [14] 745 * (006) nop 746 * (007) nop 747 * (008) ild [x+2] 748 * 749 */ 750 ild->s.k += s->s.k; 751 s->s.code = NOP; 752 add->s.code = NOP; 753 tax->s.code = NOP; 754 done = 0; 755 } 756 s = next; 757 } 758 /* 759 * If we have a subtract to do a comparison, and the X register 760 * is a known constant, we can merge this value into the 761 * comparison. 762 */ 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) { 767 int op; 768 769 b->s.k += vmap[val].const_val; 770 op = BPF_OP(b->s.code); 771 if (op == BPF_JGT || op == BPF_JGE) { 772 struct block *t = JT(b); 773 JT(b) = JF(b); 774 JF(b) = t; 775 b->s.k += 0x80000000; 776 } 777 last->s.code = NOP; 778 done = 0; 779 } else if (b->s.k == 0) { 780 /* 781 * sub x -> nop 782 * j #0 j x 783 */ 784 last->s.code = NOP; 785 b->s.code = BPF_CLASS(b->s.code) | BPF_OP(b->s.code) | 786 BPF_X; 787 done = 0; 788 } 789 } 790 /* 791 * Likewise, a constant subtract can be simplified. 792 */ 793 else if (last->s.code == (BPF_ALU|BPF_SUB|BPF_K) && 794 !ATOMELEM(b->out_use, A_ATOM)) { 795 int op; 796 797 b->s.k += last->s.k; 798 last->s.code = NOP; 799 op = BPF_OP(b->s.code); 800 if (op == BPF_JGT || op == BPF_JGE) { 801 struct block *t = JT(b); 802 JT(b) = JF(b); 803 JF(b) = t; 804 b->s.k += 0x80000000; 805 } 806 done = 0; 807 } 808 /* 809 * and #k nop 810 * jeq #0 -> jset #k 811 */ 812 if (last->s.code == (BPF_ALU|BPF_AND|BPF_K) && 813 !ATOMELEM(b->out_use, A_ATOM) && b->s.k == 0) { 814 b->s.k = last->s.k; 815 b->s.code = BPF_JMP|BPF_K|BPF_JSET; 816 last->s.code = NOP; 817 done = 0; 818 opt_not(b); 819 } 820 /* 821 * If the accumulator is a known constant, we can compute the 822 * comparison result. 823 */ 824 val = b->val[A_ATOM]; 825 if (vmap[val].is_const && BPF_SRC(b->s.code) == BPF_K) { 826 bpf_int32 v = vmap[val].const_val; 827 switch (BPF_OP(b->s.code)) { 828 829 case BPF_JEQ: 830 v = v == b->s.k; 831 break; 832 833 case BPF_JGT: 834 v = (unsigned)v > b->s.k; 835 break; 836 837 case BPF_JGE: 838 v = (unsigned)v >= b->s.k; 839 break; 840 841 case BPF_JSET: 842 v &= b->s.k; 843 break; 844 845 default: 846 abort(); 847 } 848 if (JF(b) != JT(b)) 849 done = 0; 850 if (v) 851 JF(b) = JT(b); 852 else 853 JT(b) = JF(b); 854 } 855 } 856 857 /* 858 * Compute the symbolic value of expression of 's', and update 859 * anything it defines in the value table 'val'. If 'alter' is true, 860 * do various optimizations. This code would be cleaner if symbolic 861 * evaluation and code transformations weren't folded together. 862 */ 863 static void 864 opt_stmt(s, val, alter) 865 struct stmt *s; 866 int val[]; 867 int alter; 868 { 869 int op; 870 int v; 871 872 switch (s->code) { 873 874 case BPF_LD|BPF_ABS|BPF_W: 875 case BPF_LD|BPF_ABS|BPF_H: 876 case BPF_LD|BPF_ABS|BPF_B: 877 v = F(s->code, s->k, 0L); 878 vstore(s, &val[A_ATOM], v, alter); 879 break; 880 881 case BPF_LD|BPF_IND|BPF_W: 882 case BPF_LD|BPF_IND|BPF_H: 883 case BPF_LD|BPF_IND|BPF_B: 884 v = val[X_ATOM]; 885 if (alter && vmap[v].is_const) { 886 s->code = BPF_LD|BPF_ABS|BPF_SIZE(s->code); 887 s->k += vmap[v].const_val; 888 v = F(s->code, s->k, 0L); 889 done = 0; 890 } 891 else 892 v = F(s->code, s->k, v); 893 vstore(s, &val[A_ATOM], v, alter); 894 break; 895 896 case BPF_LD|BPF_LEN: 897 case BPF_LD|BPF_RND: 898 v = F(s->code, 0L, 0L); 899 vstore(s, &val[A_ATOM], v, alter); 900 break; 901 902 case BPF_LD|BPF_IMM: 903 v = K(s->k); 904 vstore(s, &val[A_ATOM], v, alter); 905 break; 906 907 case BPF_LDX|BPF_IMM: 908 v = K(s->k); 909 vstore(s, &val[X_ATOM], v, alter); 910 break; 911 912 case BPF_LDX|BPF_MSH|BPF_B: 913 v = F(s->code, s->k, 0L); 914 vstore(s, &val[X_ATOM], v, alter); 915 break; 916 917 case BPF_ALU|BPF_NEG: 918 if (alter && vmap[val[A_ATOM]].is_const) { 919 s->code = BPF_LD|BPF_IMM; 920 s->k = -vmap[val[A_ATOM]].const_val; 921 val[A_ATOM] = K(s->k); 922 } 923 else 924 val[A_ATOM] = F(s->code, val[A_ATOM], 0L); 925 break; 926 927 case BPF_ALU|BPF_ADD|BPF_K: 928 case BPF_ALU|BPF_SUB|BPF_K: 929 case BPF_ALU|BPF_MUL|BPF_K: 930 case BPF_ALU|BPF_DIV|BPF_K: 931 case BPF_ALU|BPF_AND|BPF_K: 932 case BPF_ALU|BPF_OR|BPF_K: 933 case BPF_ALU|BPF_LSH|BPF_K: 934 case BPF_ALU|BPF_RSH|BPF_K: 935 op = BPF_OP(s->code); 936 if (alter) { 937 if (s->k == 0) { 938 if (op == BPF_ADD || op == BPF_SUB || 939 op == BPF_LSH || op == BPF_RSH || 940 op == BPF_OR) { 941 s->code = NOP; 942 break; 943 } 944 if (op == BPF_MUL || op == BPF_AND) { 945 s->code = BPF_LD|BPF_IMM; 946 val[A_ATOM] = K(s->k); 947 break; 948 } 949 } 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); 953 break; 954 } 955 } 956 val[A_ATOM] = F(s->code, val[A_ATOM], K(s->k)); 957 break; 958 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); 972 } 973 else { 974 s->code = BPF_ALU|BPF_K|op; 975 s->k = vmap[val[X_ATOM]].const_val; 976 done = 0; 977 val[A_ATOM] = 978 F(s->code, val[A_ATOM], K(s->k)); 979 } 980 break; 981 } 982 /* 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 986 * optimizations. 987 * XXX We could also check for mul by 1, and -1, etc. 988 */ 989 if (alter && vmap[val[A_ATOM]].is_const 990 && vmap[val[A_ATOM]].const_val == 0) { 991 if (op == BPF_ADD || op == BPF_OR || 992 op == BPF_LSH || op == BPF_RSH || op == BPF_SUB) { 993 s->code = BPF_MISC|BPF_TXA; 994 vstore(s, &val[A_ATOM], val[X_ATOM], alter); 995 break; 996 } 997 else if (op == BPF_MUL || op == BPF_DIV || 998 op == BPF_AND) { 999 s->code = BPF_LD|BPF_IMM; 1000 s->k = 0; 1001 vstore(s, &val[A_ATOM], K(s->k), alter); 1002 break; 1003 } 1004 else if (op == BPF_NEG) { 1005 s->code = NOP; 1006 break; 1007 } 1008 } 1009 val[A_ATOM] = F(s->code, val[A_ATOM], val[X_ATOM]); 1010 break; 1011 1012 case BPF_MISC|BPF_TXA: 1013 vstore(s, &val[A_ATOM], val[X_ATOM], alter); 1014 break; 1015 1016 case BPF_LD|BPF_MEM: 1017 v = val[s->k]; 1018 if (alter && vmap[v].is_const) { 1019 s->code = BPF_LD|BPF_IMM; 1020 s->k = vmap[v].const_val; 1021 done = 0; 1022 } 1023 vstore(s, &val[A_ATOM], v, alter); 1024 break; 1025 1026 case BPF_MISC|BPF_TAX: 1027 vstore(s, &val[X_ATOM], val[A_ATOM], alter); 1028 break; 1029 1030 case BPF_LDX|BPF_MEM: 1031 v = val[s->k]; 1032 if (alter && vmap[v].is_const) { 1033 s->code = BPF_LDX|BPF_IMM; 1034 s->k = vmap[v].const_val; 1035 done = 0; 1036 } 1037 vstore(s, &val[X_ATOM], v, alter); 1038 break; 1039 1040 case BPF_ST: 1041 vstore(s, &val[s->k], val[A_ATOM], alter); 1042 break; 1043 1044 case BPF_STX: 1045 vstore(s, &val[s->k], val[X_ATOM], alter); 1046 break; 1047 } 1048 } 1049 1050 static void 1051 deadstmt(s, last) 1052 struct stmt *s; 1053 struct stmt *last[]; 1054 { 1055 int atom; 1056 1057 atom = atomuse(s); 1058 if (atom >= 0) { 1059 if (atom == AX_ATOM) { 1060 last[X_ATOM] = 0; 1061 last[A_ATOM] = 0; 1062 } 1063 else 1064 last[atom] = 0; 1065 } 1066 atom = atomdef(s); 1067 if (atom >= 0) { 1068 if (last[atom]) { 1069 done = 0; 1070 last[atom]->code = NOP; 1071 } 1072 last[atom] = s; 1073 } 1074 } 1075 1076 static void 1077 opt_deadstores(b) 1078 struct block *b; 1079 { 1080 struct slist *s; 1081 int atom; 1082 struct stmt *last[N_ATOMS]; 1083 1084 memset((char *)last, 0, sizeof last); 1085 1086 for (s = b->stmts; s != 0; s = s->next) 1087 deadstmt(&s->s, last); 1088 deadstmt(&b->s, last); 1089 1090 for (atom = 0; atom < N_ATOMS; ++atom) 1091 if (last[atom] && !ATOMELEM(b->out_use, atom)) { 1092 last[atom]->code = NOP; 1093 done = 0; 1094 } 1095 } 1096 1097 static void 1098 opt_blk(b, do_stmts) 1099 struct block *b; 1100 int do_stmts; 1101 { 1102 struct slist *s; 1103 struct edge *p; 1104 int i; 1105 bpf_int32 aval; 1106 1107 #if 0 1108 for (s = b->stmts; s && s->next; s = s->next) 1109 if (BPF_CLASS(s->s.code) == BPF_JMP) { 1110 do_stmts = 0; 1111 break; 1112 } 1113 #endif 1114 1115 /* 1116 * Initialize the atom values. 1117 * If we have no predecessors, everything is undefined. 1118 * Otherwise, we inherent our values from our predecessors. 1119 * If any register has an ambiguous value (i.e. control paths are 1120 * merging) give it the undefined value of 0. 1121 */ 1122 p = b->in_edges; 1123 if (p == 0) 1124 memset((char *)b->val, 0, sizeof(b->val)); 1125 else { 1126 memcpy((char *)b->val, (char *)p->pred->val, sizeof(b->val)); 1127 while ((p = p->next) != NULL) { 1128 for (i = 0; i < N_ATOMS; ++i) 1129 if (b->val[i] != p->pred->val[i]) 1130 b->val[i] = 0; 1131 } 1132 } 1133 aval = b->val[A_ATOM]; 1134 for (s = b->stmts; s; s = s->next) 1135 opt_stmt(&s->s, b->val, do_stmts); 1136 1137 /* 1138 * This is a special case: if we don't use anything from this 1139 * block, and we load the accumulator with value that is 1140 * already there, or if this block is a return, 1141 * eliminate all the statements. 1142 */ 1143 if (do_stmts && 1144 ((b->out_use == 0 && aval != 0 &&b->val[A_ATOM] == aval) || 1145 BPF_CLASS(b->s.code) == BPF_RET)) { 1146 if (b->stmts != 0) { 1147 b->stmts = 0; 1148 done = 0; 1149 } 1150 } else { 1151 opt_peep(b); 1152 opt_deadstores(b); 1153 } 1154 /* 1155 * Set up values for branch optimizer. 1156 */ 1157 if (BPF_SRC(b->s.code) == BPF_K) 1158 b->oval = K(b->s.k); 1159 else 1160 b->oval = b->val[X_ATOM]; 1161 b->et.code = b->s.code; 1162 b->ef.code = -b->s.code; 1163 } 1164 1165 /* 1166 * Return true if any register that is used on exit from 'succ', has 1167 * an exit value that is different from the corresponding exit value 1168 * from 'b'. 1169 */ 1170 static int 1171 use_conflict(b, succ) 1172 struct block *b, *succ; 1173 { 1174 int atom; 1175 atomset use = succ->out_use; 1176 1177 if (use == 0) 1178 return 0; 1179 1180 for (atom = 0; atom < N_ATOMS; ++atom) 1181 if (ATOMELEM(use, atom)) 1182 if (b->val[atom] != succ->val[atom]) 1183 return 1; 1184 return 0; 1185 } 1186 1187 static struct block * 1188 fold_edge(child, ep) 1189 struct block *child; 1190 struct edge *ep; 1191 { 1192 int sense; 1193 int aval0, aval1, oval0, oval1; 1194 int code = ep->code; 1195 1196 if (code < 0) { 1197 code = -code; 1198 sense = 0; 1199 } else 1200 sense = 1; 1201 1202 if (child->s.code != code) 1203 return 0; 1204 1205 aval0 = child->val[A_ATOM]; 1206 oval0 = child->oval; 1207 aval1 = ep->pred->val[A_ATOM]; 1208 oval1 = ep->pred->oval; 1209 1210 if (aval0 != aval1) 1211 return 0; 1212 1213 if (oval0 == oval1) 1214 /* 1215 * The operands are identical, so the 1216 * result is true if a true branch was 1217 * taken to get here, otherwise false. 1218 */ 1219 return sense ? JT(child) : JF(child); 1220 1221 if (sense && code == (BPF_JMP|BPF_JEQ|BPF_K)) 1222 /* 1223 * At this point, we only know the comparison if we 1224 * came down the true branch, and it was an equality 1225 * comparison with a constant. We rely on the fact that 1226 * distinct constants have distinct value numbers. 1227 */ 1228 return JF(child); 1229 1230 return 0; 1231 } 1232 1233 static void 1234 opt_j(ep) 1235 struct edge *ep; 1236 { 1237 int i, k; 1238 struct block *target; 1239 1240 if (JT(ep->succ) == 0) 1241 return; 1242 1243 if (JT(ep->succ) == JF(ep->succ)) { 1244 /* 1245 * Common branch targets can be eliminated, provided 1246 * there is no data dependency. 1247 */ 1248 if (!use_conflict(ep->pred, ep->succ->et.succ)) { 1249 done = 0; 1250 ep->succ = JT(ep->succ); 1251 } 1252 } 1253 /* 1254 * For each edge dominator that matches the successor of this 1255 * edge, promote the edge successor to the its grandchild. 1256 * 1257 * XXX We violate the set abstraction here in favor a reasonably 1258 * efficient loop. 1259 */ 1260 top: 1261 for (i = 0; i < edgewords; ++i) { 1262 bpf_u_int32 x = ep->edom[i]; 1263 1264 while (x != 0) { 1265 k = ffs(x) - 1; 1266 x &=~ (1 << k); 1267 k += i * BITS_PER_WORD; 1268 1269 target = fold_edge(ep->succ, edges[k]); 1270 /* 1271 * Check that there is no data dependency between 1272 * nodes that will be violated if we move the edge. 1273 */ 1274 if (target != 0 && !use_conflict(ep->pred, target)) { 1275 done = 0; 1276 ep->succ = target; 1277 if (JT(target) != 0) 1278 /* 1279 * Start over unless we hit a leaf. 1280 */ 1281 goto top; 1282 return; 1283 } 1284 } 1285 } 1286 } 1287 1288 1289 static void 1290 or_pullup(b) 1291 struct block *b; 1292 { 1293 int val, at_top; 1294 struct block *pull; 1295 struct block **diffp, **samep; 1296 struct edge *ep; 1297 1298 ep = b->in_edges; 1299 if (ep == 0) 1300 return; 1301 1302 /* 1303 * Make sure each predecessor loads the same value. 1304 * XXX why? 1305 */ 1306 val = ep->pred->val[A_ATOM]; 1307 for (ep = ep->next; ep != 0; ep = ep->next) 1308 if (val != ep->pred->val[A_ATOM]) 1309 return; 1310 1311 if (JT(b->in_edges->pred) == b) 1312 diffp = &JT(b->in_edges->pred); 1313 else 1314 diffp = &JF(b->in_edges->pred); 1315 1316 at_top = 1; 1317 while (1) { 1318 if (*diffp == 0) 1319 return; 1320 1321 if (JT(*diffp) != JT(b)) 1322 return; 1323 1324 if (!SET_MEMBER((*diffp)->dom, b->id)) 1325 return; 1326 1327 if ((*diffp)->val[A_ATOM] != val) 1328 break; 1329 1330 diffp = &JF(*diffp); 1331 at_top = 0; 1332 } 1333 samep = &JF(*diffp); 1334 while (1) { 1335 if (*samep == 0) 1336 return; 1337 1338 if (JT(*samep) != JT(b)) 1339 return; 1340 1341 if (!SET_MEMBER((*samep)->dom, b->id)) 1342 return; 1343 1344 if ((*samep)->val[A_ATOM] == val) 1345 break; 1346 1347 /* XXX Need to check that there are no data dependencies 1348 between dp0 and dp1. Currently, the code generator 1349 will not produce such dependencies. */ 1350 samep = &JF(*samep); 1351 } 1352 #ifdef notdef 1353 /* XXX This doesn't cover everything. */ 1354 for (i = 0; i < N_ATOMS; ++i) 1355 if ((*samep)->val[i] != pred->val[i]) 1356 return; 1357 #endif 1358 /* Pull up the node. */ 1359 pull = *samep; 1360 *samep = JF(pull); 1361 JF(pull) = *diffp; 1362 1363 /* 1364 * At the top of the chain, each predecessor needs to point at the 1365 * pulled up node. Inside the chain, there is only one predecessor 1366 * to worry about. 1367 */ 1368 if (at_top) { 1369 for (ep = b->in_edges; ep != 0; ep = ep->next) { 1370 if (JT(ep->pred) == b) 1371 JT(ep->pred) = pull; 1372 else 1373 JF(ep->pred) = pull; 1374 } 1375 } 1376 else 1377 *diffp = pull; 1378 1379 done = 0; 1380 } 1381 1382 static void 1383 and_pullup(b) 1384 struct block *b; 1385 { 1386 int val, at_top; 1387 struct block *pull; 1388 struct block **diffp, **samep; 1389 struct edge *ep; 1390 1391 ep = b->in_edges; 1392 if (ep == 0) 1393 return; 1394 1395 /* 1396 * Make sure each predecessor loads the same value. 1397 */ 1398 val = ep->pred->val[A_ATOM]; 1399 for (ep = ep->next; ep != 0; ep = ep->next) 1400 if (val != ep->pred->val[A_ATOM]) 1401 return; 1402 1403 if (JT(b->in_edges->pred) == b) 1404 diffp = &JT(b->in_edges->pred); 1405 else 1406 diffp = &JF(b->in_edges->pred); 1407 1408 at_top = 1; 1409 while (1) { 1410 if (*diffp == 0) 1411 return; 1412 1413 if (JF(*diffp) != JF(b)) 1414 return; 1415 1416 if (!SET_MEMBER((*diffp)->dom, b->id)) 1417 return; 1418 1419 if ((*diffp)->val[A_ATOM] != val) 1420 break; 1421 1422 diffp = &JT(*diffp); 1423 at_top = 0; 1424 } 1425 samep = &JT(*diffp); 1426 while (1) { 1427 if (*samep == 0) 1428 return; 1429 1430 if (JF(*samep) != JF(b)) 1431 return; 1432 1433 if (!SET_MEMBER((*samep)->dom, b->id)) 1434 return; 1435 1436 if ((*samep)->val[A_ATOM] == val) 1437 break; 1438 1439 /* XXX Need to check that there are no data dependencies 1440 between diffp and samep. Currently, the code generator 1441 will not produce such dependencies. */ 1442 samep = &JT(*samep); 1443 } 1444 #ifdef notdef 1445 /* XXX This doesn't cover everything. */ 1446 for (i = 0; i < N_ATOMS; ++i) 1447 if ((*samep)->val[i] != pred->val[i]) 1448 return; 1449 #endif 1450 /* Pull up the node. */ 1451 pull = *samep; 1452 *samep = JT(pull); 1453 JT(pull) = *diffp; 1454 1455 /* 1456 * At the top of the chain, each predecessor needs to point at the 1457 * pulled up node. Inside the chain, there is only one predecessor 1458 * to worry about. 1459 */ 1460 if (at_top) { 1461 for (ep = b->in_edges; ep != 0; ep = ep->next) { 1462 if (JT(ep->pred) == b) 1463 JT(ep->pred) = pull; 1464 else 1465 JF(ep->pred) = pull; 1466 } 1467 } 1468 else 1469 *diffp = pull; 1470 1471 done = 0; 1472 } 1473 1474 static void 1475 opt_blks(root, do_stmts) 1476 struct block *root; 1477 int do_stmts; 1478 { 1479 int i, maxlevel; 1480 struct block *p; 1481 1482 init_val(); 1483 maxlevel = root->level; 1484 for (i = maxlevel; i >= 0; --i) 1485 for (p = levels[i]; p; p = p->link) 1486 opt_blk(p, do_stmts); 1487 1488 if (do_stmts) 1489 /* 1490 * No point trying to move branches; it can't possibly 1491 * make a difference at this point. 1492 */ 1493 return; 1494 1495 for (i = 1; i <= maxlevel; ++i) { 1496 for (p = levels[i]; p; p = p->link) { 1497 opt_j(&p->et); 1498 opt_j(&p->ef); 1499 } 1500 } 1501 for (i = 1; i <= maxlevel; ++i) { 1502 for (p = levels[i]; p; p = p->link) { 1503 or_pullup(p); 1504 and_pullup(p); 1505 } 1506 } 1507 } 1508 1509 static __inline void 1510 link_inedge(parent, child) 1511 struct edge *parent; 1512 struct block *child; 1513 { 1514 parent->next = child->in_edges; 1515 child->in_edges = parent; 1516 } 1517 1518 static void 1519 find_inedges(root) 1520 struct block *root; 1521 { 1522 int i; 1523 struct block *b; 1524 1525 for (i = 0; i < n_blocks; ++i) 1526 blocks[i]->in_edges = 0; 1527 1528 /* 1529 * Traverse the graph, adding each edge to the predecessor 1530 * list of its successors. Skip the leaves (i.e. level 0). 1531 */ 1532 for (i = root->level; i > 0; --i) { 1533 for (b = levels[i]; b != 0; b = b->link) { 1534 link_inedge(&b->et, JT(b)); 1535 link_inedge(&b->ef, JF(b)); 1536 } 1537 } 1538 } 1539 1540 static void 1541 opt_root(b) 1542 struct block **b; 1543 { 1544 struct slist *tmp, *s; 1545 1546 s = (*b)->stmts; 1547 (*b)->stmts = 0; 1548 while (BPF_CLASS((*b)->s.code) == BPF_JMP && JT(*b) == JF(*b)) 1549 *b = JT(*b); 1550 1551 tmp = (*b)->stmts; 1552 if (tmp != 0) 1553 sappend(s, tmp); 1554 (*b)->stmts = s; 1555 1556 /* 1557 * If the root node is a return, then there is no 1558 * point executing any statements (since the bpf machine 1559 * has no side effects). 1560 */ 1561 if (BPF_CLASS((*b)->s.code) == BPF_RET) 1562 (*b)->stmts = 0; 1563 } 1564 1565 static void 1566 opt_loop(root, do_stmts) 1567 struct block *root; 1568 int do_stmts; 1569 { 1570 1571 #ifdef BDEBUG 1572 if (dflag > 1) 1573 opt_dump(root); 1574 #endif 1575 do { 1576 done = 1; 1577 find_levels(root); 1578 find_dom(root); 1579 find_closure(root); 1580 find_inedges(root); 1581 find_ud(root); 1582 find_edom(root); 1583 opt_blks(root, do_stmts); 1584 #ifdef BDEBUG 1585 if (dflag > 1) 1586 opt_dump(root); 1587 #endif 1588 } while (!done); 1589 } 1590 1591 /* 1592 * Optimize the filter code in its dag representation. 1593 */ 1594 void 1595 bpf_optimize(rootp) 1596 struct block **rootp; 1597 { 1598 struct block *root; 1599 1600 root = *rootp; 1601 1602 opt_init(root); 1603 opt_loop(root, 0); 1604 opt_loop(root, 1); 1605 intern_blocks(root); 1606 opt_root(rootp); 1607 opt_cleanup(); 1608 } 1609 1610 static void 1611 make_marks(p) 1612 struct block *p; 1613 { 1614 if (!isMarked(p)) { 1615 Mark(p); 1616 if (BPF_CLASS(p->s.code) != BPF_RET) { 1617 make_marks(JT(p)); 1618 make_marks(JF(p)); 1619 } 1620 } 1621 } 1622 1623 /* 1624 * Mark code array such that isMarked(i) is true 1625 * only for nodes that are alive. 1626 */ 1627 static void 1628 mark_code(p) 1629 struct block *p; 1630 { 1631 cur_mark += 1; 1632 make_marks(p); 1633 } 1634 1635 /* 1636 * True iff the two stmt lists load the same value from the packet into 1637 * the accumulator. 1638 */ 1639 static int 1640 eq_slist(x, y) 1641 struct slist *x, *y; 1642 { 1643 while (1) { 1644 while (x && x->s.code == NOP) 1645 x = x->next; 1646 while (y && y->s.code == NOP) 1647 y = y->next; 1648 if (x == 0) 1649 return y == 0; 1650 if (y == 0) 1651 return x == 0; 1652 if (x->s.code != y->s.code || x->s.k != y->s.k) 1653 return 0; 1654 x = x->next; 1655 y = y->next; 1656 } 1657 } 1658 1659 static __inline int 1660 eq_blk(b0, b1) 1661 struct block *b0, *b1; 1662 { 1663 if (b0->s.code == b1->s.code && 1664 b0->s.k == b1->s.k && 1665 b0->et.succ == b1->et.succ && 1666 b0->ef.succ == b1->ef.succ) 1667 return eq_slist(b0->stmts, b1->stmts); 1668 return 0; 1669 } 1670 1671 static void 1672 intern_blocks(root) 1673 struct block *root; 1674 { 1675 struct block *p; 1676 int i, j; 1677 int done; 1678 top: 1679 done = 1; 1680 for (i = 0; i < n_blocks; ++i) 1681 blocks[i]->link = 0; 1682 1683 mark_code(root); 1684 1685 for (i = n_blocks - 1; --i >= 0; ) { 1686 if (!isMarked(blocks[i])) 1687 continue; 1688 for (j = i + 1; j < n_blocks; ++j) { 1689 if (!isMarked(blocks[j])) 1690 continue; 1691 if (eq_blk(blocks[i], blocks[j])) { 1692 blocks[i]->link = blocks[j]->link ? 1693 blocks[j]->link : blocks[j]; 1694 break; 1695 } 1696 } 1697 } 1698 for (i = 0; i < n_blocks; ++i) { 1699 p = blocks[i]; 1700 if (JT(p) == 0) 1701 continue; 1702 if (JT(p)->link) { 1703 done = 0; 1704 JT(p) = JT(p)->link; 1705 } 1706 if (JF(p)->link) { 1707 done = 0; 1708 JF(p) = JF(p)->link; 1709 } 1710 } 1711 if (!done) 1712 goto top; 1713 } 1714 1715 static void 1716 opt_cleanup() 1717 { 1718 free((void *)vnode_base); 1719 free((void *)vmap); 1720 free((void *)edges); 1721 free((void *)space1); 1722 free((void *)space2); 1723 free((void *)levels); 1724 free((void *)blocks); 1725 } 1726 1727 /* 1728 * Return the number of stmts in 's'. 1729 */ 1730 static int 1731 slength(s) 1732 struct slist *s; 1733 { 1734 int n = 0; 1735 1736 for (; s; s = s->next) 1737 if (s->s.code != NOP) 1738 ++n; 1739 return n; 1740 } 1741 1742 /* 1743 * Return the number of nodes reachable by 'p'. 1744 * All nodes should be initially unmarked. 1745 */ 1746 static int 1747 count_blocks(p) 1748 struct block *p; 1749 { 1750 if (p == 0 || isMarked(p)) 1751 return 0; 1752 Mark(p); 1753 return count_blocks(JT(p)) + count_blocks(JF(p)) + 1; 1754 } 1755 1756 /* 1757 * Do a depth first search on the flow graph, numbering the 1758 * the basic blocks, and entering them into the 'blocks' array.` 1759 */ 1760 static void 1761 number_blks_r(p) 1762 struct block *p; 1763 { 1764 int n; 1765 1766 if (p == 0 || isMarked(p)) 1767 return; 1768 1769 Mark(p); 1770 n = n_blocks++; 1771 p->id = n; 1772 blocks[n] = p; 1773 1774 number_blks_r(JT(p)); 1775 number_blks_r(JF(p)); 1776 } 1777 1778 /* 1779 * Return the number of stmts in the flowgraph reachable by 'p'. 1780 * The nodes should be unmarked before calling. 1781 */ 1782 static int 1783 count_stmts(p) 1784 struct block *p; 1785 { 1786 int n; 1787 1788 if (p == 0 || isMarked(p)) 1789 return 0; 1790 Mark(p); 1791 n = count_stmts(JT(p)) + count_stmts(JF(p)); 1792 return slength(p->stmts) + n + 1 + p->longjt + p->longjf; 1793 } 1794 1795 /* 1796 * Allocate memory. All allocation is done before optimization 1797 * is begun. A linear bound on the size of all data structures is computed 1798 * from the total number of blocks and/or statements. 1799 */ 1800 static void 1801 opt_init(root) 1802 struct block *root; 1803 { 1804 bpf_u_int32 *p; 1805 int i, n, max_stmts; 1806 size_t size1, size2; 1807 1808 /* 1809 * First, count the blocks, so we can malloc an array to map 1810 * block number to block. Then, put the blocks into the array. 1811 */ 1812 unMarkAll(); 1813 n = count_blocks(root); 1814 blocks = reallocarray(NULL, n, sizeof(*blocks)); 1815 if (blocks == NULL) 1816 bpf_error("malloc"); 1817 1818 unMarkAll(); 1819 n_blocks = 0; 1820 number_blks_r(root); 1821 1822 n_edges = 2 * n_blocks; 1823 edges = reallocarray(NULL, n_edges, sizeof(*edges)); 1824 if (edges == NULL) 1825 bpf_error("malloc"); 1826 1827 /* 1828 * The number of levels is bounded by the number of nodes. 1829 */ 1830 levels = reallocarray(NULL, n_blocks, sizeof(*levels)); 1831 if (levels == NULL) 1832 bpf_error("malloc"); 1833 1834 edgewords = n_edges / (8 * sizeof(bpf_u_int32)) + 1; 1835 nodewords = n_blocks / (8 * sizeof(bpf_u_int32)) + 1; 1836 1837 size1 = 2; 1838 if (n_blocks > SIZE_MAX / size1) 1839 goto fail1; 1840 size1 *= n_blocks; 1841 if (nodewords > SIZE_MAX / size1) 1842 goto fail1; 1843 size1 *= nodewords; 1844 if (sizeof(*space1) > SIZE_MAX / size1) 1845 goto fail1; 1846 size1 *= sizeof(*space1); 1847 1848 space1 = (bpf_u_int32 *)malloc(size1); 1849 if (space1 == NULL) { 1850 fail1: 1851 bpf_error("malloc"); 1852 } 1853 1854 size2 = n_edges; 1855 if (edgewords > SIZE_MAX / size2) 1856 goto fail2; 1857 size2 *= edgewords; 1858 if (sizeof(*space2) > SIZE_MAX / size2) 1859 goto fail2; 1860 size2 *= sizeof(*space2); 1861 1862 space2 = (bpf_u_int32 *)malloc(size2); 1863 if (space2 == NULL) { 1864 fail2: 1865 free(space1); 1866 bpf_error("malloc"); 1867 } 1868 1869 p = space1; 1870 all_dom_sets = p; 1871 for (i = 0; i < n; ++i) { 1872 blocks[i]->dom = p; 1873 p += nodewords; 1874 } 1875 all_closure_sets = p; 1876 for (i = 0; i < n; ++i) { 1877 blocks[i]->closure = p; 1878 p += nodewords; 1879 } 1880 p = space2; 1881 all_edge_sets = p; 1882 for (i = 0; i < n; ++i) { 1883 struct block *b = blocks[i]; 1884 1885 b->et.edom = p; 1886 p += edgewords; 1887 b->ef.edom = p; 1888 p += edgewords; 1889 b->et.id = i; 1890 edges[i] = &b->et; 1891 b->ef.id = n_blocks + i; 1892 edges[n_blocks + i] = &b->ef; 1893 b->et.pred = b; 1894 b->ef.pred = b; 1895 } 1896 max_stmts = 0; 1897 for (i = 0; i < n; ++i) 1898 max_stmts += slength(blocks[i]->stmts) + 1; 1899 /* 1900 * We allocate at most 3 value numbers per statement, 1901 * so this is an upper bound on the number of valnodes 1902 * we'll need. 1903 */ 1904 maxval = 3 * max_stmts; 1905 vmap = reallocarray(NULL, maxval, sizeof(*vmap)); 1906 vnode_base = reallocarray(NULL, maxval, sizeof(*vnode_base)); 1907 if (vmap == NULL || vnode_base == NULL) 1908 bpf_error("malloc"); 1909 } 1910 1911 /* 1912 * Some pointers used to convert the basic block form of the code, 1913 * into the array form that BPF requires. 'fstart' will point to 1914 * the malloc'd array while 'ftail' is used during the recursive traversal. 1915 */ 1916 static struct bpf_insn *fstart; 1917 static struct bpf_insn *ftail; 1918 1919 #ifdef BDEBUG 1920 int bids[1000]; 1921 #endif 1922 1923 /* 1924 * Returns true if successful. Returns false if a branch has 1925 * an offset that is too large. If so, we have marked that 1926 * branch so that on a subsequent iteration, it will be treated 1927 * properly. 1928 */ 1929 static int 1930 convert_code_r(p) 1931 struct block *p; 1932 { 1933 struct bpf_insn *dst; 1934 struct slist *src; 1935 int slen; 1936 u_int off; 1937 int extrajmps; /* number of extra jumps inserted */ 1938 struct slist **offset = NULL; 1939 1940 if (p == 0 || isMarked(p)) 1941 return (1); 1942 Mark(p); 1943 1944 if (convert_code_r(JF(p)) == 0) 1945 return (0); 1946 if (convert_code_r(JT(p)) == 0) 1947 return (0); 1948 1949 slen = slength(p->stmts); 1950 dst = ftail -= (slen + 1 + p->longjt + p->longjf); 1951 /* inflate length by any extra jumps */ 1952 1953 p->offset = dst - fstart; 1954 1955 /* generate offset[] for convenience */ 1956 if (slen) { 1957 offset = calloc(slen, sizeof(struct slist *)); 1958 if (!offset) { 1959 bpf_error("not enough core"); 1960 /*NOTREACHED*/ 1961 } 1962 } 1963 src = p->stmts; 1964 for (off = 0; off < slen && src; off++) { 1965 #if 0 1966 printf("off=%d src=%x\n", off, src); 1967 #endif 1968 offset[off] = src; 1969 src = src->next; 1970 } 1971 1972 off = 0; 1973 for (src = p->stmts; src; src = src->next) { 1974 if (src->s.code == NOP) 1975 continue; 1976 dst->code = (u_short)src->s.code; 1977 dst->k = src->s.k; 1978 1979 /* fill block-local relative jump */ 1980 if (BPF_CLASS(src->s.code) != BPF_JMP || src->s.code == (BPF_JMP|BPF_JA)) { 1981 #if 0 1982 if (src->s.jt || src->s.jf) { 1983 bpf_error("illegal jmp destination"); 1984 /*NOTREACHED*/ 1985 } 1986 #endif 1987 goto filled; 1988 } 1989 if (off == slen - 2) /*???*/ 1990 goto filled; 1991 1992 { 1993 int i; 1994 int jt, jf; 1995 static const char ljerr[] = 1996 "%s for block-local relative jump: off=%d"; 1997 1998 #if 0 1999 printf("code=%x off=%d %x %x\n", src->s.code, 2000 off, src->s.jt, src->s.jf); 2001 #endif 2002 2003 if (!src->s.jt || !src->s.jf) { 2004 bpf_error(ljerr, "no jmp destination", off); 2005 /*NOTREACHED*/ 2006 } 2007 2008 jt = jf = 0; 2009 for (i = 0; i < slen; i++) { 2010 if (offset[i] == src->s.jt) { 2011 if (jt) { 2012 bpf_error(ljerr, "multiple matches", off); 2013 /*NOTREACHED*/ 2014 } 2015 2016 dst->jt = i - off - 1; 2017 jt++; 2018 } 2019 if (offset[i] == src->s.jf) { 2020 if (jf) { 2021 bpf_error(ljerr, "multiple matches", off); 2022 /*NOTREACHED*/ 2023 } 2024 dst->jf = i - off - 1; 2025 jf++; 2026 } 2027 } 2028 if (!jt || !jf) { 2029 bpf_error(ljerr, "no destination found", off); 2030 /*NOTREACHED*/ 2031 } 2032 } 2033 filled: 2034 ++dst; 2035 ++off; 2036 } 2037 free(offset); 2038 2039 #ifdef BDEBUG 2040 bids[dst - fstart] = p->id + 1; 2041 #endif 2042 dst->code = (u_short)p->s.code; 2043 dst->k = p->s.k; 2044 if (JT(p)) { 2045 extrajmps = 0; 2046 off = JT(p)->offset - (p->offset + slen) - 1; 2047 if (off >= 256) { 2048 /* offset too large for branch, must add a jump */ 2049 if (p->longjt == 0) { 2050 /* mark this instruction and retry */ 2051 p->longjt++; 2052 return(0); 2053 } 2054 /* branch if T to following jump */ 2055 dst->jt = extrajmps; 2056 extrajmps++; 2057 dst[extrajmps].code = BPF_JMP|BPF_JA; 2058 dst[extrajmps].k = off - extrajmps; 2059 } 2060 else 2061 dst->jt = off; 2062 off = JF(p)->offset - (p->offset + slen) - 1; 2063 if (off >= 256) { 2064 /* offset too large for branch, must add a jump */ 2065 if (p->longjf == 0) { 2066 /* mark this instruction and retry */ 2067 p->longjf++; 2068 return(0); 2069 } 2070 /* branch if F to following jump */ 2071 /* if two jumps are inserted, F goes to second one */ 2072 dst->jf = extrajmps; 2073 extrajmps++; 2074 dst[extrajmps].code = BPF_JMP|BPF_JA; 2075 dst[extrajmps].k = off - extrajmps; 2076 } 2077 else 2078 dst->jf = off; 2079 } 2080 return (1); 2081 } 2082 2083 2084 /* 2085 * Convert flowgraph intermediate representation to the 2086 * BPF array representation. Set *lenp to the number of instructions. 2087 */ 2088 struct bpf_insn * 2089 icode_to_fcode(root, lenp) 2090 struct block *root; 2091 int *lenp; 2092 { 2093 int n; 2094 struct bpf_insn *fp; 2095 2096 /* 2097 * Loop doing convert_codr_r() until no branches remain 2098 * with too-large offsets. 2099 */ 2100 while (1) { 2101 unMarkAll(); 2102 n = *lenp = count_stmts(root); 2103 2104 fp = calloc(n, sizeof(*fp)); 2105 if (fp == NULL) 2106 bpf_error("calloc"); 2107 2108 fstart = fp; 2109 ftail = fp + n; 2110 2111 unMarkAll(); 2112 if (convert_code_r(root)) 2113 break; 2114 free(fp); 2115 } 2116 2117 return fp; 2118 } 2119 2120 #ifdef BDEBUG 2121 static void 2122 opt_dump(root) 2123 struct block *root; 2124 { 2125 struct bpf_program f; 2126 2127 memset(bids, 0, sizeof bids); 2128 f.bf_insns = icode_to_fcode(root, &f.bf_len); 2129 bpf_dump(&f, 1); 2130 putchar('\n'); 2131 free((char *)f.bf_insns); 2132 } 2133 #endif 2134