Coverage Report

Created: 2026-07-16 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libpcap/optimize.c
Line
Count
Source
1
/*
2
 * Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994, 1995, 1996
3
 *  The Regents of the University of California.  All rights reserved.
4
 *
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
16
 * written permission.
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.
20
 *
21
 *  Optimization module for BPF code intermediate representation.
22
 */
23
24
#include <config.h>
25
26
#include <pcap-types.h>
27
28
#include <stdio.h>
29
#include <stdlib.h>
30
#include <memory.h>
31
#include <setjmp.h>
32
#include <string.h>
33
#include <limits.h> /* for SIZE_MAX */
34
#include <errno.h>
35
36
#include "pcap-int.h"
37
38
#include "gencode.h"
39
#include "optimize.h"
40
#include "diag-control.h"
41
42
#ifdef HAVE_OS_PROTO_H
43
#include "os-proto.h"
44
#endif
45
46
#ifdef BDEBUG
47
/*
48
 * The internal "debug printout" flag for the filter expression optimizer.
49
 * The code to print that stuff is present only if BDEBUG is defined, so
50
 * the flag, and the routine to set it, are defined only if BDEBUG is
51
 * defined.
52
 */
53
static int pcap_optimizer_debug;
54
55
/*
56
 * Routine to set that flag.
57
 *
58
 * This is intended for libpcap developers, not for general use.
59
 * If you want to set these in a program, you'll have to declare this
60
 * routine yourself, with the appropriate DLL import attribute on Windows;
61
 * it's not declared in any header file, and won't be declared in any
62
 * header file provided by libpcap.
63
 */
64
PCAP_API void pcap_set_optimizer_debug(int value);
65
66
PCAP_API_DEF void
67
pcap_set_optimizer_debug(int value)
68
{
69
  pcap_optimizer_debug = value;
70
}
71
72
/*
73
 * The internal "print dot graph" flag for the filter expression optimizer.
74
 * The code to print that stuff is present only if BDEBUG is defined, so
75
 * the flag, and the routine to set it, are defined only if BDEBUG is
76
 * defined.
77
 */
78
static int pcap_print_dot_graph;
79
80
/*
81
 * Routine to set that flag.
82
 *
83
 * This is intended for libpcap developers, not for general use.
84
 * If you want to set these in a program, you'll have to declare this
85
 * routine yourself, with the appropriate DLL import attribute on Windows;
86
 * it's not declared in any header file, and won't be declared in any
87
 * header file provided by libpcap.
88
 */
89
PCAP_API void pcap_set_print_dot_graph(int value);
90
91
PCAP_API_DEF void
92
pcap_set_print_dot_graph(int value)
93
{
94
  pcap_print_dot_graph = value;
95
}
96
97
#endif
98
99
/*
100
 * lowest_set_bit().
101
 *
102
 * Takes a 32-bit integer as an argument.
103
 *
104
 * If handed a non-zero value, returns the index of the lowest set bit,
105
 * counting upwards from zero.
106
 *
107
 * If handed zero, the results are platform- and compiler-dependent.
108
 * Keep it out of the light, don't give it any water, don't feed it
109
 * after midnight, and don't pass zero to it.
110
 *
111
 * This is the same as the count of trailing zeroes in the word.
112
 */
113
#if PCAP_IS_AT_LEAST_GNUC_VERSION(3,4)
114
  /*
115
   * GCC 3.4 and later; we have __builtin_ctz().
116
   */
117
2.87M
  #define lowest_set_bit(mask) ((u_int)__builtin_ctz(mask))
118
#elif defined(_MSC_VER)
119
  /*
120
   * Visual Studio; we support only 2015 and later, so use
121
   * _BitScanForward().
122
   */
123
#include <intrin.h>
124
125
#ifndef __clang__
126
#pragma intrinsic(_BitScanForward)
127
#endif
128
129
static __forceinline u_int
130
lowest_set_bit(int mask)
131
{
132
  unsigned long bit;
133
134
  /*
135
   * Don't sign-extend mask if long is longer than int.
136
   * (It's currently not, in MSVC, even on 64-bit platforms, but....)
137
   */
138
  if (_BitScanForward(&bit, (unsigned int)mask) == 0)
139
    abort();  /* mask is zero */
140
  return (u_int)bit;
141
}
142
#else
143
  /*
144
   * POSIX.1-2001 says ffs() is in <strings.h>.  Every supported non-Windows OS
145
   * (including Linux with musl libc and uclibc-ng) has the header and (except
146
   * HP-UX) declares the function there.  HP-UX declares the function in
147
   * <string.h>, which has already been included.
148
   */
149
  #include <strings.h>
150
  #define lowest_set_bit(mask)  ((u_int)(ffs((mask)) - 1))
151
#endif
152
153
/*
154
 * Represents a deleted instruction.
155
 */
156
43.8M
#define NOP -1
157
158
/*
159
 * Register numbers for use-def values.
160
 * 0 through BPF_MEMWORDS-1 represent the corresponding scratch memory
161
 * location.  A_ATOM is the accumulator and X_ATOM is the index
162
 * register.
163
 */
164
17.1M
#define A_ATOM BPF_MEMWORDS
165
3.42M
#define X_ATOM (BPF_MEMWORDS+1)
166
167
/*
168
 * This define is used to represent *both* the accumulator and
169
 * x register in use-def computations.
170
 * Currently, the use-def code assumes only one definition per instruction.
171
 */
172
4.65M
#define AX_ATOM N_ATOMS
173
174
/*
175
 * These data structures are used in a Cocke and Schwartz style
176
 * value numbering scheme.  Since the flowgraph is acyclic,
177
 * exit values can be propagated from a node's predecessors
178
 * provided it is uniquely defined.
179
 */
180
struct valnode {
181
  int code;
182
  bpf_u_int32 v0, v1;
183
  int val;    /* the value number */
184
  struct valnode *next;
185
};
186
187
/* Integer constants mapped with the load immediate opcode. */
188
1.10M
#define K(i) F(opt_state, BPF_LD|BPF_IMM|BPF_W, i, 0U)
189
190
struct vmapinfo {
191
  int is_const;
192
  bpf_u_int32 const_val;
193
};
194
195
typedef struct {
196
  /*
197
   * Place to longjmp to on an error.
198
   */
199
  jmp_buf top_ctx;
200
201
  /*
202
   * The buffer into which to put error message.
203
   */
204
  char *errbuf;
205
206
  /*
207
   * A flag to indicate that further optimization is needed.
208
   * Iterative passes are continued until a given pass yields no
209
   * code simplification or branch movement.
210
   */
211
  int done;
212
213
  /*
214
   * XXX - detect loops that do nothing but repeated AND/OR pullups
215
   * and edge moves.
216
   * If 100 passes in a row do nothing but that, treat that as a
217
   * sign that we're in a loop that just shuffles in a cycle in
218
   * which each pass just shuffles the code and we eventually
219
   * get back to the original configuration.
220
   *
221
   * XXX - we need a non-heuristic way of detecting, or preventing,
222
   * such a cycle.
223
   */
224
  int non_branch_movement_performed;
225
226
  u_int n_blocks;   /* number of blocks in the CFG; guaranteed to be > 0, as it's a RET instruction at a minimum */
227
  struct block **blocks;
228
  u_int n_edges;    /* twice n_blocks, so guaranteed to be > 0 */
229
  struct edge **edges;
230
231
  /*
232
   * A bit vector set representation of the dominators.
233
   * We round up the set size to the next power of two.
234
   */
235
  u_int nodewords;  /* number of 32-bit words for a bit vector of "number of nodes" bits; guaranteed to be > 0 */
236
  u_int edgewords;  /* number of 32-bit words for a bit vector of "number of edges" bits; guaranteed to be > 0 */
237
  struct block **levels;
238
  bpf_u_int32 *space;
239
240
11.3M
#define BITS_PER_WORD (8*sizeof(bpf_u_int32))
241
/*
242
 * True if a is in uset {p}
243
 */
244
861k
#define SET_MEMBER(p, a) \
245
861k
((p)[(unsigned)(a) / BITS_PER_WORD] & ((bpf_u_int32)1 << ((unsigned)(a) % BITS_PER_WORD)))
246
247
/*
248
 * Add 'a' to uset p.
249
 */
250
3.36M
#define SET_INSERT(p, a) \
251
3.36M
(p)[(unsigned)(a) / BITS_PER_WORD] |= ((bpf_u_int32)1 << ((unsigned)(a) % BITS_PER_WORD))
252
253
/*
254
 * Delete 'a' from uset p.
255
 */
256
#define SET_DELETE(p, a) \
257
(p)[(unsigned)(a) / BITS_PER_WORD] &= ~((bpf_u_int32)1 << ((unsigned)(a) % BITS_PER_WORD))
258
259
/*
260
 * a := a intersect b
261
 * n must be guaranteed to be > 0
262
 */
263
4.80M
#define SET_INTERSECT(a, b, n)\
264
4.80M
{\
265
4.80M
  bpf_u_int32 *_x = a, *_y = b;\
266
4.80M
  u_int _n = n;\
267
53.0M
  do *_x++ &= *_y++; while (--_n != 0);\
268
4.80M
}
269
270
/*
271
 * a := a - b
272
 * n must be guaranteed to be > 0
273
 */
274
#define SET_SUBTRACT(a, b, n)\
275
{\
276
  bpf_u_int32 *_x = a, *_y = b;\
277
  u_int _n = n;\
278
  do *_x++ &=~ *_y++; while (--_n != 0);\
279
}
280
281
/*
282
 * a := a union b
283
 * n must be guaranteed to be > 0
284
 */
285
1.25M
#define SET_UNION(a, b, n)\
286
1.25M
{\
287
1.25M
  bpf_u_int32 *_x = a, *_y = b;\
288
1.25M
  u_int _n = n;\
289
9.50M
  do *_x++ |= *_y++; while (--_n != 0);\
290
1.25M
}
291
292
  uset all_dom_sets;
293
  uset all_closure_sets;
294
  uset all_edge_sets;
295
296
2.40M
#define MODULUS 213
297
  struct valnode *hashtbl[MODULUS];
298
  bpf_u_int32 curval;
299
  bpf_u_int32 maxval;
300
301
  struct vmapinfo *vmap;
302
  struct valnode *vnode_base;
303
  struct valnode *next_vnode;
304
} opt_state_t;
305
306
typedef struct {
307
  /*
308
   * Place to longjmp to on an error.
309
   */
310
  jmp_buf top_ctx;
311
312
  /*
313
   * The buffer into which to put error message.
314
   */
315
  char *errbuf;
316
317
  /*
318
   * Some pointers used to convert the basic block form of the code,
319
   * into the array form that BPF requires.  'fstart' will point to
320
   * the malloc'd array while 'ftail' is used during the recursive
321
   * traversal.
322
   */
323
  struct bpf_insn *fstart;
324
  struct bpf_insn *ftail;
325
} conv_state_t;
326
327
static void opt_init(opt_state_t *, struct icode *);
328
static void opt_cleanup(opt_state_t *);
329
static void PCAP_NORETURN opt_error(opt_state_t *, const char *, ...)
330
    PCAP_PRINTFLIKE(2, 3);
331
static void PCAP_NORETURN conv_error(conv_state_t *, const char *, ...)
332
    PCAP_PRINTFLIKE(2, 3);
333
334
static void intern_blocks(opt_state_t *, struct icode *);
335
336
static void find_inedges(opt_state_t *, struct block *);
337
#ifdef BDEBUG
338
static void opt_dump(opt_state_t *, struct icode *);
339
#endif
340
341
static void
342
find_levels_r(opt_state_t *opt_state, struct icode *ic, struct block *b)
343
1.29M
{
344
1.29M
  int level;
345
346
1.29M
  if (isMarked(ic, b))
347
592k
    return;
348
349
705k
  Mark(ic, b);
350
705k
  b->link = 0;
351
352
705k
  if (JT(b)) {
353
626k
    find_levels_r(opt_state, ic, JT(b));
354
626k
    find_levels_r(opt_state, ic, JF(b));
355
626k
    level = max(JT(b)->level, JF(b)->level) + 1;
356
626k
  } else
357
78.8k
    level = 0;
358
705k
  b->level = level;
359
705k
  b->link = opt_state->levels[level];
360
705k
  opt_state->levels[level] = b;
361
705k
}
362
363
/*
364
 * Level graph.  The levels go from 0 at the leaves to
365
 * N_LEVELS at the root.  The opt_state->levels[] array points to the
366
 * first node of the level list, whose elements are linked
367
 * with the 'link' field of the struct block.
368
 */
369
static void
370
find_levels(opt_state_t *opt_state, struct icode *ic)
371
44.9k
{
372
44.9k
  memset((char *)opt_state->levels, 0, opt_state->n_blocks * sizeof(*opt_state->levels));
373
44.9k
  unMarkAll(ic);
374
44.9k
  find_levels_r(opt_state, ic, ic->root);
375
44.9k
}
376
377
/*
378
 * Find dominator relationships.
379
 * Assumes graph has been leveled.
380
 */
381
static void
382
find_dom(opt_state_t *opt_state, struct block *root)
383
57.0k
{
384
57.0k
  u_int i;
385
57.0k
  int level;
386
57.0k
  struct block *b;
387
57.0k
  bpf_u_int32 *x;
388
389
  /*
390
   * Initialize sets to contain all nodes.
391
   */
392
57.0k
  x = opt_state->all_dom_sets;
393
  /*
394
   * In opt_init(), we've made sure the product doesn't overflow.
395
   */
396
57.0k
  i = opt_state->n_blocks * opt_state->nodewords;
397
13.6M
  while (i != 0) {
398
13.5M
    --i;
399
13.5M
    *x++ = 0xFFFFFFFFU;
400
13.5M
  }
401
  /* Root starts off empty. */
402
158k
  for (i = opt_state->nodewords; i != 0;) {
403
101k
    --i;
404
101k
    root->dom[i] = 0;
405
101k
  }
406
407
  /* root->level is the highest level no found. */
408
833k
  for (level = root->level; level >= 0; --level) {
409
2.02M
    for (b = opt_state->levels[level]; b; b = b->link) {
410
1.25M
      SET_INSERT(b->dom, b->id);
411
1.25M
      if (JT(b) == 0)
412
103k
        continue;
413
1.14M
      SET_INTERSECT(JT(b)->dom, b->dom, opt_state->nodewords);
414
1.14M
      SET_INTERSECT(JF(b)->dom, b->dom, opt_state->nodewords);
415
1.14M
    }
416
776k
  }
417
57.0k
}
418
419
static void
420
propedom(opt_state_t *opt_state, struct edge *ep)
421
1.41M
{
422
1.41M
  SET_INSERT(ep->edom, ep->id);
423
1.41M
  if (ep->succ) {
424
1.25M
    SET_INTERSECT(ep->succ->et.edom, ep->edom, opt_state->edgewords);
425
1.25M
    SET_INTERSECT(ep->succ->ef.edom, ep->edom, opt_state->edgewords);
426
1.25M
  }
427
1.41M
}
428
429
/*
430
 * Compute edge dominators.
431
 * Assumes graph has been leveled and predecessors established.
432
 */
