File: iflib_red.c

package info (click to toggle)
tcng 10b-4
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 3,644 kB
  • sloc: ansic: 19,040; pascal: 4,640; yacc: 2,619; sh: 1,914; perl: 1,546; lex: 772; makefile: 751
file content (579 lines) | stat: -rw-r--r-- 13,759 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
/*
 * iflib_red.c - Normalize and reduce (optimize) an if expression
 *
 * Written 2001 by Werner Almesberger
 * Copyright 2001 EPFL-ICA, Network Robots
 */


#include <stdlib.h>

#include "config.h"
#include "util.h"
#include "registry.h"
#include "error.h"
#include "data.h"
#include "tree.h"
#include "op.h"
#include "iflib.h"


/*
 * @@@ does not handle nested ifs properly
 */


#define BUNDLE_THRESHOLD 2 /* bundle if at least that many common entries */
			   /* MUST be > 1 */


/* --------------------- Normalize boolean expression ---------------------- */


static void bubble_or(DATA *d)
{
    DATA new;

    while (1) {
	SELF_CONTAINED sc;

	if (d->type == dt_none) return;
	if (d->op) {
	    bubble_or(&d->op->a);
	    bubble_or(&d->op->b);
	    bubble_or(&d->op->c);
	}
	if (!d->op || d->op->dsc != &op_logical_and) return;

	sc = self_contained(d->op->a);
	if (sc == sc_yes || sc == sc_no_false) {
	    new = d->op->a;
	    data_destroy(d->op->b);
	    data_destroy_1(*d);
	    *d = new;
	    continue;
	}

	/*
	 * (a || b) && c -> (a && c) || (b && c)
	 *
	 * Exception: if b has a side-effect, this transformation is only
	 * valid if c is self-contained or if a is self-contained or always
	 * true.
	 */
	if (d->op->a.op && d->op->a.op->dsc == &op_logical_or) {
	    sc = self_contained(d->op->a.op->a);
	    if (!side_effect(d->op->a.op->b) ||
	      self_contained(d->op->b) == sc_yes ||
	      sc == sc_yes || sc == sc_no_true) {
		new = op_binary(&op_logical_or,
		  op_binary(&op_logical_and,data_clone(d->op->a.op->a),
		    data_clone(d->op->b)),
		  op_binary(&op_logical_and,data_clone(d->op->a.op->b),
		    data_clone(d->op->b)));
		data_destroy(*d);
		*d = new;
		continue;
	    }
	}

	/* a && (b || c) -> (a && b) || (a && c) */
	if (d->op->b.op && d->op->b.op->dsc == &op_logical_or) {
	    if (action_tree(d->op->b) &&
	      self_contained(d->op->b) == sc_yes)
		break;
		  /* Do NOT normalize actions */
	    new = op_binary(&op_logical_or,
	      op_binary(&op_logical_and,data_clone(d->op->a),
		data_clone(d->op->b.op->a)),
	      op_binary(&op_logical_and,data_clone(d->op->a),
		data_clone(d->op->b.op->b)));
	    data_destroy(*d);
	    *d = new;
	    continue;
	}
	break;
    }
}


static void linearize(DATA *d)
{
    if (d->type == dt_none) return;

    /* (a || b) || c -> a || (b || c)   (idem for &&) */
    while (d->op &&
      (d->op->dsc == &op_logical_or || d->op->dsc == &op_logical_and) &&
      d->op->a.op && d->op->a.op->dsc == d->op->dsc) {
	DATA tmp;

	tmp = d->op->a;
	d->op->a = tmp.op->b;
	tmp.op->b = *d;
	*d = tmp;
    }
    if (d->op) {
	linearize(&d->op->a);
	linearize(&d->op->b);
	linearize(&d->op->c);
    }
}


void iflib_normalize(DATA *d)
{
    bubble_or(d);
    debug_expr("AFTER bubble_or",*d);
    linearize(d);
    debug_expr("AFTER linearize (2)",*d);
}


/* --------------- Eliminate redundant common subexpressions --------------- */


int expr_equal(DATA a,DATA b)
{
    if (a.op) {
	if (!b.op) return 0;
	if (a.op->dsc != b.op->dsc) return 0;
	return expr_equal(a.op->a,b.op->a) && expr_equal(a.op->b,b.op->b) &&
	  expr_equal(a.op->c,b.op->c);
    }
    if (b.op) return 0;
    return data_equal(a,b);
}