433
static void
434
find_edom(opt_state_t *opt_state, struct block *root)
435
44.9k
{
436
44.9k
  u_int i;
437
44.9k
  uset x;
438
44.9k
  int level;
439
44.9k
  struct block *b;
440
441
44.9k
  x = opt_state->all_edge_sets;
442
  /*
443
   * In opt_init(), we've made sure the product doesn't overflow.
444
   */
445
25.3M
  for (i = opt_state->n_edges * opt_state->edgewords; i != 0; ) {
446
25.3M
    --i;
447
25.3M
    x[i] = 0xFFFFFFFFU;
448
25.3M
  }
449
450
  /* root->level is the highest level no found. */
451
44.9k
  memset(root->et.edom, 0, opt_state->edgewords * sizeof(*(uset)0));
452
44.9k
  memset(root->ef.edom, 0, opt_state->edgewords * sizeof(*(uset)0));
453
556k
  for (level = root->level; level >= 0; --level) {
454
1.21M
    for (b = opt_state->levels[level]; b != 0; b = b->link) {
455
705k
      propedom(opt_state, &b->et);
456
705k
      propedom(opt_state, &b->ef);
457
705k
    }
458
511k
  }
459
44.9k
}
460
461
/*
462
 * Find the backwards transitive closure of the flow graph.  These sets
463
 * are backwards in the sense that we find the set of nodes that reach
464
 * a given node, not the set of nodes that can be reached by a node.
465
 *
466
 * Assumes graph has been leveled.
467
 */
468
static void
469
find_closure(opt_state_t *opt_state, struct block *root)
470
44.9k
{
471
44.9k
  int level;
472
44.9k
  struct block *b;
473
474
  /*
475
   * Initialize sets to contain no nodes.
476
   */
477
44.9k
  memset((char *)opt_state->all_closure_sets, 0,
478
44.9k
        opt_state->n_blocks * opt_state->nodewords * sizeof(*opt_state->all_closure_sets));
479
480
  /* root->level is the highest level no found. */
481
556k
  for (level = root->level; level >= 0; --level) {
482
1.21M
    for (b = opt_state->levels[level]; b; b = b->link) {
483
705k
      SET_INSERT(b->closure, b->id);
484
705k
      if (JT(b) == 0)
485
78.8k
        continue;
486
626k
      SET_UNION(JT(b)->closure, b->closure, opt_state->nodewords);
487
626k
      SET_UNION(JF(b)->closure, b->closure, opt_state->nodewords);
488
626k
    }
489
511k
  }
490
44.9k
}
491
492
/*
493
 * Return the register number that is used by s.
494
 *
495
 * Returns ATOM_A if A is used, ATOM_X if X is used, AX_ATOM if both A and X
496
 * are used, the scratch memory location's number if a scratch memory
497
 * location is used (e.g., 0 for M[0]), or -1 if none of those are used.
498
 *
499
 * The implementation should probably change to an array access.
500
 */
501
static int
502
atomuse(struct stmt *s)
503
7.54M
{
504
7.54M
  int c = s->code;
505
506
7.54M
  if (c == NOP)
507
2.01M
    return -1;
508
509
5.53M
  switch (BPF_CLASS(c)) {
510
511
43.6k
  case BPF_RET:
512
43.6k
    return (BPF_RVAL(c) == BPF_A) ? A_ATOM :
513
43.6k
      (BPF_RVAL(c) == BPF_X) ? X_ATOM : -1;
514
515
1.77M
  case BPF_LD:
516
2.20M
  case BPF_LDX:
517
    /*
518
     * As there are fewer than 2^31 memory locations,
519
     * s->k should be convertible to int without problems.
520
     */
521
2.20M
    return (BPF_MODE(c) == BPF_IND) ? X_ATOM :
522
2.20M
      (BPF_MODE(c) == BPF_MEM) ? (int)s->k : -1;
523
524
408k
  case BPF_ST:
525
408k
    return A_ATOM;
526
527
11.1k
  case BPF_STX:
528
11.1k
    return X_ATOM;
529
530
1.24M
  case BPF_JMP:
531
2.58M
  case BPF_ALU:
532
2.58M
    if (BPF_SRC(c) == BPF_X)
533
311k
      return AX_ATOM;
534
2.27M
    return A_ATOM;
535
536
273k
  case BPF_MISC:
537
273k
    return BPF_MISCOP(c) == BPF_TXA ? X_ATOM : A_ATOM;
538
5.53M
  }
539
0
  abort();
540
  /* NOTREACHED */
541
5.53M
}
542
543
/*
544
 * Return the register number that is defined by 's'.  We assume that
545
 * a single stmt cannot define more than one register.  If no register
546
 * is defined, return -1.
547
 *
548
 * The implementation should probably change to an array access.
549
 */
550
static int
551
atomdef(struct stmt *s)
552
6.92M
{
553
6.92M
  if (s->code == NOP)
554
2.01M
    return -1;
555
556
4.90M
  switch (BPF_CLASS(s->code)) {
557
558
1.77M
  case BPF_LD:
559
3.10M
  case BPF_ALU:
560
3.10M
    return A_ATOM;
561
562
434k
  case BPF_LDX:
563
434k
    return X_ATOM;
564
565
408k
  case BPF_ST:
566
419k
  case BPF_STX:
567
419k
    return s->k;
568
569
273k
  case BPF_MISC:
570
273k
    return BPF_MISCOP(s->code) == BPF_TAX ? X_ATOM : A_ATOM;
571
4.90M
  }
572
667k
  return -1;
573
4.90M
}
574
575
/*
576
 * Compute the sets of registers used, defined, and killed by 'b'.
577
 *
578
 * "Used" means that a statement in 'b' uses the register before any
579
 * statement in 'b' defines it, i.e. it uses the value left in
580
 * that register by a predecessor block of this block.
581
 * "Defined" means that a statement in 'b' defines it.
582
 * "Killed" means that a statement in 'b' defines it before any
583
 * statement in 'b' uses it, i.e. it kills the value left in that
584
 * register by a predecessor block of this block.
585
 */
586
static void
587
compute_local_ud(struct block *b)
588
705k
{
589
705k
  struct slist *s;
590
705k
  atomset def = 0, use = 0, killed = 0;
591
705k
  int atom;
592
593
4.81M
  for (s = b->stmts; s; s = s->next) {
594
4.11M
    if (s->s.code == NOP)
595
1.96M
      continue;
596
2.15M
    atom = atomuse(&s->s);
597
2.15M
    if (atom >= 0) {
598
1.57M
      if (atom == AX_ATOM) {
599
127k
        if (!ATOMELEM(def, X_ATOM))
600
4.53k
          use |= ATOMMASK(X_ATOM);
601
127k
        if (!ATOMELEM(def, A_ATOM))
602
231
          use |= ATOMMASK(A_ATOM);
603
127k
      }
604
1.44M
      else if (atom < N_ATOMS) {
605
1.44M
        if (!ATOMELEM(def, atom))
606
170k
          use |= ATOMMASK(atom);
607
1.44M
      }
608
0
      else
609
0
        abort();
610
1.57M
    }
611
2.15M
    atom = atomdef(&s->s);
612
2.15M
    if (atom >= 0) {
613
2.15M
      if (!ATOMELEM(use, atom))
614
2.10M
        killed |= ATOMMASK(atom);
615
2.15M
      def |= ATOMMASK(atom);
616
2.15M
    }
617
2.15M
  }
618
705k
  if (BPF_CLASS(b->s.code) == BPF_JMP) {
619
    /*
620
     * XXX - what about RET?
621
     */
622
626k
    atom = atomuse(&b->s);
623
626k
    if (atom >= 0) {
624
626k
      if (atom == AX_ATOM) {
625
35.6k
        if (!ATOMELEM(def, X_ATOM))
626
2.69k
          use |= ATOMMASK(X_ATOM);
627
35.6k
        if (!ATOMELEM(def, A_ATOM))
628
389
          use |= ATOMMASK(A_ATOM);
629
35.6k
      }
630
590k
      else if (atom < N_ATOMS) {
631
590k
        if (!ATOMELEM(def, atom))
632
27.9k
          use |= ATOMMASK(atom);
633
590k
      }
634
0
      else
635
0
        abort();
636
626k
    }
637
626k
  }
638
639
705k
  b->def = def;
640
705k
  b->kill = killed;
641
705k
  b->in_use = use;
642
705k
}
643
644
/*
645
 * Assume graph is already leveled.
646
 */
647
static void
648
find_ud(opt_state_t *opt_state, struct block *root)
649
44.9k
{
650
44.9k
  int i, maxlevel;
651
44.9k
  struct block *p;
652
653
  /*
654
   * root->level is the highest level no found;
655
   * count down from there.
656
   */
657
44.9k
  maxlevel = root->level;
658
556k
  for (i = maxlevel; i >= 0; --i)
659
1.21M
    for (p = opt_state->levels[i]; p; p = p->link) {
660
705k
      compute_local_ud(p);
661
705k
      p->out_use = 0;
662
705k
    }
663
664
511k
  for (i = 1; i <= maxlevel; ++i) {
665
1.09M
    for (p = opt_state->levels[i]; p; p = p->link) {
666
626k
      p->out_use |= JT(p)->in_use | JF(p)->in_use;
667
626k
      p->in_use |= p->out_use &~ p->kill;
668
626k
    }
669
466k
  }
670
44.9k
}
671
static void
672
init_val(opt_state_t *opt_state)
673
44.9k
{
674
44.9k
  opt_state->curval = 0;
675
44.9k
  opt_state->next_vnode = opt_state->vnode_base;
676
44.9k
  memset((char *)opt_state->vmap, 0, opt_state->maxval * sizeof(*opt_state->vmap));
677
44.9k
  memset((char *)opt_state->hashtbl, 0, sizeof opt_state->hashtbl);
678
44.9k
}
679
680
/*
681
 * Because we really don't have an IR, this stuff is a little messy.
682
 *
683
 * This routine looks in the table of existing value number for a value
684
 * with generated from an operation with the specified opcode and
685
 * the specified values.  If it finds it, it returns its value number,
686
 * otherwise it makes a new entry in the table and returns the
687
 * value number of that entry.
688
 */
689
static bpf_u_int32
690
F(opt_state_t *opt_state, int code, bpf_u_int32 v0, bpf_u_int32 v1)
691
2.40M
{
692
2.40M
  u_int hash;
693
2.40M
  bpf_u_int32 val;
694
2.40M
  struct valnode *p;
695
696
2.40M
  hash = (u_int)code ^ (v0 << 4) ^ (v1 << 8);
697
2.40M
  hash %= MODULUS;
698
699
2.69M
  for (p = opt_state->hashtbl[hash]; p; p = p->next)
700
1.72M
    if (p->code == code && p->v0 == v0 && p->v1 == v1)
701
1.43M
      return p->val;
702
703
  /*
704
   * Not found.  Allocate a new value, and assign it a new
705
   * value number.
706
   *
707
   * opt_state->curval starts out as 0, which means VAL_UNKNOWN; we
708
   * increment it before using it as the new value number, which
709
   * means we never assign VAL_UNKNOWN.
710
   *
711
   * XXX - unless we overflow, but we probably won't have 2^32-1
712
   * values; we treat 32 bits as effectively infinite.
713
   */
714
974k
  val = ++opt_state->curval;
715
974k
  if (BPF_MODE(code) == BPF_IMM &&
716
394k
      (BPF_CLASS(code) == BPF_LD || BPF_CLASS(code) == BPF_LDX)) {
717
330k
    opt_state->vmap[val].const_val = v0;
718
330k
    opt_state->vmap[val].is_const = 1;
719
330k
  }
720
974k
  p = opt_state->next_vnode++;
721
974k
  p->val = val;
722
974k
  p->code = code;
723
974k
  p->v0 = v0;
724
974k
  p->v1 = v1;
725
974k
  p->next = opt_state->hashtbl[hash];
726
974k
  opt_state->hashtbl[hash] = p;
727
728
974k
  return val;
729
2.40M
}
730
731
static inline void
732
vstore(struct stmt *s, bpf_u_int32 *valp, bpf_u_int32 newval, int alter)
733
1.50M
{
734
1.50M
  if (alter && newval != VAL_UNKNOWN && *valp == newval)
735
58.7k
    s->code = NOP;
736
1.44M
  else
737
1.44M
    *valp = newval;
738
1.50M
}
739
740
/*
741
 * Do constant-folding on binary operators.
742
 * (Unary operators are handled elsewhere.)
743
 */