static void common_subexpressions(DATA *d)
{
    while (d->op && (d->op->dsc == &op_or || d->op->dsc == &op_and ||
      d->op->dsc == &op_logical_or || d->op->dsc == &op_logical_and)) {
	DATA *walk;
	int again = 0;

	for (walk = &d->op->b; walk->op && walk->op->dsc == d->op->dsc;
	  walk = &walk->op->b) {
	    DATA next;

	    /* a && ... && a && ... -> a && ... && ... */
	    if (expr_equal(d->op->a,walk->op->a)) {
		next = walk->op->b;
		data_destroy(walk->op->a);
		data_destroy_1(*walk);
		*walk = next;
		again = 1;
		break;
	    }

	    /* a && ... && a -> a && ... */
	    if (expr_equal(d->op->a,walk->op->b)) {
		next = walk->op->a;
		data_destroy(walk->op->b);
		data_destroy_1(*walk);
		*walk = next;
		break;
	    }
	}
	if (!again) break;
    }
    if (d->op) {
	common_subexpressions(&d->op->a);
	common_subexpressions(&d->op->b);
	common_subexpressions(&d->op->c);
    }
}


/* ------------------ Bundle common && prefix in || chain ------------------ */

/*
 * (a && b) || (a && c) || d -> (a && (b || c) || d
 *
 * Note: (a && x) expressions must be consecutive, e.g. we can't bundle
 * (a && b) || c || (a && d)  to  (a && (b || d) || c, because shortcut
 * evaluation would be different if a = c = d = 1, b = 0
 *
 * Also, "a" must be a sequence of &&s right at the beginning of
 * the expression, e.g. we can't bundle (a && b && c) || (b && a && c)
 *
 * Note: none of this is really binding. In fact, we could relax the
 * reordering constraints quite a bit it we take into account that they
 * are caused by a) accepting states (i.e. decision), and b) field
 * accessibility. E.g. in the example above, we know that "a" and "b"
 * can each be evaluated without precondition, so they're in fact
 * commutative.
 */

/*
 * First, convert the ||-then-&& structure into a matrix, for easier handling
 */

struct or_row {
    DATA *and;
    int ands;
    DATA **cells;
};

struct matrix {
    int ors;
    struct or_row *rows;
};

static void bundle_make_matrix(DATA *d,struct matrix *m)
{
    DATA *or;
    int i;

    m->ors = 0;
    for (or = d; 1; or = &or->op->b) {
	m->ors++;
	if (!or->op || or->op->dsc != &op_logical_or) break;
    }
    m->rows = alloc(sizeof(struct or_row)*m->ors);
    or = d;
    for (i = 0; i < m->ors-1; i++) {
	m->rows[i].and = &or->op->a;
	or = &or->op->b;
    }
    m->rows[i].and = or;
    for (i = 0; i < m->ors; i++) {
	struct or_row *r = m->rows+i;
	DATA *and;
	int j;

	r->ands = 0;
	for (and = r->and; 1; and = &and->op->b) {
	    r->ands++;
	    if (!and->op || and->op->dsc != &op_logical_and) break;
	}
	r->cells = alloc(sizeof(DATA *)*r->ands);
	and = r->and;
	for (j = 0; j < r->ands-1; j++) {
	    r->cells[j] = &and->op->a;
	    and = &and->op->b;
	}
	r->cells[j] = and;
    }
}


static char bundle_dump_char(DATA d)
{
    if (d.op) {
	if (d.op->dsc == &op_eq) return '=';
	if (d.op->dsc == &op_logical_or) return '|';
	if (d.op->dsc == &op_conform) return 'P';
	if (d.op->dsc == &op_count) return 'P';
	return '?';
    }
    if (d.type == dt_decision) return 'D';
    return 'd';
}


static void bundle_dump_matrix(FILE *file,struct matrix m)
{
    int or;

    if (!debug) return;
    fprintf(file,"----- current matrix -----\n");
    for (or = 0; or < m.ors; or++) {
	int and;

	for (and = 0; and < m.rows[or].ands; and++)
	    putc(bundle_dump_char(*m.rows[or].cells[and]),file);
	putc('\n',file);
    }
    fprintf(file,"----------\n");
}


static void bundle_free_matrix(struct matrix *m)
{
    int i;

    for (i = 0; i < m->ors; i++)
	free(m->rows[i].cells);
    free(m->rows);
}


/*
 * Find best optimization. Actually, this isn't optimal yet. We should also
 * take into account how we could bundle adjacent areas. But this is probably
 * overkill.
 */


static void bundle_find_best(struct matrix *m,int *best_or,int *best_ors,
  int *best_ands)
{
    int first_or;

    *best_ors = *best_ands = 0;
    for (first_or = 0; first_or < m->ors; first_or++) {
	int ors;

	for (ors = 2; first_or+ors <= m->ors; ors++) {
	    int min_ands = -1;
	    int i,j,ands;

	    for (i = first_or; i < first_or+ors; i++)
		if (m->rows[i].ands < min_ands || min_ands == -1)
		    min_ands = m->rows[i].ands;
	    if (ors*min_ands < *best_ors**best_ands) continue;
	    for (ands = 1; ands <= min_ands; ands++) {
		for (i = first_or+1; i < first_or+ors; i++)
		    for (j = 0; j < ands; j++)
			if (!expr_equal(*m->rows[first_or].cells[j],
			  *m->rows[i].cells[j]))
			    goto out;
		if (ors*ands > *best_ors**best_ands) {
		    *best_or = first_or;
		    *best_ors = ors;
		    *best_ands = ands;
		}
	    }
out:
	    ; /* semicolon required for "new" C syntax */
	}
    }
}


/*
 * Build a new tree
 *
 *          |-| ands=2
 * 	    a b c
 * first -> d e f-- ors=2
 *          d e g--
 *          h
 *          i j k
 *
 * becomes
 * (a && b && c) || (d && e && (f || g)) || h || (i && j && k)
 *
 * Note: we data_clone a lot here. This keeps the whole design reasonably
 * simple, but it's bad for performance.
 */


static DATA bundle_ands(struct or_row *r,int from,int ands,DATA add)
{
    DATA tmp = add;
    int j,last = ands == -1 ? r->ands-1 : from+ands-1;

    if (add.type == dt_none) {
	if (last < from) return data_none();
	tmp = data_clone(*r->cells[last]);
    }
    else last++;
    for (j = last-1; j >= from; j--)
	tmp = op_binary(&op_logical_and,data_clone(*r->cells[j]),tmp);
    return tmp;
}


static DATA bundle_ors(struct matrix *m,int from,int ors,int from_ands,
  int ands,DATA add)
{
    DATA tmp = add;
    int i,last = ors == -1 ? m->ors-1 : from+ors-1;

    if (add.type == dt_none) {
	if (last < from) return data_none();
	tmp = bundle_ands(m->rows+last,from_ands,ands,data_none());
    }
    else last++;
    for (i = last-1; i >= from; i--) {
	if (tmp.type == dt_none) break; /* a || ab -> a */
	tmp = op_binary(&op_logical_or,bundle_ands(m->rows+i,from_ands,ands,
	  data_none()),tmp);
    }
    return tmp;
}


static DATA bundle_rebuild(struct matrix *m,int from,int ors,int ands)
{
    DATA d,new;

    new = bundle_ors(m,from,ors,ands,-1,data_none());
    new = bundle_ands(m->rows+from,0,ands,new);
    d = from+ors == m->ors ? new :
      op_binary(&op_logical_or,new,bundle_ors(m,from+ors,-1,0,-1,data_none()));
    if (from) d = bundle_ors(m,0,from,0,-1,d);
    return d;
}


/*
 * Skip all ors
 */


static void bundle(DATA *d)
{
    while (1) {
	struct matrix m;
	int from,ors,ands;
	DATA old = *d;

	debug_expr("BEFORE bundle iteration",*d);
	if (!d->op) return;
	if (d->op->dsc != &op_logical_or) break;
	bundle_make_matrix(d,&m);
	bundle_dump_matrix(stdout,m);
	bundle_find_best(&m,&from,&ors,&ands);
	if (ors*ands < BUNDLE_THRESHOLD) {
	    bundle_free_matrix(&m);
	    break;
	}
	debugf("BEFORE bundle_rebuild (from %d, ors %d, ands %d)\n",from,ors,
	  ands);
	*d = bundle_rebuild(&m,from,ors,ands);
	debug_expr("AFTER bundle_rebuild",*d);
	data_destroy(old);
	bundle_free_matrix(&m);
    }
    bundle(&d->op->a);
    bundle(&d->op->b);
    bundle(&d->op->c);
}