744
static void
745
fold_op(opt_state_t *opt_state, struct stmt *s, bpf_u_int32 v0, bpf_u_int32 v1)
746
5.95k
{
747
5.95k
  bpf_u_int32 a, b;
748
749
5.95k
  a = opt_state->vmap[v0].const_val;
750
5.95k
  b = opt_state->vmap[v1].const_val;
751
752
5.95k
  switch (BPF_OP(s->code)) {
753
1.35k
  case BPF_ADD:
754
1.35k
    a += b;
755
1.35k
    break;
756
757
472
  case BPF_SUB:
758
472
    a -= b;
759
472
    break;
760
761
1.52k
  case BPF_MUL:
762
1.52k
    a *= b;
763
1.52k
    break;
764
765
825
  case BPF_DIV:
766
825
    if (b == 0)
767
3
      opt_error(opt_state, "division by zero");
768
822
    a /= b;
769
822
    break;
770
771
331
  case BPF_MOD:
772
331
    if (b == 0)
773
24
      opt_error(opt_state, "modulus by zero");
774
307
    a %= b;
775
307
    break;
776
777
453
  case BPF_AND:
778
453
    a &= b;
779
453
    break;
780
781
372
  case BPF_OR:
782
372
    a |= b;
783
372
    break;
784
785
187
  case BPF_XOR:
786
187
    a ^= b;
787
187
    break;
788
789
227
  case BPF_LSH:
790
    /*
791
     * A left shift of more than the width of the type
792
     * is undefined in C; we'll just treat it as shifting
793
     * all the bits out.
794
     *
795
     * XXX - the BPF interpreter doesn't check for this,
796
     * so its behavior is dependent on the behavior of
797
     * the processor on which it's running.  There are
798
     * processors on which it shifts all the bits out
799
     * and processors on which it does no shift.
800
     */
801
227
    if (b < 32)
802
160
      a <<= b;
803
67
    else
804
67
      a = 0;
805
227
    break;
806
807
211
  case BPF_RSH:
808
    /*
809
     * A right shift of more than the width of the type
810
     * is undefined in C; we'll just treat it as shifting
811
     * all the bits out.
812
     *
813
     * XXX - the BPF interpreter doesn't check for this,
814
     * so its behavior is dependent on the behavior of
815
     * the processor on which it's running.  There are
816
     * processors on which it shifts all the bits out
817
     * and processors on which it does no shift.
818
     */
819
211
    if (b < 32)
820
145
      a >>= b;
821
66
    else
822
66
      a = 0;
823
211
    break;
824
825
0
  default:
826
0
    abort();
827
5.95k
  }
828
5.93k
  s->k = a;
829
5.93k
  s->code = BPF_LD|BPF_IMM;
830
5.93k
  opt_state->done = 0;
831
  /*
832
   * XXX - optimizer loop detection.
833
   */
834
5.93k
  opt_state->non_branch_movement_performed = 1;
835
5.93k
}
836
837
static inline struct slist *
838
this_op(struct slist *s)
839
4.23M
{
840
6.26M
  while (s != 0 && s->s.code == NOP)
841
2.03M
    s = s->next;
842
4.23M
  return s;
843
4.23M
}
844
845
static void
846
opt_not(struct block *b)
847
613
{
848
613
  struct block *tmp = JT(b);
849
850
613
  JT(b) = JF(b);
851
613
  JF(b) = tmp;
852
613
}
853
854
static void
855
opt_peep(opt_state_t *opt_state, struct block *b)
856
667k
{
857
667k
  struct slist *s;
858
667k
  struct slist *next, *last;
859
667k
  bpf_u_int32 val;
860
861
667k
  s = b->stmts;
862
667k
  if (s == 0)
863
46.4k
    return;
864
865
620k
  last = s;
866
2.13M
  for (/*empty*/; /*empty*/; s = next) {
867
    /*
868
     * Skip over nops.
869
     */
870
2.13M
    s = this_op(s);
871
2.13M
    if (s == 0)
872
42.8k
      break;  /* nothing left in the block */
873
874
    /*
875
     * Find the next real instruction after that one
876
     * (skipping nops).
877
     */
878
2.08M
    next = this_op(s->next);
879
2.08M
    if (next == 0)
880
577k
      break;  /* no next instruction */
881
1.50M
    last = next;
882
883
    /*
884
     * st  M[k] --> st  M[k]
885
     * ldx M[k]   tax
886
     */
887
1.50M
    if (s->s.code == BPF_ST &&
888
201k
        next->s.code == (BPF_LDX|BPF_MEM) &&
889
19.1k
        s->s.k == next->s.k) {
890
16.7k
      opt_state->done = 0;
891
16.7k
      next->s.code = BPF_MISC|BPF_TAX;
892
      /*
893
       * XXX - optimizer loop detection.
894
       */
895
16.7k
      opt_state->non_branch_movement_performed = 1;
896
16.7k
    }
897
    /*
898
     * ld  #k --> ldx  #k
899
     * tax      txa
900
     */
901
1.50M
    if (s->s.code == (BPF_LD|BPF_IMM) &&
902
112k
        next->s.code == (BPF_MISC|BPF_TAX)) {
903
10.1k
      s->s.code = BPF_LDX|BPF_IMM;
904
10.1k
      next->s.code = BPF_MISC|BPF_TXA;
905
10.1k
      opt_state->done = 0;
906
      /*
907
       * XXX - optimizer loop detection.
908
       */
909
10.1k
      opt_state->non_branch_movement_performed = 1;
910
10.1k
    }
911
    /*
912
     * This is an ugly special case, but it happens
913
     * when you say tcp[k] or udp[k] where k is a constant.
914
     */
915
1.50M
    if (s->s.code == (BPF_LD|BPF_IMM)) {
916
102k
      struct slist *add, *tax, *ild;
917
918
      /*
919
       * Check that X isn't used on exit from this
920
       * block (which the optimizer might cause).
921
       * We know the code generator won't generate
922
       * any local dependencies.
923
       */
924
102k
      if (ATOMELEM(b->out_use, X_ATOM))
925
626
        continue;
926
927
      /*
928
       * Check that the instruction following the ldi
929
       * is an addx, or it's an ldxms with an addx
930
       * following it (with 0 or more nops between the
931
       * ldxms and addx).
932
       */
933
101k
      if (next->s.code != (BPF_LDX|BPF_MSH|BPF_B))
934
101k
        add = next;
935
542
      else
936
542
        add = this_op(next->next);
937
101k
      if (add == 0 || add->s.code != (BPF_ALU|BPF_ADD|BPF_X))
938
91.7k
        continue;
939
940
      /*
941
       * Check that a tax follows that (with 0 or more
942
       * nops between them).
943
       */
944
9.94k
      tax = this_op(add->next);
945
9.94k
      if (tax == 0 || tax->s.code != (BPF_MISC|BPF_TAX))
946
1.54k
        continue;
947
948
      /*
949
       * Check that an ild follows that (with 0 or more
950
       * nops between them).
951
       */
952
8.39k
      ild = this_op(tax->next);
953
8.39k
      if (ild == 0 || BPF_CLASS(ild->s.code) != BPF_LD ||
954
2.38k
          BPF_MODE(ild->s.code) != BPF_IND)
955
7.80k
        continue;
956
      /*
957
       * We want to turn this sequence:
958
       *
959
       * (004) ldi     #0x2   {s}
960
       * (005) ldxms   [14]   {next}  -- optional
961
       * (006) addx     {add}
962
       * (007) tax      {tax}
963
       * (008) ild     [x+0]    {ild}
964
       *
965
       * into this sequence:
966
       *
967
       * (004) nop
968
       * (005) ldxms   [14]
969
       * (006) nop
970
       * (007) nop
971
       * (008) ild     [x+2]
972
       *
973
       * XXX We need to check that X is not
974
       * subsequently used, because we want to change
975
       * what'll be in it after this sequence.
976
       *
977
       * We know we can eliminate the accumulator
978
       * modifications earlier in the sequence since
979
       * it is defined by the last stmt of this sequence
980
       * (i.e., the last statement of the sequence loads
981
       * a value into the accumulator, so we can eliminate
982
       * earlier operations on the accumulator).
983
       */
984
591
      ild->s.k += s->s.k;
985
591
      s->s.code = NOP;
986
591
      add->s.code = NOP;
987
591
      tax->s.code = NOP;
988
591
      opt_state->done = 0;
989
      /*
990
       * XXX - optimizer loop detection.
991
       */
992
591
      opt_state->non_branch_movement_performed = 1;
993
591
    }
994
1.50M
  }
995
  /*
996
   * If the comparison at the end of a block is an equality
997
   * comparison against a constant, and nobody uses the value
998
   * we leave in the A register at the end of a block, and
999
   * the operation preceding the comparison is an arithmetic
1000
   * operation, we can sometime optimize it away.
1001
   */
1002
620k
  if (b->s.code == (BPF_JMP|BPF_JEQ|BPF_K) &&
1003
542k
      !ATOMELEM(b->out_use, A_ATOM)) {
1004
    /*
1005
     * We can optimize away certain subtractions of the
1006
     * X register.
1007
     */
1008
514k
    if (last->s.code == (BPF_ALU|BPF_SUB|BPF_X)) {
1009
596
      val = b->val[X_ATOM];
1010
596
      if (opt_state->vmap[val].is_const) {
1011
        /*
1012
         * If we have a subtract to do a comparison,
1013
         * and the X register is a known constant,
1014
         * we can merge this value into the
1015
         * comparison:
1016
         *
1017
         * sub x  ->  nop
1018
         * jeq #y jeq #(x+y)
1019
         */
1020
0
        b->s.k += opt_state->vmap[val].const_val;
1021
0
        last->s.code = NOP;
1022
0
        opt_state->done = 0;
1023
        /*
1024
         * XXX - optimizer loop detection.
1025
         */
1026
0
        opt_state->non_branch_movement_performed = 1;
1027
596
      } else if (b->s.k == 0) {
1028
        /*
1029
         * If the X register isn't a constant,
1030
         * and the comparison in the test is
1031
         * against 0, we can compare with the
1032
         * X register, instead:
1033
         *
1034
         * sub x  ->  nop
1035
         * jeq #0 jeq x
1036
         */
1037
12
        last->s.code = NOP;
1038
12
        b->s.code = BPF_JMP|BPF_JEQ|BPF_X;
1039
12
        opt_state->done = 0;
1040
        /*
1041
         * XXX - optimizer loop detection.
1042
         */
1043
12
        opt_state->non_branch_movement_performed = 1;
1044
12
      }
1045
596
    }
1046
    /*
1047
     * Likewise, a constant subtract can be simplified:
1048
     *
1049
     * sub #x ->  nop
1050
     * jeq #y ->  jeq #(x+y)
1051
     */
1052
513k
    else if (last->s.code == (BPF_ALU|BPF_SUB|BPF_K)) {
1053
84
      last->s.code = NOP;
1054
84
      b->s.k += last->s.k;
1055
84
      opt_state->done = 0;
1056
      /*
1057
       * XXX - optimizer loop detection.
1058
       */
1059
84
      opt_state->non_branch_movement_performed = 1;
1060
84
    }
1061
    /*
1062
     * And, similarly, a constant AND can be simplified
1063
     * if we're testing against 0, i.e.:
1064
     *
1065
     * and #k nop
1066
     * jeq #0  -> jset #k
1067
     */
1068
513k
    else if (last->s.code == (BPF_ALU|BPF_AND|BPF_K) &&
1069
158k
        b->s.k == 0) {
1070
607
      b->s.k = last->s.k;
1071
607
      b->s.code = BPF_JMP|BPF_K|BPF_JSET;
1072
607
      last->s.code = NOP;
1073
607
      opt_state->done = 0;
1074
607
      opt_not(b);
1075
      /*
1076
       * XXX - optimizer loop detection.
1077
       */
1078
607
      opt_state->non_branch_movement_performed = 1;
1079
607
    }
1080
514k
  }
1081
  /*
1082
   * jset #0x0         ->  never
1083
   * jset #0xffffffff  ->  iff A != 0
1084
   */
1085
620k
  if (b->s.code == (BPF_JMP|BPF_K|BPF_JSET)) {
1086
    /*
1087
     * This can be, but not necessarily is a result of the folding
1088
     * into "jset #k" above.
1089
     */
1090
29.4k
    if (b->s.k == 0)
1091
308
      JT(b) = JF(b);
1092
29.1k
    else if (b->s.k == 0xffffffffU) {
1093
      /*
1094
       * For any A: "A has at least one bit set" means the
1095
       * same as "A != 0".  Test the latter condition, which
1096
       * executes slightly faster and is easier to read.
1097
       * This is not meant to be the inverse of the folding,
1098
       * hence do not prepend a [no-op] "and #0xffffffff".
1099
       */
1100
6
      b->s.code = BPF_JMP|BPF_JEQ|BPF_K;
1101
6
      b->s.k = 0;
1102
6
      opt_not(b);
1103
6
      opt_state->done = 0;
1104
      /*
1105
       * XXX - optimizer loop detection.
1106
       */
1107
6
      opt_state->non_branch_movement_performed = 1;
1108
6
    }
1109
29.4k
  }
1110
  /*
1111
   * If we're comparing against the index register, and the index
1112
   * register is a known constant, we can just compare against that
1113
   * constant.
1114
   */
1115
620k
  val = b->val[X_ATOM];
1116
620k
  if (opt_state->vmap[val].is_const && BPF_SRC(b->s.code) == BPF_X) {
1117
2.54k
    bpf_u_int32 v = opt_state->vmap[val].const_val;
1118
2.54k
    b->s.code &= ~BPF_X;
1119
2.54k
    b->s.k = v;
1120
2.54k
  }
1121
  /*
1122
   * If the accumulator is a known constant, we can compute the
1123
   * comparison result.
1124
   */
1125
620k
  val = b->val[A_ATOM];
1126
620k
  if (opt_state->vmap[val].is_const && BPF_SRC(b->s.code) == BPF_K) {
1127
20.7k
    bpf_u_int32 v = opt_state->vmap[val].const_val;
1128
20.7k
    switch (BPF_OP(b->s.code)) {
1129
1130
12.9k
    case BPF_JEQ:
1131
12.9k
      v = v == b->s.k;
1132
12.9k
      break;
1133
1134
3.38k
    case BPF_JGT:
1135
3.38k
      v = v > b->s.k;
1136
3.38k
      break;
1137
1138
3.98k
    case BPF_JGE:
1139
3.98k
      v = v >= b->s.k;
1140
3.98k
      break;
1141
1142
452
    case BPF_JSET:
1143
452
      v &= b->s.k;
1144
452
      break;
1145
1146
0
    default:
1147
0
      abort();
1148
20.7k
    }
1149
20.7k
    if (JF(b) != JT(b)) {
1150
3.13k
      opt_state->done = 0;
1151
      /*
1152
       * XXX - optimizer loop detection.
1153
       */
1154
3.13k
      opt_state->non_branch_movement_performed = 1;
1155
3.13k
    }
1156
20.7k
    if (v)
1157
13.6k
      JF(b) = JT(b);
1158
7.04k
    else
1159
7.04k
      JT(b) = JF(b);
1160
20.7k
  }
1161
620k
}
1162
1163
/*
1164
 * Compute the symbolic value of expression of 's', and update
1165
 * anything it defines in the value table 'val'.  If 'alter' is true,
1166
 * do various optimizations.  This code would be cleaner if symbolic
1167
 * evaluation and code transformations weren't folded together.
1168
 */