/* ---------- Remove dead branches caused by shortcut evaluation ----------- */


void prune_shortcuts(DATA *d)
{
    DATA old = *d;

    if (!d->op) return;
    prune_shortcuts(&d->op->a);
    prune_shortcuts(&d->op->b);
    prune_shortcuts(&d->op->c);

    /* <class X> || ... -> <class X>  and <class X> && ... -> <class X> */
    if ((d->op->dsc == &op_logical_or || d->op->dsc == &op_logical_and) &&
      d->op->a.type == dt_decision) {
	*d = d->op->a;
	data_destroy(old.op->b);
	data_destroy_1(old);
	return;
    }

    if (d->op->dsc == &op_logical_and) {
	if (!d->op->a.op && d->op->a.type == dt_unum) {
	    /* 0 && X -> 0 */
	    if (!d->op->a.u.unum) {
		*d = data_unum(0);
		data_destroy(old);
		return;
	    }
	    /* 1 && X -> X */
	    if (d->op->a.u.unum) {
		*d = old.op->b;
		data_destroy_1(old);
		return;
	    }
	}
	if (!d->op->b.op && d->op->b.type == dt_unum) {
	    /* X && 0 -> 0, unless X has side-effect */
	    if (!d->op->b.u.unum && !side_effect(d->op->a)) {
		*d = data_unum(0);
		data_destroy(old);
		return;
	    }
	    /* X && 1 -> X */
	    if (d->op->b.u.unum) {
		*d = old.op->a;
		data_destroy_1(old);
		return;
	    }
	}
    }

    if (d->op->dsc == &op_logical_or) {
	if (!d->op->a.op && d->op->a.type == dt_unum) {
	    /* 1 || X -> 1 */
	    if (d->op->a.u.unum) {
		*d = data_unum(1);
		data_destroy(old);
		return;
	    }
	    /* 0 || X -> X */
	    if (!d->op->a.u.unum) {
		*d = old.op->b;
		data_destroy_1(old);
		return;
	    }
	}
	if (!d->op->b.op && d->op->b.type == dt_unum) {
	    /* X || 1 -> 1, unless X has side-effect */
	    if (d->op->b.u.unum && !side_effect(d->op->a)) {
		*d = data_unum(1);
		data_destroy(old);
		return;
	    }
	    /* X || 0 -> X */
	    if (!d->op->b.u.unum) {
		*d = old.op->a;
		data_destroy_1(old);
		return;
	    }
	}
    }
}


/* --------------------- Optimize the "if" expression ---------------------- */


void iflib_reduce(DATA *d)
{
    debug_expr("BEFORE iflib_reduce",*d);
    /*
     * There's a bit white magic going on here.
     *
     * The first round of "prune_shortcuts" eliminates constructs like
     * 1 && class ...  which turns them into action trees, which can then be
     * left alone by bubble_or.
     *
     * The first "linearize" turns expressions of the type
     *  classification && action  which have become
     * (classification && action) && class X  into
     * classification (action && class X)
     *
     * This subtle change means that the action part can be self-contained
     * (that is, if "action" contains an || to filter out "false"), and
     * "bubble_or" doesn't have to break it into pieces to extract the ||s. 
     *
     * This in turn will keep iflib_act.c:push_action from needing to
     * re-arrange the expression even further, in order to bring all actions
     * together again.
     *
     * Since "bubble_or" breaks apart linear structures, and further processing
     * steps expect to find the expression in a linear structure, we have to
     * call "linearize" again after "bubble_or" (both in "iflib_normalize").
     */
    linearize(d);
    debug_expr("AFTER linearize (1)",*d);
    prune_shortcuts(d);
    debug_expr("AFTER prune_shortcuts (1)",*d);
    if (alg_mode || !registry_probe(&optimization_switches,"cse")) {
	iflib_normalize(d);
	return;
    }
    bundle(d);
    debug_expr("AFTER bundle",*d);
    iflib_normalize(d);
    common_subexpressions(d);
    debug_expr("AFTER common_subexpressions",*d);
    bundle(d);
    debug_expr("AFTER bundle",*d);
    prune_shortcuts(d);
    debug_expr("AFTER prune_shortcuts (2)",*d);
}