1169
static void
1170
opt_stmt(opt_state_t *opt_state, struct stmt *s, bpf_u_int32 val[], int alter)
1171
4.11M
{
1172
4.11M
  int op;
1173
4.11M
  bpf_u_int32 v;
1174
1175
4.11M
  switch (s->code) {
1176
1177
177k
  case BPF_LD|BPF_ABS|BPF_W:
1178
261k
  case BPF_LD|BPF_ABS|BPF_H:
1179
375k
  case BPF_LD|BPF_ABS|BPF_B:
1180
375k
    v = F(opt_state, s->code, s->k, 0L);
1181
375k
    vstore(s, &val[A_ATOM], v, alter);
1182
375k
    break;
1183
1184
39.4k
  case BPF_LD|BPF_IND|BPF_W:
1185
118k
  case BPF_LD|BPF_IND|BPF_H:
1186
215k
  case BPF_LD|BPF_IND|BPF_B:
1187
215k
    v = val[X_ATOM];
1188
215k
    if (alter && opt_state->vmap[v].is_const) {
1189
3.95k
      s->code = BPF_LD|BPF_ABS|BPF_SIZE(s->code);
1190
3.95k
      s->k += opt_state->vmap[v].const_val;
1191
3.95k
      v = F(opt_state, s->code, s->k, 0L);
1192
3.95k
      opt_state->done = 0;
1193
      /*
1194
       * XXX - optimizer loop detection.
1195
       */
1196
3.95k
      opt_state->non_branch_movement_performed = 1;
1197
3.95k
    }
1198
211k
    else
1199
211k
      v = F(opt_state, s->code, s->k, v);
1200
215k
    vstore(s, &val[A_ATOM], v, alter);
1201
215k
    break;
1202
1203
22.5k
  case BPF_LD|BPF_LEN:
1204
22.5k
    v = F(opt_state, s->code, 0L, 0L);
1205
22.5k
    vstore(s, &val[A_ATOM], v, alter);
1206
22.5k
    break;
1207
1208
116k
  case BPF_LD|BPF_IMM:
1209
116k
    v = K(s->k);
1210
116k
    vstore(s, &val[A_ATOM], v, alter);
1211
116k
    break;
1212
1213
31.8k
  case BPF_LDX|BPF_IMM:
1214
31.8k
    v = K(s->k);
1215
31.8k
    vstore(s, &val[X_ATOM], v, alter);
1216
31.8k
    break;
1217
1218
28.4k
  case BPF_LDX|BPF_MSH|BPF_B:
1219
28.4k
    v = F(opt_state, s->code, s->k, 0L);
1220
28.4k
    vstore(s, &val[X_ATOM], v, alter);
1221
28.4k
    break;
1222
1223
283k
  case BPF_ALU|BPF_NEG:
1224
283k
    if (alter && opt_state->vmap[val[A_ATOM]].is_const) {
1225
5.48k
      s->code = BPF_LD|BPF_IMM;
1226
      /*
1227
       * Do this negation as unsigned arithmetic; that's
1228
       * what modern BPF engines do, and it guarantees
1229
       * that all possible values can be negated.  (Yeah,
1230
       * negating 0x80000000, the minimum signed 32-bit
1231
       * two's-complement value, results in 0x80000000,
1232
       * so it's still negative, but we *should* be doing
1233
       * all unsigned arithmetic here, to match what
1234
       * modern BPF engines do.)
1235
       *
1236
       * Express it as 0U - (unsigned value) so that we
1237
       * don't get compiler warnings about negating an
1238
       * unsigned value and don't get UBSan warnings
1239
       * about the result of negating 0x80000000 being
1240
       * undefined.
1241
       */
1242
5.48k
      s->k = 0U - opt_state->vmap[val[A_ATOM]].const_val;
1243
5.48k
      val[A_ATOM] = K(s->k);
1244
5.48k
    }
1245
278k
    else
1246
278k
      val[A_ATOM] = F(opt_state, s->code, val[A_ATOM], 0L);
1247
283k
    break;
1248
1249
28.0k
  case BPF_ALU|BPF_ADD|BPF_K:
1250
30.9k
  case BPF_ALU|BPF_SUB|BPF_K:
1251
34.6k
  case BPF_ALU|BPF_MUL|BPF_K:
1252
36.0k
  case BPF_ALU|BPF_DIV|BPF_K:
1253
37.1k
  case BPF_ALU|BPF_MOD|BPF_K:
1254
231k
  case BPF_ALU|BPF_AND|BPF_K:
1255
232k
  case BPF_ALU|BPF_OR|BPF_K:
1256
232k
  case BPF_ALU|BPF_XOR|BPF_K:
1257
264k
  case BPF_ALU|BPF_LSH|BPF_K:
1258
265k
  case BPF_ALU|BPF_RSH|BPF_K:
1259
265k
    op = BPF_OP(s->code);
1260
265k
    if (alter) {
1261
79.1k
      if (s->k == 0) {
1262
        /*
1263
         * Optimize operations where the constant
1264
         * is zero.
1265
         *
1266
         * Don't optimize away "sub #0"
1267
         * as it may be needed later to
1268
         * fixup the generated math code.
1269
         *
1270
         * Fail if we're dividing by zero or taking
1271
         * a modulus by zero.
1272
         */
1273
2.47k
        if (op == BPF_ADD ||
1274
2.29k
            op == BPF_LSH || op == BPF_RSH ||
1275
2.19k
            op == BPF_OR || op == BPF_XOR) {
1276
416
          s->code = NOP;
1277
416
          break;
1278
416
        }
1279
2.06k
        if (op == BPF_MUL || op == BPF_AND) {
1280
788
          s->code = BPF_LD|BPF_IMM;
1281
788
          val[A_ATOM] = K(s->k);
1282
788
          break;
1283
788
        }
1284
1.27k
        if (op == BPF_DIV)
1285
1
          opt_error(opt_state,
1286
1
              "division by zero");
1287
1.27k
        if (op == BPF_MOD)
1288
24
          opt_error(opt_state,
1289
24
              "modulus by zero");
1290
1.27k
      }
1291
77.9k
      if (opt_state->vmap[val[A_ATOM]].is_const) {
1292
1.29k
        fold_op(opt_state, s, val[A_ATOM], K(s->k));
1293
1.29k
        val[A_ATOM] = K(s->k);
1294
1.29k
        break;
1295
1.29k
      }
1296
77.9k
    }
1297
262k
    val[A_ATOM] = F(opt_state, s->code, val[A_ATOM], K(s->k));
1298
262k
    break;
1299
1300
53.7k
  case BPF_ALU|BPF_ADD|BPF_X:
1301
62.8k
  case BPF_ALU|BPF_SUB|BPF_X:
1302
81.0k
  case BPF_ALU|BPF_MUL|BPF_X:
1303
89.4k
  case BPF_ALU|BPF_DIV|BPF_X:
1304
96.6k
  case BPF_ALU|BPF_MOD|BPF_X:
1305
107k
  case BPF_ALU|BPF_AND|BPF_X:
1306
114k
  case BPF_ALU|BPF_OR|BPF_X:
1307
120k
  case BPF_ALU|BPF_XOR|BPF_X:
1308
124k
  case BPF_ALU|BPF_LSH|BPF_X:
1309
127k
  case BPF_ALU|BPF_RSH|BPF_X:
1310
127k
    op = BPF_OP(s->code);
1311
127k
    if (alter && opt_state->vmap[val[X_ATOM]].is_const) {
1312
9.96k
      if (opt_state->vmap[val[A_ATOM]].is_const) {
1313
4.66k
        fold_op(opt_state, s, val[A_ATOM], val[X_ATOM]);
1314
4.66k
        val[A_ATOM] = K(s->k);
1315
4.66k
      }
1316
5.29k
      else {
1317
5.29k
        s->code = BPF_ALU|BPF_K|op;
1318
5.29k
        s->k = opt_state->vmap[val[X_ATOM]].const_val;
1319
5.29k
        if ((op == BPF_LSH || op == BPF_RSH) &&
1320
378
            s->k > 31)
1321
40
          opt_error(opt_state,
1322
40
              "shift by more than 31 bits");
1323
5.25k
        opt_state->done = 0;
1324
5.25k
        val[A_ATOM] =
1325
5.25k
          F(opt_state, s->code, val[A_ATOM], K(s->k));
1326
        /*
1327
         * XXX - optimizer loop detection.
1328
         */
1329
5.25k
        opt_state->non_branch_movement_performed = 1;
1330
5.25k
      }
1331
9.92k
      break;
1332
9.96k
    }
1333
    /*
1334
     * Check if we're doing something to an accumulator
1335
     * that is 0, and simplify.  This may not seem like
1336
     * much of a simplification but it could open up further
1337
     * optimizations.
1338
     * XXX We could also check for mul by 1, etc.
1339
     */
1340
117k
    if (alter && opt_state->vmap[val[A_ATOM]].is_const
1341
20.7k
        && opt_state->vmap[val[A_ATOM]].const_val == 0) {
1342
2.05k
      if (op == BPF_ADD || op == BPF_OR || op == BPF_XOR) {
1343
481
        s->code = BPF_MISC|BPF_TXA;
1344
481
        vstore(s, &val[A_ATOM], val[X_ATOM], alter);
1345
481
        break;
1346
481
      }
1347
1.57k
      else if (op == BPF_MUL || op == BPF_DIV || op == BPF_MOD ||
1348
1.24k
         op == BPF_AND || op == BPF_LSH || op == BPF_RSH) {
1349
648
        s->code = BPF_LD|BPF_IMM;
1350
648
        s->k = 0;
1351
648
        vstore(s, &val[A_ATOM], K(s->k), alter);
1352
648
        break;
1353
648
      }
1354
929
      else if (op == BPF_NEG) {
1355
0
        s->code = NOP;
1356
0
        break;
1357
0
      }
1358
2.05k
    }
1359
116k
    val[A_ATOM] = F(opt_state, s->code, val[A_ATOM], val[X_ATOM]);
1360
116k
    break;
1361
1362
12.2k
  case BPF_MISC|BPF_TXA:
1363
12.2k
    vstore(s, &val[A_ATOM], val[X_ATOM], alter);
1364
12.2k
    break;
1365
1366
178k
  case BPF_LD|BPF_MEM:
1367
178k
    v = val[s->k];
1368
178k
    if (alter && opt_state->vmap[v].is_const) {
1369
16.0k
      s->code = BPF_LD|BPF_IMM;
1370
16.0k
      s->k = opt_state->vmap[v].const_val;
1371
16.0k
      opt_state->done = 0;
1372
      /*
1373
       * XXX - optimizer loop detection.
1374
       */
1375
16.0k
      opt_state->non_branch_movement_performed = 1;
1376
16.0k
    }
1377
178k
    vstore(s, &val[A_ATOM], v, alter);
1378
178k
    break;
1379
1380
117k
  case BPF_MISC|BPF_TAX:
1381
117k
    vstore(s, &val[X_ATOM], val[A_ATOM], alter);
1382
117k
    break;
1383
1384
164k
  case BPF_LDX|BPF_MEM:
1385
164k
    v = val[s->k];
1386
164k
    if (alter && opt_state->vmap[v].is_const) {
1387
3.73k
      s->code = BPF_LDX|BPF_IMM;
1388
3.73k
      s->k = opt_state->vmap[v].const_val;
1389
3.73k
      opt_state->done = 0;
1390
      /*
1391
       * XXX - optimizer loop detection.
1392
       */
1393
3.73k
      opt_state->non_branch_movement_performed = 1;
1394
3.73k
    }
1395
164k
    vstore(s, &val[X_ATOM], v, alter);
1396
164k
    break;
1397
1398
205k
  case BPF_ST:
1399
205k
    vstore(s, &val[s->k], val[A_ATOM], alter);
1400
205k
    break;
1401
1402
5.58k
  case BPF_STX:
1403
5.58k
    vstore(s, &val[s->k], val[X_ATOM], alter);
1404
5.58k
    break;
1405
4.11M
  }
1406
4.11M
}
1407
1408
static void
1409
deadstmt(opt_state_t *opt_state, struct stmt *s, struct stmt *last[])
1410
4.77M
{
1411
4.77M
  int atom;
1412
1413
4.77M
  atom = atomuse(s);
1414
4.77M
  if (atom >= 0) {
1415
2.13M
    if (atom == AX_ATOM) {
1416
148k
      last[X_ATOM] = 0;
1417
148k
      last[A_ATOM] = 0;
1418
148k
    }
1419
1.98M
    else
1420
1.98M
      last[atom] = 0;
1421
2.13M
  }
1422
4.77M
  atom = atomdef(s);
1423
4.77M
  if (atom >= 0) {
1424
2.08M
    if (last[atom]) {
1425
72.7k
      opt_state->done = 0;
1426
72.7k
      last[atom]->code = NOP;
1427
      /*
1428
       * XXX - optimizer loop detection.
1429
       */
1430
72.7k
      opt_state->non_branch_movement_performed = 1;
1431
72.7k
    }
1432
2.08M
    last[atom] = s;
1433
2.08M
  }
1434
4.77M
}
1435
1436
static void
1437
opt_deadstores(opt_state_t *opt_state, struct block *b)
1438
667k
{
1439
667k
  struct slist *s;
1440
667k
  int atom;
1441
667k
  struct stmt *last[N_ATOMS];
1442
1443
667k
  memset((char *)last, 0, sizeof last);
1444
1445
4.77M
  for (s = b->stmts; s != 0; s = s->next)
1446
4.10M
    deadstmt(opt_state, &s->s, last);
1447
667k
  deadstmt(opt_state, &b->s, last);
1448
1449
12.6M
  for (atom = 0; atom < N_ATOMS; ++atom)
1450
12.0M
    if (last[atom] && !ATOMELEM(b->out_use, atom)) {
1451
26.2k
      last[atom]->code = NOP;
1452
      /*
1453
       * The store was removed as it's dead,
1454
       * so the value stored into now has
1455
       * an unknown value.
1456
       */
1457
26.2k
      vstore(0, &b->val[atom], VAL_UNKNOWN, 0);
1458
26.2k
      opt_state->done = 0;
1459
      /*
1460
       * XXX - optimizer loop detection.
1461
       */
1462
26.2k
      opt_state->non_branch_movement_performed = 1;
1463
26.2k
    }
1464
667k
}
1465
1466
static void
1467
opt_blk(opt_state_t *opt_state, struct block *b, int do_stmts)
1468
705k
{
1469
705k
  struct slist *s;
1470
705k
  struct edge *p;
1471
705k
  int i;
1472
705k
  bpf_u_int32 aval, xval;
1473
1474
#if 0
1475
  for (s = b->stmts; s && s->next; s = s->next)
1476
    if (BPF_CLASS(s->s.code) == BPF_JMP) {
1477
      do_stmts = 0;
1478
      break;
1479
    }
1480
#endif
1481
1482
  /*
1483
   * Initialize the atom values.
1484
   */
1485
705k
  p = b->in_edges;
1486
705k
  if (p == 0) {
1487
    /*
1488
     * We have no predecessors, so everything is undefined
1489
     * upon entry to this block.
1490
     */
1491
44.9k
    memset((char *)b->val, 0, sizeof(b->val));
1492
660k
  } else {
1493
    /*
1494
     * Inherit values from our predecessors.
1495
     *
1496
     * First, get the values from the predecessor along the
1497
     * first edge leading to this node.
1498
     */
1499
660k
    memcpy((char *)b->val, (char *)p->pred->val, sizeof(b->val));
1500
    /*
1501
     * Now look at all the other nodes leading to this node.
1502
     * If, for the predecessor along that edge, a register
1503
     * has a different value from the one we have (i.e.,
1504
     * control paths are merging, and the merging paths
1505
     * assign different values to that register), give the
1506
     * register the undefined value of 0.
1507
     */
1508
1.25M
    while ((p = p->next) != NULL) {
1509
11.2M
      for (i = 0; i < N_ATOMS; ++i)
1510
10.6M
        if (b->val[i] != p->pred->val[i])
1511
652k
          b->val[i] = 0;
1512
592k
    }
1513
660k
  }
1514
705k
  aval = b->val[A_ATOM];
1515
705k
  xval = b->val[X_ATOM];
1516
4.81M
  for (s = b->stmts; s; s = s->next)
1517
4.11M
    opt_stmt(opt_state, &s->s, b->val, do_stmts);
1518
1519
  /*
1520
   * This is a special case: if we don't use anything from this
1521
   * block, and we load the accumulator or index register with a
1522
   * value that is already there, or if this block is a return,
1523
   * eliminate all the statements.
1524
   *
1525
   * XXX - what if it does a store?  Presumably that falls under
1526
   * the heading of "if we don't use anything from this block",
1527
   * i.e., if we use any memory location set to a different
1528
   * value by this block, then we use something from this block.
1529
   *
1530
   * XXX - why does it matter whether we use anything from this
1531
   * block?  If the accumulator or index register doesn't change
1532
   * its value, isn't that OK even if we use that value?
1533
   *
1534
   * XXX - if we load the accumulator with a different value,
1535
   * and the block ends with a conditional branch, we obviously
1536
   * can't eliminate it, as the branch depends on that value.
1537
   * For the index register, the conditional branch only depends
1538
   * on the index register value if the test is against the index
1539
   * register value rather than a constant; if nothing uses the
1540
   * value we put into the index register, and we're not testing
1541
   * against the index register's value, and there aren't any
1542
   * other problems that would keep us from eliminating this
1543
   * block, can we eliminate it?
1544
   */
1545
705k
  if (do_stmts &&
1546
237k
      ((b->out_use == 0 &&
1547
137k
        aval != VAL_UNKNOWN && b->val[A_ATOM] == aval &&
1548
51.8k
        xval != VAL_UNKNOWN && b->val[X_ATOM] == xval) ||
1549
219k
       BPF_CLASS(b->s.code) == BPF_RET)) {
1550
37.8k
    if (b->stmts != 0) {
1551
1.76k
      b->stmts = 0;
1552
1.76k
      opt_state->done = 0;
1553
      /*
1554
       * XXX - optimizer loop detection.
1555
       */
1556
1.76k
      opt_state->non_branch_movement_performed = 1;
1557
1.76k
    }
1558
667k
  } else {
1559
667k
    opt_peep(opt_state, b);
1560
667k
    opt_deadstores(opt_state, b);
1561
667k
  }
1562
  /*
1563
   * Set up values for branch optimizer.
1564
   */
1565
705k
  if (BPF_SRC(b->s.code) == BPF_K)
1566
671k
    b->oval = K(b->s.k);
1567
33.1k
  else
1568
33.1k
    b->oval = b->val[X_ATOM];
1569
705k
  b->et.code = b->s.code;
1570
705k
  b->ef.code = -b->s.code;
1571
705k
}
1572
1573
/*
1574
 * Return true if any register that is used on exit from 'succ', has
1575
 * an exit value that is different from the corresponding exit value
1576
 * from 'b'.
1577
 */
1578
static int
1579
use_conflict(struct block *b, struct block *succ)
1580
231k
{
1581
231k
  int atom;
1582
231k
  atomset use = succ->out_use;
1583
1584
231k
  if (use == 0)
1585
195k
    return 0;
1586
1587
496k
  for (atom = 0; atom < N_ATOMS; ++atom)
1588
473k
    if (ATOMELEM(use, atom))
1589
49.4k
      if (b->val[atom] != succ->val[atom])
1590
13.4k
        return 1;
1591
22.8k
  return 0;
1592
36.3k
}
1593
1594
/*
1595
 * Given a block that is the successor of an edge, and an edge that
1596
 * dominates that edge, return either a pointer to a child of that
1597
 * block (a block to which that block jumps) if that block is a
1598
 * candidate to replace the successor of the latter edge or NULL
1599
 * if neither of the children of the first block are candidates.
1600
 */
1601
static struct block *
1602
fold_edge(struct block *child, struct edge *ep)
1603
2.87M
{
1604
2.87M
  int sense;
1605
2.87M
  bpf_u_int32 aval0, aval1, oval0, oval1;
1606
2.87M
  int code = ep->code;
1607
1608
2.87M
  if (code < 0) {
1609
    /*
1610
     * This edge is a "branch if false" edge.
1611
     */
1612
1.70M
    code = -code;
1613
1.70M
    sense = 0;
1614
1.70M
  } else {
1615
    /*
1616
     * This edge is a "branch if true" edge.
1617
     */
1618
1.17M
    sense = 1;
1619
1.17M
  }
1620
1621
  /*
1622
   * If the opcode for the branch at the end of the block we
1623
   * were handed isn't the same as the opcode for the branch
1624
   * to which the edge we were handed corresponds, the tests
1625
   * for those branches aren't testing the same conditions,
1626
   * so the blocks to which the first block branches aren't
1627
   * candidates to replace the successor of the edge.
1628
   */
1629
2.87M
  if (child->s.code != code)
1630
557k
    return 0;
1631
1632
2.32M
  aval0 = child->val[A_ATOM];
1633
2.32M
  oval0 = child->oval;
1634
2.32M
  aval1 = ep->pred->val[A_ATOM];
1635
2.32M
  oval1 = ep->pred->oval;
1636
1637
  /*
1638
   * If the A register value on exit from the successor block
1639
   * isn't the same as the A register value on exit from the
1640
   * predecessor of the edge, the blocks to which the first
1641
   * block branches aren't candidates to replace the successor
1642
   * of the edge.
1643
   */
1644
2.32M
  if (aval0 != aval1)
1645
1.67M
    return 0;
1646
1647
646k
  if (oval0 == oval1)
1648
    /*
1649
     * The operands of the branch instructions are
1650
     * identical, so the branches are testing the
1651
     * same condition, and the result is true if a true
1652
     * branch was taken to get here, otherwise false.
1653
     */
1654
128k
    return sense ? JT(child) : JF(child);
1655
1656
517k
  if (sense && code == (BPF_JMP|BPF_JEQ|BPF_K))
1657
    /*
1658
     * At this point, we only know the comparison if we
1659
     * came down the true branch, and it was an equality
1660
     * comparison with a constant.
1661
     *
1662
     * I.e., if we came down the true branch, and the branch
1663
     * was an equality comparison with a constant, we know the
1664
     * accumulator contains that constant.  If we came down
1665
     * the false branch, or the comparison wasn't with a
1666
     * constant, we don't know what was in the accumulator.
1667
     *
1668
     * We rely on the fact that distinct constants have distinct
1669
     * value numbers.
1670
     */
1671
88.9k
    return JF(child);
1672
1673
428k
  return 0;
1674
517k
}
1675
1676
/*
1677
 * If we can make this edge go directly to a child of the edge's current
1678
 * successor, do so.
1679
 */
1680
static void
1681
opt_j(opt_state_t *opt_state, struct edge *ep)
1682
847k
{
1683
847k
  u_int i, k;
1684
847k
  struct block *target;
1685
1686
  /*
1687
   * Does this edge go to a block where, if the test
1688
   * at the end of it succeeds, it goes to a block
1689
   * that's a leaf node of the DAG, i.e. a return
1690
   * statement?
1691
   * If so, there's nothing to optimize.
1692
   */
1693
847k
  if (JT(ep->succ) == 0)
1694
212k
    return;
1695
1696
  /*
1697
   * Does this edge go to a block that goes, in turn, to
1698
   * the same block regardless of whether the test at the
1699
   * end succeeds or fails?
1700
   */
1701
634k
  if (JT(ep->succ) == JF(ep->succ)) {
1702
    /*
1703
     * Common branch targets can be eliminated, provided
1704
     * there is no data dependency.
1705
     *
1706
     * Check whether any register used on exit from the
1707
     * block to which the successor of this edge goes
1708
     * has a value at that point that's different from
1709
     * the value it has on exit from the predecessor of
1710
     * this edge.  If not, the predecessor of this edge
1711
     * can just go to the block to which the successor
1712
     * of this edge goes, bypassing the successor of this
1713
     * edge, as the successor of this edge isn't doing
1714
     * any calculations whose results are different
1715
     * from what the blocks before it did and isn't
1716
     * doing any tests the results of which matter.
1717
     */
1718
14.2k
    if (!use_conflict(ep->pred, JT(ep->succ))) {
1719
      /*
1720
       * No, there isn't.
1721
       * Make this edge go to the block to
1722
       * which the successor of that edge
1723
       * goes.
1724
       */
1725
7.64k
      opt_state->done = 0;
1726
7.64k
      ep->succ = JT(ep->succ);
1727
      /*
1728
       * XXX - optimizer loop detection.
1729
       */
1730
7.64k
      opt_state->non_branch_movement_performed = 1;
1731
7.64k
    }
1732
14.2k
  }
1733
  /*
1734
   * For each edge dominator that matches the successor of this
1735
   * edge, promote the edge successor to the its grandchild.
1736
   *
1737
   * XXX We violate the set abstraction here in favor a reasonably
1738
   * efficient loop.
1739
   */
1740
804k
 top:
1741
12.0M
  for (i = 0; i < opt_state->edgewords; ++i) {
1742
    /* i'th word in the bitset of dominators */
1743
11.4M
    bpf_u_int32 x = ep->edom[i];
1744
1745
14.1M
    while (x != 0) {
1746
      /* Find the next dominator in that word and mark it as found */
1747
2.87M
      k = lowest_set_bit(x);
1748
2.87M
      x &=~ ((bpf_u_int32)1 << k);
1749
2.87M
      k += i * BITS_PER_WORD;
1750
1751
2.87M
      target = fold_edge(ep->succ, opt_state->edges[k]);
1752
      /*
1753
       * We have a candidate to replace the successor
1754
       * of ep.
1755
       *
1756
       * Check that there is no data dependency between
1757
       * nodes that will be violated if we move the edge;
1758
       * i.e., if any register used on exit from the
1759
       * candidate has a value at that point different
1760
       * from the value it has when we exit the
1761
       * predecessor of that edge, there's a data
1762
       * dependency that will be violated.
1763
       */
1764
2.87M
      if (target != 0 && !use_conflict(ep->pred, target)) {
1765
        /*
1766
         * It's safe to replace the successor of
1767
         * ep; do so, and note that we've made
1768
         * at least one change.
1769
         *
1770
         * XXX - this is one of the operations that
1771
         * happens when the optimizer gets into
1772
         * one of those infinite loops.
1773
         */
1774
210k
        opt_state->done = 0;
1775
210k
        ep->succ = target;
1776
210k
        if (JT(target) != 0)
1777
          /*
1778
           * Start over unless we hit a leaf.
1779
           */
1780
169k
          goto top;
1781
41.3k
        return;
1782
210k
      }
1783
2.87M
    }
1784
11.4M
  }
1785
804k
}
1786
1787
/*
1788
 * XXX - is this, and and_pullup(), what's described in section 6.1.2
1789
 * "Predicate Assertion Propagation" in the BPF+ paper?
1790
 *
1791
 * Note that this looks at block dominators, not edge dominators.
1792
 * Don't think so.
1793
 *
1794
 * "A or B" compiles into
1795
 *
1796
 *          A
1797
 *       t / \ f
1798
 *        /   B
1799
 *       / t / \ f
1800
 *      \   /
1801
 *       \ /
1802
 *        X
1803
 *
1804
 *
1805
 */
1806
static void
1807
or_pullup(opt_state_t *opt_state, struct block *b, struct block *root)
1808
423k
{
1809
423k
  bpf_u_int32 val;
1810
423k
  int at_top;
1811
423k
  struct block *pull;
1812
423k
  struct block **diffp, **samep;
1813
423k
  struct edge *ep;
1814
1815
423k
  ep = b->in_edges;
1816
423k
  if (ep == 0)
1817
47.2k
    return;
1818
1819
  /*
1820
   * Make sure each predecessor loads the same value.
1821
   * XXX why?
1822
   */
1823
376k
  val = ep->pred->val[A_ATOM];
1824
465k
  for (ep = ep->next; ep != 0; ep = ep->next)
1825
150k
    if (val != ep->pred->val[A_ATOM])
1826
61.3k
      return;
1827
1828
  /*
1829
   * For the first edge in the list of edges coming into this block,
1830
   * see whether the predecessor of that edge comes here via a true
1831
   * branch or a false branch.
1832
   */
1833
315k
  if (JT(b->in_edges->pred) == b)
1834
126k
    diffp = &JT(b->in_edges->pred); /* jt */
1835
188k
  else
1836
188k
    diffp = &JF(b->in_edges->pred);  /* jf */
1837
1838
  /*
1839
   * diffp is a pointer to a pointer to the block.
1840
   *
1841
   * Go down the false chain looking as far as you can,
1842
   * making sure that each jump-compare is doing the
1843
   * same as the original block.
1844
   *
1845
   * If you reach the bottom before you reach a
1846
   * different jump-compare, just exit.  There's nothing
1847
   * to do here.  XXX - no, this version is checking for
1848
   * the value leaving the block; that's from the BPF+
1849
   * pullup routine.
1850
   */
1851
315k
  at_top = 1;
1852
466k
  for (;;) {
1853
    /*
1854
     * Done if that's not going anywhere XXX
1855
     */
1856
466k
    if (*diffp == 0)
1857
0
      return;
1858
1859
    /*
1860
     * Done if that predecessor blah blah blah isn't
1861
     * going the same place we're going XXX
1862
     *
1863
     * Does the true edge of this block point to the same
1864
     * location as the true edge of b?
1865
     */
1866
466k
    if (JT(*diffp) != JT(b))
1867
79.8k
      return;
1868
1869
    /*
1870
     * Done if this node isn't a dominator of that
1871
     * node blah blah blah XXX
1872
     *
1873
     * Does b dominate diffp?
1874
     */
1875
386k
    if (!SET_MEMBER((*diffp)->dom, b->id))
1876
3.34k
      return;
1877
1878
    /*
1879
     * Break out of the loop if that node's value of A
1880
     * isn't the value of A above XXX
1881
     */
1882
382k
    if ((*diffp)->val[A_ATOM] != val)
1883
231k
      break;
1884
1885
    /*
1886
     * Get the JF for that node XXX
1887
     * Go down the false path.
1888
     */
1889
150k
    diffp = &JF(*diffp);
1890
150k
    at_top = 0;
1891
150k
  }
1892
1893
  /*
1894
   * Now that we've found a different jump-compare in a chain
1895
   * below b, search further down until we find another
1896
   * jump-compare that looks at the original value.  This
1897
   * jump-compare should get pulled up.  XXX again we're
1898
   * comparing values not jump-compares.
1899
   */
1900
231k
  samep = &JF(*diffp);
1901
308k
  for (;;) {
1902
    /*
1903
     * Done if that's not going anywhere XXX
1904
     */
1905
308k
    if (*samep == 0)
1906
0
      return;
1907
1908
    /*
1909
     * Done if that predecessor blah blah blah isn't
1910
     * going the same place we're going XXX
1911
     */
1912
308k
    if (JT(*samep) != JT(b))
1913
208k
      return;
1914
1915
    /*
1916
     * Done if this node isn't a dominator of that
1917
     * node blah blah blah XXX
1918
     *
1919
     * Does b dominate samep?
1920
     */
1921
99.7k
    if (!SET_MEMBER((*samep)->dom, b->id))
1922
11.7k
      return;
1923
1924
    /*
1925
     * Break out of the loop if that node's value of A
1926
     * is the value of A above XXX
1927
     */
1928
88.0k
    if ((*samep)->val[A_ATOM] == val)
1929
11.5k
      break;
1930
1931
    /* XXX Need to check that there are no data dependencies
1932
       between dp0 and dp1.  Currently, the code generator
1933
       will not produce such dependencies. */
1934
76.4k
    samep = &JF(*samep);
1935
76.4k
  }
1936
#ifdef notdef
1937
  /* XXX This doesn't cover everything. */
1938
  for (i = 0; i < N_ATOMS; ++i)
1939
    if ((*samep)->val[i] != pred->val[i])
1940
      return;
1941
#endif
1942
  /* Pull up the node. */
1943
11.5k
  pull = *samep;
1944
11.5k
  *samep = JF(pull);
1945
11.5k
  JF(pull) = *diffp;
1946
1947
  /*
1948
   * At the top of the chain, each predecessor needs to point at the
1949
   * pulled up node.  Inside the chain, there is only one predecessor
1950
   * to worry about.
1951
   */
1952
11.5k
  if (at_top) {
1953
23.3k
    for (ep = b->in_edges; ep != 0; ep = ep->next) {
1954
12.4k
      if (JT(ep->pred) == b)
1955
8.60k
        JT(ep->pred) = pull;
1956
3.84k
      else
1957
3.84k
        JF(ep->pred) = pull;
1958
12.4k
    }
1959
10.8k
  }
1960
697
  else
1961
697
    *diffp = pull;
1962
1963
  /*
1964
   * XXX - this is one of the operations that happens when the
1965
   * optimizer gets into one of those infinite loops.
1966
   */
1967
11.5k
  opt_state->done = 0;
1968
1969
  /*
1970
   * Recompute dominator sets as control flow graph has changed.
1971
   */
1972
11.5k
  find_dom(opt_state, root);
1973
11.5k
}
1974
1975
static void
1976
and_pullup(opt_state_t *opt_state, struct block *b, struct block *root)
1977
423k
{
1978
423k
  bpf_u_int32 val;
1979
423k
  int at_top;
1980
423k
  struct block *pull;
1981
423k
  struct block **diffp, **samep;
1982
423k
  struct edge *ep;
1983
1984
423k
  ep = b->in_edges;
1985
423k
  if (ep == 0)
1986
47.2k
    return;
1987
1988
  /*
1989
   * Make sure each predecessor loads the same value.
1990
   */
1991
376k
  val = ep->pred->val[A_ATOM];
1992
465k
  for (ep = ep->next; ep != 0; ep = ep->next)
1993
150k
    if (val != ep->pred->val[A_ATOM])
1994
61.3k
      return;
1995
1996
315k
  if (JT(b->in_edges->pred) == b)
1997
119k
    diffp = &JT(b->in_edges->pred);
1998
195k
  else
1999
195k
    diffp = &JF(b->in_edges->pred);
2000
2001
315k
  at_top = 1;
2002
406k
  for (;;) {
2003
406k
    if (*diffp == 0)
2004
0
      return;
2005
2006
406k
    if (JF(*diffp) != JF(b))
2007
91.7k
      return;
2008
2009
314k
    if (!SET_MEMBER((*diffp)->dom, b->id))
2010
4.95k
      return;
2011
2012
310k
    if ((*diffp)->val[A_ATOM] != val)
2013
218k
      break;
2014
2015
91.6k
    diffp = &JT(*diffp);
2016
91.6k
    at_top = 0;
2017
91.6k
  }
2018
218k
  samep = &JT(*diffp);
2019
274k
  for (;;) {
2020
274k
    if (*samep == 0)
2021
0
      return;
2022
2023
274k
    if (JF(*samep) != JF(b))
2024
213k
      return;
2025
2026
60.3k
    if (!SET_MEMBER((*samep)->dom, b->id))
2027
3.90k
      return;
2028
2029
56.4k
    if ((*samep)->val[A_ATOM] == val)
2030
551
      break;
2031
2032
    /* XXX Need to check that there are no data dependencies
2033
       between diffp and samep.  Currently, the code generator
2034
       will not produce such dependencies. */
2035
55.8k
    samep = &JT(*samep);
2036
55.8k
  }
2037
#ifdef notdef
2038
  /* XXX This doesn't cover everything. */
2039
  for (i = 0; i < N_ATOMS; ++i)
2040
    if ((*samep)->val[i] != pred->val[i])
2041
      return;
2042
#endif
2043
  /* Pull up the node. */
2044
551
  pull = *samep;
2045
551
  *samep = JT(pull);
2046
551
  JT(pull) = *diffp;
2047
2048
  /*
2049
   * At the top of the chain, each predecessor needs to point at the
2050
   * pulled up node.  Inside the chain, there is only one predecessor
2051
   * to worry about.
2052
   */
2053
551
  if (at_top) {
2054
1.47k
    for (ep = b->in_edges; ep != 0; ep = ep->next) {
2055
972
      if (JT(ep->pred) == b)
2056
613
        JT(ep->pred) = pull;
2057
359
      else
2058
359
        JF(ep->pred) = pull;
2059
972
    }
2060
503
  }
2061
48
  else
2062
48
    *diffp = pull;
2063
2064
  /*
2065
   * XXX - this is one of the operations that happens when the
2066
   * optimizer gets into one of those infinite loops.
2067
   */
2068
551
  opt_state->done = 0;
2069
2070
  /*
2071
   * Recompute dominator sets as control flow graph has changed.
2072
   */
2073
551
  find_dom(opt_state, root);
2074
551
}
2075
2076
static void
2077
opt_blks(opt_state_t *opt_state, struct icode *ic, int do_stmts)
2078
44.9k
{
2079
44.9k
  int i, maxlevel;
2080
44.9k
  struct block *p;
2081
2082
44.9k
  init_val(opt_state);
2083
44.9k
  maxlevel = ic->root->level;
2084
2085
44.9k
  find_inedges(opt_state, ic->root);
2086
556k
  for (i = maxlevel; i >= 0; --i)
2087
1.21M
    for (p = opt_state->levels[i]; p; p = p->link)
2088
705k
      opt_blk(opt_state, p, do_stmts);
2089
2090
44.9k
  if (do_stmts)
2091
    /*
2092
     * No point trying to move branches; it can't possibly
2093
     * make a difference at this point.
2094
     *
2095
     * XXX - this might be after we detect a loop where
2096
     * we were just looping infinitely moving branches
2097
     * in such a fashion that we went through two or more
2098
     * versions of the machine code, eventually returning
2099
     * to the first version.  (We're really not doing a
2100
     * full loop detection, we're just testing for two
2101
     * passes in a row where we do nothing but
2102
     * move branches.)
2103
     */
2104
21.3k
    return;
2105
2106
  /*
2107
   * Is this what the BPF+ paper describes in sections 6.1.1,
2108
   * 6.1.2, and 6.1.3?
2109
   */
2110
335k
  for (i = 1; i <= maxlevel; ++i) {
2111
735k
    for (p = opt_state->levels[i]; p; p = p->link) {
2112
423k
      opt_j(opt_state, &p->et);
2113
423k
      opt_j(opt_state, &p->ef);
2114
423k
    }
2115
312k
  }
2116
2117
23.6k
  find_inedges(opt_state, ic->root);
2118
335k
  for (i = 1; i <= maxlevel; ++i) {
2119
735k
    for (p = opt_state->levels[i]; p; p = p->link) {
2120
423k
      or_pullup(opt_state, p, ic->root);
2121
423k
      and_pullup(opt_state, p, ic->root);
2122
423k
    }
2123
312k
  }
2124
23.6k
}
2125
2126
static inline void
2127
link_inedge(struct edge *parent, struct block *child)
2128
2.10M
{
2129
2.10M
  parent->next = child->in_edges;
2130
2.10M
  child->in_edges = parent;
2131
2.10M
}
2132
2133
static void
2134
find_inedges(opt_state_t *opt_state, struct block *root)
2135
68.5k
{
2136
68.5k
  u_int i;
2137
68.5k
  int level;
2138
68.5k
  struct block *b;
2139
2140
1.59M
  for (i = 0; i < opt_state->n_blocks; ++i)
2141
1.52M
    opt_state->blocks[i]->in_edges = 0;
2142
2143
  /*
2144
   * Traverse the graph, adding each edge to the predecessor
2145
   * list of its successors.  Skip the leaves (i.e. level 0).
2146
   */
2147
846k
  for (level = root->level; level > 0; --level) {
2148
1.82M
    for (b = opt_state->levels[level]; b != 0; b = b->link) {
2149
1.05M
      link_inedge(&b->et, JT(b));
2150
1.05M
      link_inedge(&b->ef, JF(b));
2151
1.05M
    }
2152
778k
  }
2153
68.5k
}
2154
2155
static void
2156
opt_root(struct block **b)
2157
7.90k
{
2158
7.90k
  struct slist *tmp, *s;
2159
2160
7.90k
  s = (*b)->stmts;
2161
7.90k
  (*b)->stmts = 0;
2162
9.68k
  while (BPF_CLASS((*b)->s.code) == BPF_JMP && JT(*b) == JF(*b))
2163
1.78k
    *b = JT(*b);
2164
2165
7.90k
  tmp = (*b)->stmts;
2166
7.90k
  if (tmp != 0)
2167
186
    sappend(s, tmp);
2168
7.90k
  (*b)->stmts = s;
2169
2170
  /*
2171
   * If the root node is a return, then there is no
2172
   * point executing any statements (since the bpf machine
2173
   * has no side effects).
2174
   */
2175
7.90k
  if (BPF_CLASS((*b)->s.code) == BPF_RET)
2176
4.01k
    (*b)->stmts = 0;
2177
7.90k
}
2178
2179
static void
2180
opt_loop(opt_state_t *opt_state, struct icode *ic, int do_stmts)
2181
15.9k
{
2182
2183
#ifdef BDEBUG
2184
  if (pcap_optimizer_debug > 1 || pcap_print_dot_graph) {
2185
    printf("%s(root, %d) begin\n", __func__, do_stmts);
2186
    opt_dump(opt_state, ic);
2187
  }
2188
#endif
2189
2190
  /*
2191
   * XXX - optimizer loop detection.
2192
   */
2193
15.9k
  int loop_count = 0;
2194
44.9k
  for (;;) {
2195
    /*
2196
     * XXX - optimizer loop detection.
2197
     */
2198
44.9k
    opt_state->non_branch_movement_performed = 0;
2199
44.9k
    opt_state->done = 1;
2200
44.9k
    find_levels(opt_state, ic);
2201
44.9k
    find_dom(opt_state, ic->root);
2202
44.9k
    find_closure(opt_state, ic->root);
2203
44.9k
    find_ud(opt_state, ic->root);
2204
44.9k
    find_edom(opt_state, ic->root);
2205
44.9k
    opt_blks(opt_state, ic, do_stmts);
2206
#ifdef BDEBUG
2207
    if (pcap_optimizer_debug > 1 || pcap_print_dot_graph) {
2208
      printf("%s(root, %d) bottom, done=%d\n", __func__, do_stmts, opt_state->done);
2209
      opt_dump(opt_state, ic);
2210
    }
2211
#endif
2212
2213
    /*
2214
     * Was anything done in this optimizer pass?
2215
     */
2216
44.9k
    if (opt_state->done) {
2217
      /*
2218
       * No, so we've reached a fixed point.
2219
       * We're done.
2220
       */
2221
15.8k
      break;
2222
15.8k
    }
2223
2224
    /*
2225
     * XXX - was anything done other than branch movement
2226
     * in this pass?
2227
     */
2228
29.1k
    if (opt_state->non_branch_movement_performed) {
2229
      /*
2230
       * Yes.  Clear any loop-detection counter;
2231
       * we're making some form of progress (assuming
2232
       * we can't get into a cycle doing *other*
2233
       * optimizations...).
2234
       */
2235
19.9k
      loop_count = 0;
2236
19.9k
    } else {
2237
      /*
2238
       * No - increment the counter, and quit if
2239
       * it's up to 100.
2240
       */
2241
9.22k
      loop_count++;
2242
9.22k
      if (loop_count >= 100) {
2243
        /*
2244
         * We've done nothing but branch movement
2245
         * for 100 passes; we're probably
2246
         * in a cycle and will never reach a
2247
         * fixed point.
2248
         *
2249
         * XXX - yes, we really need a non-
2250
         * heuristic way of detecting a cycle.
2251
         */
2252
70
        opt_state->done = 1;
2253
70
        break;
2254
70
      }
2255
9.22k
    }
2256
29.1k
  }
2257
15.9k
}
2258
2259
/*
2260
 * Optimize the filter code in its dag representation.
2261
 * Return 0 on success, -1 on error.
2262
 */
2263
int
2264
bpf_optimize(struct icode *ic, char *errbuf)
2265
7.99k
{
2266
7.99k
  opt_state_t opt_state;
2267
2268
7.99k
  memset(&opt_state, 0, sizeof(opt_state));
2269
7.99k
  opt_state.errbuf = errbuf;
2270
7.99k
  if (setjmp(opt_state.top_ctx)) {
2271
92
    opt_cleanup(&opt_state);
2272
92
    return -1;
2273
92
  }
2274
7.90k
  opt_init(&opt_state, ic);
2275
7.90k
  opt_loop(&opt_state, ic, 0);
2276
7.90k
  opt_loop(&opt_state, ic, 1);
2277
7.90k
  intern_blocks(&opt_state, ic);
2278
#ifdef BDEBUG
2279
  if (pcap_optimizer_debug > 1 || pcap_print_dot_graph) {
2280
    printf("after intern_blocks()\n");
2281
    opt_dump(&opt_state, ic);
2282
  }
2283
#endif
2284
7.90k
  opt_root(&ic->root);
2285
#ifdef BDEBUG
2286
  if (pcap_optimizer_debug > 1 || pcap_print_dot_graph) {
2287
    printf("after opt_root()\n");
2288
    opt_dump(&opt_state, ic);
2289
  }
2290
#endif
2291
7.90k
  opt_cleanup(&opt_state);
2292
7.90k
  return 0;
2293
7.99k
}
2294
2295
static void
2296
make_marks(struct icode *ic, struct block *p)
2297
649k
{
2298
649k
  if (!isMarked(ic, p)) {
2299
336k
    Mark(ic, p);
2300
336k
    if (BPF_CLASS(p->s.code) != BPF_RET) {
2301
319k
      make_marks(ic, JT(p));
2302
319k
      make_marks(ic, JF(p));
2303
319k
    }
2304
336k
  }
2305
649k
}
2306
2307
/*
2308
 * Mark code array such that isMarked(ic->cur_mark, i) is true
2309
 * only for nodes that are alive.
2310
 */
2311
static void
2312
mark_code(struct icode *ic)
2313
10.3k
{
2314
10.3k
  ic->cur_mark += 1;
2315
10.3k
  make_marks(ic, ic->root);
2316
10.3k
}
2317
2318
/*
2319
 * True iff the two stmt lists load the same value from the packet into
2320
 * the accumulator.
2321
 */
2322
static int
2323
eq_slist(struct slist *x, struct slist *y)
2324
10.6k
{
2325
16.5k
  for (;;) {
2326
18.9k
    while (x && x->s.code == NOP)
2327
2.46k
      x = x->next;
2328
19.0k
    while (y && y->s.code == NOP)
2329
2.56k
      y = y->next;
2330
16.5k
    if (x == 0)
2331
4.03k
      return y == 0;
2332
12.4k
    if (y == 0)
2333
413
      return x == 0;
2334
12.0k
    if (x->s.code != y->s.code || x->s.k != y->s.k)
2335
6.18k
      return 0;
2336
5.87k
    x = x->next;
2337
5.87k
    y = y->next;
2338
5.87k
  }
2339
10.6k
}
2340
2341
static inline int
2342
eq_blk(struct block *b0, struct block *b1)
2343
41.6M
{
2344
41.6M
  if (b0->s.code == b1->s.code &&
2345
39.0M
      b0->s.k == b1->s.k &&
2346
5.25M
      b0->et.succ == b1->et.succ &&
2347
251k
      b0->ef.succ == b1->ef.succ)
2348
10.6k
    return eq_slist(b0->stmts, b1->stmts);
2349
41.6M
  return 0;
2350
41.6M
}
2351
2352
static void
2353
intern_blocks(opt_state_t *opt_state, struct icode *ic)
2354
7.90k
{
2355
7.90k
  struct block *p;
2356
7.90k
  u_int i, j;
2357
7.90k
  int done1; /* don't shadow global */
2358
10.3k
 top:
2359
10.3k
  done1 = 1;
2360
638k
  for (i = 0; i < opt_state->n_blocks; ++i)
2361
627k
    opt_state->blocks[i]->link = 0;
2362
2363
10.3k
  mark_code(ic);
2364
2365
627k
  for (i = opt_state->n_blocks - 1; i != 0; ) {
2366
617k
    --i;
2367
617k
    if (!isMarked(ic, opt_state->blocks[i]))
2368
291k
      continue;
2369
63.9M
    for (j = i + 1; j < opt_state->n_blocks; ++j) {
2370
63.6M
      if (!isMarked(ic, opt_state->blocks[j]))
2371
21.9M
        continue;
2372
41.6M
      if (eq_blk(opt_state->blocks[i], opt_state->blocks[j])) {
2373
3.78k
        opt_state->blocks[i]->link = opt_state->blocks[j]->link ?
2374
3.16k
          opt_state->blocks[j]->link : opt_state->blocks[j];
2375
3.78k
        break;
2376
3.78k
      }
2377
41.6M
    }
2378
326k
  }
2379
638k
  for (i = 0; i < opt_state->n_blocks; ++i) {
2380
627k
    p = opt_state->blocks[i];
2381
627k
    if (JT(p) == 0)
2382
18.1k
      continue;
2383
609k
    if (JT(p)->link) {
2384
4.24k
      done1 = 0;
2385
4.24k
      JT(p) = JT(p)->link;
2386
4.24k
    }
2387
609k
    if (JF(p)->link) {
2388
3.62k
      done1 = 0;
2389
3.62k
      JF(p) = JF(p)->link;
2390
3.62k
    }
2391
609k
  }
2392
10.3k
  if (!done1)
2393
2.42k
    goto top;
2394
10.3k
}
2395
2396
static void
2397
opt_cleanup(opt_state_t *opt_state)
2398
7.99k
{
2399
7.99k
  free((void *)opt_state->vnode_base);
2400
7.99k
  free((void *)opt_state->vmap);
2401
7.99k
  free((void *)opt_state->edges);
2402
7.99k
  free((void *)opt_state->space);
2403
7.99k
  free((void *)opt_state->levels);
2404
7.99k
  free((void *)opt_state->blocks);
2405
7.99k
}
2406
2407
/*
2408
 * For optimizer errors.
2409
 */
2410
static void PCAP_NORETURN
2411
opt_error(opt_state_t *opt_state, const char *fmt, ...)
2412
92
{
2413
92
  va_list ap;
2414
2415
92
  if (opt_state->errbuf != NULL) {
2416
92
    va_start(ap, fmt);
2417
92
    (void)vsnprintf(opt_state->errbuf,
2418
92
        PCAP_ERRBUF_SIZE, fmt, ap);
2419
92
    va_end(ap);
2420
92
  }
2421
92
  longjmp(opt_state->top_ctx, 1);
2422
  /* NOTREACHED */
2423
#ifdef _AIX
2424
  PCAP_UNREACHABLE
2425
#endif /* _AIX */
2426
92
}
2427
2428
/*
2429
 * Return the number of stmts in 's'.
2430
 */
2431
static u_int
2432
slength(struct slist *s)
2433
7.75M
{
2434
7.75M
  u_int n = 0;
2435
2436
21.9M
  for (; s; s = s->next)
2437
14.1M
    if (s->s.code != NOP)
2438
10.4M
      ++n;
2439
7.75M
  return n;
2440
7.75M
}
2441
2442
/*
2443
 * Return the number of nodes reachable by 'p'.
2444
 * All nodes should be initially unmarked.
2445
 */
2446
static int
2447
count_blocks(struct icode *ic, struct block *p)
2448
276k
{
2449
276k
  if (p == 0 || isMarked(ic, p))
2450
142k
    return 0;
2451
134k
  Mark(ic, p);
2452
134k
  return count_blocks(ic, JT(p)) + count_blocks(ic, JF(p)) + 1;
2453
276k
}
2454
2455
/*
2456
 * Do a depth first search on the flow graph, numbering the
2457
 * the basic blocks, and entering them into the 'blocks' array.`
2458
 */
2459
static void
2460
number_blks_r(opt_state_t *opt_state, struct icode *ic, struct block *p)
2461
276k
{
2462
276k
  u_int n;
2463
2464
276k
  if (p == 0 || isMarked(ic, p))
2465
142k
    return;
2466
2467
134k
  Mark(ic, p);
2468
134k
  n = opt_state->n_blocks++;
2469
134k
  if (opt_state->n_blocks == 0) {
2470
    /*
2471
     * Overflow.
2472
     */
2473
0
    opt_error(opt_state, "filter is too complex to optimize");
2474
0
  }
2475
134k
  p->id = n;
2476
134k
  opt_state->blocks[n] = p;
2477
2478
134k
  number_blks_r(opt_state, ic, JT(p));
2479
134k
  number_blks_r(opt_state, ic, JF(p));
2480
134k
}
2481
2482
/*
2483
 * Return the number of stmts in the flowgraph reachable by 'p'.
2484
 * The nodes should be unmarked before calling.
2485
 *
2486
 * Note that "stmts" means "instructions", and that this includes
2487
 *
2488
 *  side-effect statements in 'p' (slength(p->stmts));
2489
 *
2490
 *  statements in the true branch from 'p' (count_stmts(JT(p)));
2491
 *
2492
 *  statements in the false branch from 'p' (count_stmts(JF(p)));
2493
 *
2494
 *  the conditional jump itself (1);
2495
 *
2496
 *  an extra long jump if the true branch requires it (p->longjt);
2497
 *
2498
 *  an extra long jump if the false branch requires it (p->longjf).
2499
 */
2500
static u_int
2501
count_stmts(struct icode *ic, struct block *p)
2502
9.55M
{
2503
9.55M
  u_int n;
2504
2505
9.55M
  if (p == 0 || isMarked(ic, p))
2506
4.78M
    return 0;
2507
4.77M
  Mark(ic, p);
2508
4.77M
  n = count_stmts(ic, JT(p)) + count_stmts(ic, JF(p));
2509
4.77M
  return slength(p->stmts) + n + 1 + p->longjt + p->longjf;
2510
9.55M
}
2511
2512
/*
2513
 * Allocate memory.  All allocation is done before optimization
2514
 * is begun.  A linear bound on the size of all data structures is computed
2515
 * from the total number of blocks and/or statements.
2516
 */
2517
static void
2518
opt_init(opt_state_t *opt_state, struct icode *ic)
2519
7.99k
{
2520
7.99k
  bpf_u_int32 *p;
2521
7.99k
  int i, n, max_stmts;
2522
7.99k
  u_int product;
2523
7.99k
  size_t block_memsize, edge_memsize;
2524
2525
  /*
2526
   * First, count the blocks, so we can malloc an array to map
2527
   * block number to block.  Then, put the blocks into the array.
2528
   */
2529
7.99k
  unMarkAll(ic);
2530
7.99k
  n = count_blocks(ic, ic->root);
2531
7.99k
  opt_state->blocks = (struct block **)calloc(n, sizeof(*opt_state->blocks));
2532
7.99k
  if (opt_state->blocks == NULL)
2533
0
    opt_error(opt_state, "malloc");
2534
7.99k
  unMarkAll(ic);
2535
7.99k
  opt_state->n_blocks = 0;
2536
7.99k
  number_blks_r(opt_state, ic, ic->root);
2537
2538
  /*
2539
   * This "should not happen".
2540
   */
2541
7.99k
  if (opt_state->n_blocks == 0)
2542
0
    opt_error(opt_state, "filter has no instructions; please report this as a libpcap issue");
2543
2544
7.99k
  opt_state->n_edges = 2 * opt_state->n_blocks;
2545
7.99k
  if ((opt_state->n_edges / 2) != opt_state->n_blocks) {
2546
    /*
2547
     * Overflow.
2548
     */
2549
0
    opt_error(opt_state, "filter is too complex to optimize");
2550
0
  }
2551
7.99k
  opt_state->edges = (struct edge **)calloc(opt_state->n_edges, sizeof(*opt_state->edges));
2552
7.99k
  if (opt_state->edges == NULL) {
2553
0
    opt_error(opt_state, "malloc");
2554
0
  }
2555
2556
  /*
2557
   * The number of levels is bounded by the number of nodes.
2558
   */
2559
7.99k
  opt_state->levels = (struct block **)calloc(opt_state->n_blocks, sizeof(*opt_state->levels));
2560
7.99k
  if (opt_state->levels == NULL) {
2561
0
    opt_error(opt_state, "malloc");
2562
0
  }
2563
2564
7.99k
  opt_state->edgewords = opt_state->n_edges / BITS_PER_WORD + 1;
2565
7.99k
  opt_state->nodewords = opt_state->n_blocks / BITS_PER_WORD + 1;
2566
2567
  /*
2568
   * Make sure opt_state->n_blocks * opt_state->nodewords fits
2569
   * in a u_int; we use it as a u_int number-of-iterations
2570
   * value.
2571
   */
2572
7.99k
  product = opt_state->n_blocks * opt_state->nodewords;
2573
7.99k
  if ((product / opt_state->n_blocks) != opt_state->nodewords) {
2574
    /*
2575
     * XXX - just punt and don't try to optimize?
2576
     * In practice, this is unlikely to happen with
2577
     * a normal filter.
2578
     */
2579
0
    opt_error(opt_state, "filter is too complex to optimize");
2580
0
  }
2581
2582
  /*
2583
   * Make sure the total memory required for that doesn't
2584
   * overflow.
2585
   */
2586
7.99k
  block_memsize = (size_t)2 * product * sizeof(*opt_state->space);
2587
7.99k
  if ((block_memsize / product) != 2 * sizeof(*opt_state->space)) {
2588
0
    opt_error(opt_state, "filter is too complex to optimize");
2589
0
  }
2590
2591
  /*
2592
   * Make sure opt_state->n_edges * opt_state->edgewords fits
2593
   * in a u_int; we use it as a u_int number-of-iterations
2594
   * value.
2595
   */
2596
7.99k
  product = opt_state->n_edges * opt_state->edgewords;
2597
7.99k
  if ((product / opt_state->n_edges) != opt_state->edgewords) {
2598
0
    opt_error(opt_state, "filter is too complex to optimize");
2599
0
  }
2600
2601
  /*
2602
   * Make sure the total memory required for that doesn't
2603
   * overflow.
2604
   */
2605
7.99k
  edge_memsize = (size_t)product * sizeof(*opt_state->space);
2606
7.99k
  if (edge_memsize / product != sizeof(*opt_state->space)) {
2607
0
    opt_error(opt_state, "filter is too complex to optimize");
2608
0
  }
2609
2610
  /*
2611
   * Make sure the total memory required for both of them doesn't
2612
   * overflow.
2613
   */
2614
7.99k
  if (block_memsize > SIZE_MAX - edge_memsize) {
2615
0
    opt_error(opt_state, "filter is too complex to optimize");
2616
0
  }
2617
2618
  /* XXX */
2619
7.99k
  opt_state->space = (bpf_u_int32 *)malloc(block_memsize + edge_memsize);
2620
7.99k
  if (opt_state->space == NULL) {
2621
0
    opt_error(opt_state, "malloc");
2622
0
  }
2623
7.99k
  p = opt_state->space;
2624
7.99k
  opt_state->all_dom_sets = p;
2625
142k
  for (i = 0; i < n; ++i) {
2626
134k
    opt_state->blocks[i]->dom = p;
2627
134k
    p += opt_state->nodewords;
2628
134k
  }
2629
7.99k
  opt_state->all_closure_sets = p;
2630
142k
  for (i = 0; i < n; ++i) {
2631
134k
    opt_state->blocks[i]->closure = p;
2632
134k
    p += opt_state->nodewords;
2633
134k
  }
2634
7.99k
  opt_state->all_edge_sets = p;
2635
142k
  for (i = 0; i < n; ++i) {
2636
134k
    struct block *b = opt_state->blocks[i];
2637
2638
134k
    b->et.edom = p;
2639
134k
    p += opt_state->edgewords;
2640
134k
    b->ef.edom = p;
2641
134k
    p += opt_state->edgewords;
2642
134k
    b->et.id = i;
2643
134k
    opt_state->edges[i] = &b->et;
2644
134k
    b->ef.id = opt_state->n_blocks + i;
2645
134k
    opt_state->edges[opt_state->n_blocks + i] = &b->ef;
2646
134k
    b->et.pred = b;
2647
134k
    b->ef.pred = b;
2648
134k
  }
2649
7.99k
  max_stmts = 0;
2650
142k
  for (i = 0; i < n; ++i)
2651
134k
    max_stmts += slength(opt_state->blocks[i]->stmts) + 1;
2652
  /*
2653
   * We allocate at most 3 value numbers per statement,
2654
   * so this is an upper bound on the number of valnodes
2655
   * we'll need.
2656
   */
2657
7.99k
  opt_state->maxval = 3 * max_stmts;
2658
7.99k
  opt_state->vmap = (struct vmapinfo *)calloc(opt_state->maxval, sizeof(*opt_state->vmap));
2659
7.99k
  if (opt_state->vmap == NULL) {
2660
0
    opt_error(opt_state, "malloc");
2661
0
  }
2662
7.99k
  opt_state->vnode_base = (struct valnode *)calloc(opt_state->maxval, sizeof(*opt_state->vnode_base));
2663
7.99k
  if (opt_state->vnode_base == NULL) {
2664
0
    opt_error(opt_state, "malloc");
2665
0
  }
2666
7.99k
}
2667
2668
/*
2669
 * This is only used when supporting optimizer debugging.  It is
2670
 * global state, so do *not* do more than one compile in parallel
2671
 * and expect it to provide meaningful information.
2672
 */
2673
#ifdef BDEBUG
2674
int bids[NBIDS];
2675
#endif
2676
2677
/*
2678
 * Returns true if successful.  Returns false if a branch has
2679
 * an offset that is too large.  If so, we have marked that
2680
 * branch so that on a subsequent iteration, it will be treated
2681
 * properly.
2682
 */
2683
static int
2684
convert_code_r(conv_state_t *conv_state, struct icode *ic, struct block *p)
2685
7.07M
{
2686
7.07M
  struct bpf_insn *dst;
2687
7.07M
  struct slist *src;
2688
7.07M
  u_int slen;
2689
7.07M
  u_int off;
2690
7.07M
  struct slist **offset = NULL;
2691
2692
7.07M
  if (p == 0 || isMarked(ic, p))
2693
3.15M
    return (1);
2694
3.91M
  Mark(ic, p);
2695
2696
3.91M
  if (convert_code_r(conv_state, ic, JF(p)) == 0)
2697
772k
    return (0);
2698
3.14M
  if (convert_code_r(conv_state, ic, JT(p)) == 0)
2699
290k
    return (0);
2700
2701
2.85M
  slen = slength(p->stmts);
2702
2.85M
  dst = conv_state->ftail -= (slen + 1 + p->longjt + p->longjf);
2703
    /* inflate length by any extra jumps */
2704
2705
2.85M
  p->offset = (int)(dst - conv_state->fstart);
2706
2707
  /* generate offset[] for convenience  */
2708
2.85M
  if (slen) {
2709
1.93M
    offset = (struct slist **)calloc(slen, sizeof(struct slist *));
2710
1.93M
    if (!offset) {
2711
0
      conv_error(conv_state, "not enough core");
2712
      /*NOTREACHED*/
2713
0
    }
2714
1.93M
  }
2715
2.85M
  src = p->stmts;
2716
6.69M
  for (off = 0; off < slen && src; off++) {
2717
#if 0
2718
    printf("off=%d src=%x\n", off, src);
2719
#endif
2720
3.83M
    offset[off] = src;
2721
3.83M
    src = src->next;
2722
3.83M
  }
2723
2724
2.85M
  off = 0;
2725
8.06M
  for (src = p->stmts; src; src = src->next) {
2726
5.20M
    if (src->s.code == NOP)
2727
1.36M
      continue;
2728
3.83M
    dst->code = (u_short)src->s.code;
2729
3.83M
    dst->k = src->s.k;
2730
2731
    /* fill block-local relative jump */
2732
3.83M
    if (BPF_CLASS(src->s.code) != BPF_JMP || src->s.code == (BPF_JMP|BPF_JA)) {
2733
#if 0
2734
      if (src->s.jt || src->s.jf) {
2735
        free(offset);
2736
        conv_error(conv_state, "illegal jmp destination");
2737
        /*NOTREACHED*/
2738
      }
2739
#endif
2740
3.83M
      goto filled;
2741
3.83M
    }
2742
6.01k
    if (off == slen - 2)  /*???*/
2743
0
      goto filled;
2744
2745
6.01k
      {
2746
6.01k
    u_int i;
2747
6.01k
    int jt, jf;
2748
6.01k
    const char ljerr[] = "%s for block-local relative jump: off=%d";
2749
2750
#if 0
2751
    printf("code=%x off=%d %x %x\n", src->s.code,
2752
      off, src->s.jt, src->s.jf);
2753
#endif
2754
2755
6.01k
    if (!src->s.jt || !src->s.jf) {
2756
0
      free(offset);
2757
0
      conv_error(conv_state, ljerr, "no jmp destination", off);
2758
      /*NOTREACHED*/
2759
0
    }
2760
2761
6.01k
    jt = jf = 0;
2762
163k
    for (i = 0; i < slen; i++) {
2763
157k
      if (offset[i] == src->s.jt) {
2764
6.01k
        if (jt) {
2765
0
          free(offset);
2766
0
          conv_error(conv_state, ljerr, "multiple matches", off);
2767
          /*NOTREACHED*/
2768
0
        }
2769
2770
6.01k
        if (i - off - 1 >= 256) {
2771
0
          free(offset);
2772
0
          conv_error(conv_state, ljerr, "out-of-range jump", off);
2773
          /*NOTREACHED*/
2774
0
        }
2775
6.01k
        dst->jt = (u_char)(i - off - 1);
2776
6.01k
        jt++;
2777
6.01k
      }
2778
157k
      if (offset[i] == src->s.jf) {
2779
6.01k
        if (jf) {
2780
0
          free(offset);
2781
0
          conv_error(conv_state, ljerr, "multiple matches", off);
2782
          /*NOTREACHED*/
2783
0
        }
2784
6.01k
        if (i - off - 1 >= 256) {
2785
0
          free(offset);
2786
0
          conv_error(conv_state, ljerr, "out-of-range jump", off);
2787
          /*NOTREACHED*/
2788
0
        }
2789
6.01k
        dst->jf = (u_char)(i - off - 1);
2790
6.01k
        jf++;
2791
6.01k
      }
2792
157k
    }
2793
6.01k
    if (!jt || !jf) {
2794
0
      free(offset);
2795
0
      conv_error(conv_state, ljerr, "no destination found", off);
2796
      /*NOTREACHED*/
2797
0
    }
2798
6.01k
      }
2799
3.83M
filled:
2800
3.83M
    ++dst;
2801
3.83M
    ++off;
2802
3.83M
  }
2803
2.85M
  if (offset)
2804
1.93M
    free(offset);
2805
2806
#ifdef BDEBUG
2807
  if (dst - conv_state->fstart < NBIDS)
2808
    bids[dst - conv_state->fstart] = p->id + 1;
2809
#endif
2810
2.85M
  dst->code = (u_short)p->s.code;
2811
2.85M
  dst->k = p->s.k;
2812
2.85M
  if (JT(p)) {
2813
    /* number of extra jumps inserted */
2814
2.82M
    u_char extrajmps = 0;
2815
2.82M
    off = JT(p)->offset - (p->offset + slen) - 1;
2816
2.82M
    if (off >= 256) {
2817
        /* offset too large for branch, must add a jump */
2818
180k
        if (p->longjt == 0) {
2819
      /* mark this instruction and retry */
2820
3.08k
      p->longjt++;
2821
3.08k
      return(0);
2822
3.08k
        }
2823
177k
        dst->jt = extrajmps;
2824
177k
        extrajmps++;
2825
177k
        dst[extrajmps].code = BPF_JMP|BPF_JA;
2826
177k
        dst[extrajmps].k = off - extrajmps;
2827
177k
    }
2828
2.64M
    else
2829
2.64M
        dst->jt = (u_char)off;
2830
2.82M
    off = JF(p)->offset - (p->offset + slen) - 1;
2831
2.82M
    if (off >= 256) {
2832
        /* offset too large for branch, must add a jump */
2833
387k
        if (p->longjf == 0) {
2834
      /* mark this instruction and retry */
2835
4.97k
      p->longjf++;
2836
4.97k
      return(0);
2837
4.97k
        }
2838
        /* branch if F to following jump */
2839
        /* if two jumps are inserted, F goes to second one */
2840
382k
        dst->jf = extrajmps;
2841
382k
        extrajmps++;
2842
382k
        dst[extrajmps].code = BPF_JMP|BPF_JA;
2843
382k
        dst[extrajmps].k = off - extrajmps;
2844
382k
    }
2845
2.43M
    else
2846
2.43M
        dst->jf = (u_char)off;
2847
2.82M
  }
2848
2.84M
  return (1);
2849
2.85M
}
2850
2851
2852
/*
2853
 * Convert flowgraph intermediate representation to the
2854
 * BPF array representation.  Set *lenp to the number of instructions.
2855
 *
2856
 * This routine does *NOT* leak the memory pointed to by fp.  It *must
2857
 * not* do free(fp) before returning fp; doing so would make no sense,
2858
 * as the BPF array pointed to by the return value of icode_to_fcode()
2859
 * must be valid - it's being returned for use in a bpf_program structure.
2860
 *
2861
 * If it appears that icode_to_fcode() is leaking, the problem is that
2862
 * the program using pcap_compile() is failing to free the memory in
2863
 * the BPF program when it's done - the leak is in the program, not in
2864
 * the routine that happens to be allocating the memory.  (By analogy, if
2865
 * a program calls fopen() without ever calling fclose() on the FILE *,
2866
 * it will leak the FILE structure; the leak is not in fopen(), it's in
2867
 * the program.)  Change the program to use pcap_freecode() when it's
2868
 * done with the filter program.  See the pcap man page.
2869
 */
2870
struct bpf_insn *
2871
icode_to_fcode(struct icode *ic, struct block *root, u_int *lenp,
2872
    char *errbuf)
2873
7.59k
{
2874
7.59k
  u_int n;
2875
7.59k
  struct bpf_insn *fp;
2876
7.59k
  conv_state_t conv_state;
2877
2878
7.59k
  conv_state.fstart = NULL;
2879
7.59k
  conv_state.errbuf = errbuf;
2880
7.59k
  if (setjmp(conv_state.top_ctx) != 0) {
2881
0
    free(conv_state.fstart);
2882
0
    return NULL;
2883
0
  }
2884
2885
  /*
2886
   * Loop doing convert_code_r() until no branches remain
2887
   * with too-large offsets.
2888
   */
2889
15.6k
  for (;;) {
2890
15.6k
      unMarkAll(ic);
2891
15.6k
      n = *lenp = count_stmts(ic, root);
2892
2893
15.6k
      fp = (struct bpf_insn *)malloc(sizeof(*fp) * n);
2894
15.6k
      if (fp == NULL) {
2895
0
    (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2896
0
        "malloc");
2897
0
    return NULL;
2898
0
      }
2899
15.6k
      memset((char *)fp, 0, sizeof(*fp) * n);
2900
15.6k
      conv_state.fstart = fp;
2901
15.6k
      conv_state.ftail = fp + n;
2902
2903
15.6k
      unMarkAll(ic);
2904
15.6k
      if (convert_code_r(&conv_state, ic, root))
2905
7.59k
    break;
2906
8.06k
      free(fp);
2907
8.06k
  }
2908
2909
7.59k
  return fp;
2910
7.59k
}
2911
2912
/*
2913
 * For iconv_to_fconv() errors.
2914
 */
2915
static void PCAP_NORETURN
2916
conv_error(conv_state_t *conv_state, const char *fmt, ...)
2917
0
{
2918
0
  va_list ap;
2919
2920
0
  va_start(ap, fmt);
2921
0
  (void)vsnprintf(conv_state->errbuf,
2922
0
      PCAP_ERRBUF_SIZE, fmt, ap);
2923
0
  va_end(ap);
2924
0
  longjmp(conv_state->top_ctx, 1);
2925
  /* NOTREACHED */
2926
#ifdef _AIX
2927
  PCAP_UNREACHABLE
2928
#endif /* _AIX */
2929
0
}
2930
2931
/*
2932
 * Make a copy of a BPF program and put it in the "fcode" member of
2933
 * a "pcap_t".
2934
 *
2935
 * If we fail to allocate memory for the copy, fill in the "errbuf"
2936
 * member of the "pcap_t" with an error message, and return -1;
2937
 * otherwise, return 0.
2938
 */
2939
int
2940
pcapint_install_bpf_program(pcap_t *p, struct bpf_program *fp)
2941
0
{
2942
0
  size_t prog_size;
2943
2944
  /*
2945
   * Validate the program.
2946
   */
2947
0
  if (!pcapint_validate_filter(fp->bf_insns, fp->bf_len)) {
2948
0
    snprintf(p->errbuf, sizeof(p->errbuf),
2949
0
      "BPF program is not valid");
2950
0
    return (-1);
2951
0
  }
2952
2953
  /*
2954
   * Free up any already installed program.
2955
   */
2956
0
  pcap_freecode(&p->fcode);
2957
2958
0
  prog_size = sizeof(*fp->bf_insns) * fp->bf_len;
2959
0
  p->fcode.bf_len = fp->bf_len;
2960
0
  p->fcode.bf_insns = (struct bpf_insn *)malloc(prog_size);
2961
0
  if (p->fcode.bf_insns == NULL) {
2962
0
    pcapint_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
2963
0
        errno, "malloc");
2964
0
    return (-1);
2965
0
  }
2966
0
  memcpy(p->fcode.bf_insns, fp->bf_insns, prog_size);
2967
0
  return (0);
2968
0
}
2969
2970
#ifdef BDEBUG
2971
static void
2972
dot_dump_node(struct icode *ic, struct block *block, struct bpf_program *prog,
2973
    FILE *out)
2974
{
2975
  int icount, noffset;
2976
  int i;
2977
2978
  if (block == NULL || isMarked(ic, block))
2979
    return;
2980
  Mark(ic, block);
2981
2982
  icount = slength(block->stmts) + 1 + block->longjt + block->longjf;
2983
  noffset = min(block->offset + icount, (int)prog->bf_len);
2984
2985
  fprintf(out, "\tblock%u [shape=ellipse, id=\"block-%u\" label=\"BLOCK%u\\n", block->id, block->id, block->id);
2986
  for (i = block->offset; i < noffset; i++) {
2987
    fprintf(out, "\\n%s", bpf_image(prog->bf_insns + i, i));
2988
  }
2989
  fprintf(out, "\" tooltip=\"");
2990
  for (i = 0; i < BPF_MEMWORDS; i++)
2991
    if (block->val[i] != VAL_UNKNOWN)
2992
      fprintf(out, "val[%d]=%d ", i, block->val[i]);
2993
  fprintf(out, "val[A]=%d ", block->val[A_ATOM]);
2994
  fprintf(out, "val[X]=%d", block->val[X_ATOM]);
2995
  fprintf(out, "\"");
2996
  if (JT(block) == NULL)
2997
    fprintf(out, ", peripheries=2");
2998
  fprintf(out, "];\n");
2999
3000
  dot_dump_node(ic, JT(block), prog, out);
3001
  dot_dump_node(ic, JF(block), prog, out);
3002
}
3003
3004
static void
3005
dot_dump_edge(struct icode *ic, struct block *block, FILE *out)
3006
{
3007
  if (block == NULL || isMarked(ic, block))
3008
    return;
3009
  Mark(ic, block);
3010
3011
  if (JT(block)) {
3012
    fprintf(out, "\t\"block%u\":se -> \"block%u\":n [label=\"T\"]; \n",
3013
        block->id, JT(block)->id);
3014
    fprintf(out, "\t\"block%u\":sw -> \"block%u\":n [label=\"F\"]; \n",
3015
         block->id, JF(block)->id);
3016
  }
3017
  dot_dump_edge(ic, JT(block), out);
3018
  dot_dump_edge(ic, JF(block), out);
3019
}
3020
3021
/* Output the block CFG using graphviz/DOT language
3022
 * In the CFG, block's code, value index for each registers at EXIT,
3023
 * and the jump relationship is show.
3024
 *
3025
 * example DOT for BPF `ip src host 1.1.1.1' is:
3026
    digraph BPF {
3027
  block0 [shape=ellipse, id="block-0" label="BLOCK0\n\n(000) ldh      [12]\n(001) jeq      #0x800           jt 2  jf 5" tooltip="val[A]=0 val[X]=0"];
3028
  block1 [shape=ellipse, id="block-1" label="BLOCK1\n\n(002) ld       [26]\n(003) jeq      #0x1010101       jt 4  jf 5" tooltip="val[A]=0 val[X]=0"];
3029
  block2 [shape=ellipse, id="block-2" label="BLOCK2\n\n(004) ret      #68" tooltip="val[A]=0 val[X]=0", peripheries=2];
3030
  block3 [shape=ellipse, id="block-3" label="BLOCK3\n\n(005) ret      #0" tooltip="val[A]=0 val[X]=0", peripheries=2];
3031
  "block0":se -> "block1":n [label="T"];
3032
  "block0":sw -> "block3":n [label="F"];
3033
  "block1":se -> "block2":n [label="T"];
3034
  "block1":sw -> "block3":n [label="F"];
3035
    }
3036
 *
3037
 *  After install graphviz on https://www.graphviz.org/, save it as bpf.dot
3038
 *  and run `dot -Tpng -O bpf.dot' to draw the graph.
3039
 */
3040
static int
3041
dot_dump(struct icode *ic, char *errbuf)
3042
{
3043
  struct bpf_program f;
3044
  FILE *out = stdout;
3045
3046
  memset(bids, 0, sizeof bids);
3047
  f.bf_insns = icode_to_fcode(ic, ic->root, &f.bf_len, errbuf);
3048
  if (f.bf_insns == NULL)
3049
    return -1;
3050
3051
  fprintf(out, "digraph BPF {\n");
3052
  unMarkAll(ic);
3053
  dot_dump_node(ic, ic->root, &f, out);
3054
  unMarkAll(ic);
3055
  dot_dump_edge(ic, ic->root, out);
3056
  fprintf(out, "}\n");
3057
3058
  free((char *)f.bf_insns);
3059
  return 0;
3060
}
3061
3062
static int
3063
plain_dump(struct icode *ic, char *errbuf)
3064
{
3065
  struct bpf_program f;
3066
3067
  memset(bids, 0, sizeof bids);
3068
  f.bf_insns = icode_to_fcode(ic, ic->root, &f.bf_len, errbuf);
3069
  if (f.bf_insns == NULL)
3070
    return -1;
3071
  bpf_dump(&f, 1);
3072
  putchar('\n');
3073
  free((char *)f.bf_insns);
3074
  return 0;
3075
}
3076
3077
static void
3078
opt_dump(opt_state_t *opt_state, struct icode *ic)
3079
{
3080
  int status;
3081
  char errbuf[PCAP_ERRBUF_SIZE];
3082
3083
  /*
3084
   * If the CFG, in DOT format, is requested, output it rather than
3085
   * the code that would be generated from that graph.
3086
   */
3087
  if (pcap_print_dot_graph)
3088
    status = dot_dump(ic, errbuf);
3089
  else
3090
    status = plain_dump(ic, errbuf);
3091
  if (status == -1)
3092
    opt_error(opt_state, "%s: icode_to_fcode failed: %s", __func__, errbuf);
3093
}
3094
#endif