summary refs log tree commit diff
path: root/src/librustc/middle/dataflow.rs
blob: ac18a9b76cf9a5a71172d6e07088d223e3ecb593 (plain)
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.


/*!
 * A module for propagating forward dataflow information. The analysis
 * assumes that the items to be propagated can be represented as bits
 * and thus uses bitvectors. Your job is simply to specify the so-called
 * GEN and KILL bits for each expression.
 */


use std::cast;
use std::io;
use std::uint;
use std::vec;
use std::hashmap::HashMap;
use syntax::ast;
use syntax::ast_util;
use syntax::ast_util::id_range;
use syntax::print::{pp, pprust};
use middle::ty;
use middle::typeck;
use util::ppaux::Repr;

pub struct DataFlowContext<O> {
    priv tcx: ty::ctxt,
    priv method_map: typeck::method_map,

    /// the data flow operator
    priv oper: O,

    /// number of bits to propagate per id
    priv bits_per_id: uint,

    /// number of words we will use to store bits_per_id.
    /// equal to bits_per_id/uint::bits rounded up.
    priv words_per_id: uint,

    // mapping from node to bitset index.
    priv nodeid_to_bitset: HashMap<ast::node_id,uint>,

    // Bit sets per id.  The following three fields (`gens`, `kills`,
    // and `on_entry`) all have the same structure. For each id in
    // `id_range`, there is a range of words equal to `words_per_id`.
    // So, to access the bits for any given id, you take a slice of
    // the full vector (see the method `compute_id_range()`).

    /// bits generated as we exit the scope `id`. Updated by `add_gen()`.
    priv gens: ~[uint],

    /// bits killed as we exit the scope `id`. Updated by `add_kill()`.
    priv kills: ~[uint],

    /// bits that are valid on entry to the scope `id`. Updated by
    /// `propagate()`.
    priv on_entry: ~[uint]
}

/// Parameterization for the precise form of data flow that is used.
pub trait DataFlowOperator {
    /// Specifies the initial value for each bit in the `on_entry` set
    fn initial_value(&self) -> bool;

    /// Joins two predecessor bits together, typically either `|` or `&`
    fn join(&self, succ: uint, pred: uint) -> uint;

    /// True if we should propagate through closures
    fn walk_closures(&self) -> bool;
}

struct PropagationContext<'self, O> {
    dfcx: &'self mut DataFlowContext<O>,
    changed: bool
}

#[deriving(Eq)]
enum LoopKind {
    /// A `while` or `loop` loop
    TrueLoop,

    /// A `for` "loop" (i.e., really a func call where `break`, `return`,
    /// and `loop` all essentially perform an early return from the closure)
    ForLoop
}

struct LoopScope<'self> {
    loop_id: ast::node_id,
    loop_kind: LoopKind,
    break_bits: ~[uint]
}

impl<O:DataFlowOperator> DataFlowContext<O> {
    pub fn new(tcx: ty::ctxt,
               method_map: typeck::method_map,
               oper: O,
               id_range: id_range,
               bits_per_id: uint) -> DataFlowContext<O> {
        let words_per_id = (bits_per_id + uint::bits - 1) / uint::bits;

        debug!("DataFlowContext::new(id_range=%?, bits_per_id=%?, words_per_id=%?)",
               id_range, bits_per_id, words_per_id);

        let gens = ~[];
        let kills = ~[];
        let on_entry = ~[];

        DataFlowContext {
            tcx: tcx,
            method_map: method_map,
            words_per_id: words_per_id,
            nodeid_to_bitset: HashMap::new(),
            bits_per_id: bits_per_id,
            oper: oper,
            gens: gens,
            kills: kills,
            on_entry: on_entry
        }
    }

    pub fn add_gen(&mut self, id: ast::node_id, bit: uint) {
        //! Indicates that `id` generates `bit`

        debug!("add_gen(id=%?, bit=%?)", id, bit);
        let (start, end) = self.compute_id_range(id);
        {
            let gens = self.gens.mut_slice(start, end);
            set_bit(gens, bit);
        }
    }

    pub fn add_kill(&mut self, id: ast::node_id, bit: uint) {
        //! Indicates that `id` kills `bit`

        debug!("add_kill(id=%?, bit=%?)", id, bit);
        let (start, end) = self.compute_id_range(id);
        {
            let kills = self.kills.mut_slice(start, end);
            set_bit(kills, bit);
        }
    }

    fn apply_gen_kill(&mut self, id: ast::node_id, bits: &mut [uint]) {
        //! Applies the gen and kill sets for `id` to `bits`

        debug!("apply_gen_kill(id=%?, bits=%s) [before]",
               id, mut_bits_to_str(bits));
        let (start, end) = self.compute_id_range(id);
        let gens = self.gens.slice(start, end);
        bitwise(bits, gens, |a, b| a | b);
        let kills = self.kills.slice(start, end);
        bitwise(bits, kills, |a, b| a & !b);

        debug!("apply_gen_kill(id=%?, bits=%s) [after]",
               id, mut_bits_to_str(bits));
    }

    fn apply_kill(&mut self, id: ast::node_id, bits: &mut [uint]) {
        debug!("apply_kill(id=%?, bits=%s) [before]",
               id, mut_bits_to_str(bits));
        let (start, end) = self.compute_id_range(id);
        let kills = self.kills.slice(start, end);
        bitwise(bits, kills, |a, b| a & !b);
        debug!("apply_kill(id=%?, bits=%s) [after]",
               id, mut_bits_to_str(bits));
    }

    fn compute_id_range_frozen(&self, id: ast::node_id) -> (uint, uint) {
        let n = *self.nodeid_to_bitset.get(&id);
        let start = n * self.words_per_id;
        let end = start + self.words_per_id;
        (start, end)
    }

    fn compute_id_range(&mut self, id: ast::node_id) -> (uint, uint) {
        let mut expanded = false;
        let len = self.nodeid_to_bitset.len();
        let n = do self.nodeid_to_bitset.find_or_insert_with(id) |_| {
            expanded = true;
            len
        };
        if expanded {
            let entry = if self.oper.initial_value() { uint::max_value } else {0};
            for self.words_per_id.times {
                self.gens.push(0);
                self.kills.push(0);
                self.on_entry.push(entry);
            }
        }
        let start = *n * self.words_per_id;
        let end = start + self.words_per_id;

        assert!(start < self.gens.len());
        assert!(end <= self.gens.len());
        assert!(self.gens.len() == self.kills.len());
        assert!(self.gens.len() == self.on_entry.len());

        (start, end)
    }


    pub fn each_bit_on_entry_frozen(&self,
                                    id: ast::node_id,
                                    f: &fn(uint) -> bool) -> bool {
        //! Iterates through each bit that is set on entry to `id`.
        //! Only useful after `propagate()` has been called.
        if !self.nodeid_to_bitset.contains_key(&id) {
            return true;
        }
        let (start, end) = self.compute_id_range_frozen(id);
        let on_entry = self.on_entry.slice(start, end);
        debug!("each_bit_on_entry_frozen(id=%?, on_entry=%s)",
               id, bits_to_str(on_entry));
        self.each_bit(on_entry, f)
    }

    pub fn each_bit_on_entry(&mut self,
                             id: ast::node_id,
                             f: &fn(uint) -> bool) -> bool {
        //! Iterates through each bit that is set on entry to `id`.
        //! Only useful after `propagate()` has been called.

        let (start, end) = self.compute_id_range(id);
        let on_entry = self.on_entry.slice(start, end);
        debug!("each_bit_on_entry(id=%?, on_entry=%s)",
               id, bits_to_str(on_entry));
        self.each_bit(on_entry, f)
    }

    pub fn each_gen_bit(&mut self,
                        id: ast::node_id,
                        f: &fn(uint) -> bool) -> bool {
        //! Iterates through each bit in the gen set for `id`.

        let (start, end) = self.compute_id_range(id);
        let gens = self.gens.slice(start, end);
        debug!("each_gen_bit(id=%?, gens=%s)",
               id, bits_to_str(gens));
        self.each_bit(gens, f)
    }

    pub fn each_gen_bit_frozen(&self,
                               id: ast::node_id,
                               f: &fn(uint) -> bool) -> bool {
        //! Iterates through each bit in the gen set for `id`.
        if !self.nodeid_to_bitset.contains_key(&id) {
            return true;
        }
        let (start, end) = self.compute_id_range_frozen(id);
        let gens = self.gens.slice(start, end);
        debug!("each_gen_bit(id=%?, gens=%s)",
               id, bits_to_str(gens));
        self.each_bit(gens, f)
    }

    fn each_bit(&self,
                words: &[uint],
                f: &fn(uint) -> bool) -> bool {
        //! Helper for iterating over the bits in a bit set.

        for words.iter().enumerate().advance |(word_index, &word)| {
            if word != 0 {
                let base_index = word_index * uint::bits;
                for uint::range(0, uint::bits) |offset| {
                    let bit = 1 << offset;
                    if (word & bit) != 0 {
                        // NB: we round up the total number of bits
                        // that we store in any given bit set so that
                        // it is an even multiple of uint::bits.  This
                        // means that there may be some stray bits at
                        // the end that do not correspond to any
                        // actual value.  So before we callback, check
                        // whether the bit_index is greater than the
                        // actual value the user specified and stop
                        // iterating if so.
                        let bit_index = base_index + offset;
                        if bit_index >= self.bits_per_id {
                            return true;
                        } else if !f(bit_index) {
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }
}

impl<O:DataFlowOperator+Copy+'static> DataFlowContext<O> {
//                      ^^^^^^^^^^^^ only needed for pretty printing
    pub fn propagate(&mut self, blk: &ast::blk) {
        //! Performs the data flow analysis.

        if self.bits_per_id == 0 {
            // Optimize the surprisingly common degenerate case.
            return;
        }

        let mut propcx = PropagationContext {
            dfcx: self,
            changed: true
        };

        let mut temp = vec::from_elem(self.words_per_id, 0);
        let mut loop_scopes = ~[];

        while propcx.changed {
            propcx.changed = false;
            propcx.reset(temp);
            propcx.walk_block(blk, temp, &mut loop_scopes);
        }

        debug!("Dataflow result:");
        debug!("%s", {
            let this = @copy *self;
            this.pretty_print_to(io::stderr(), blk);
            ""
        });
    }

    fn pretty_print_to(@self, wr: @io::Writer, blk: &ast::blk) {
        let pre: @fn(pprust::ann_node) = |node| {
            let (ps, id) = match node {
                pprust::node_expr(ps, expr) => (ps, expr.id),
                pprust::node_block(ps, blk) => (ps, blk.node.id),
                pprust::node_item(ps, _) => (ps, 0),
                pprust::node_pat(ps, pat) => (ps, pat.id)
            };

            if self.nodeid_to_bitset.contains_key(&id) {
                let (start, end) = self.compute_id_range_frozen(id);
                let on_entry = self.on_entry.slice(start, end);
                let entry_str = bits_to_str(on_entry);

                let gens = self.gens.slice(start, end);
                let gens_str = if gens.iter().any_(|&u| u != 0) {
                    fmt!(" gen: %s", bits_to_str(gens))
                } else {
                    ~""
                };

                let kills = self.kills.slice(start, end);
                let kills_str = if kills.iter().any_(|&u| u != 0) {
                    fmt!(" kill: %s", bits_to_str(kills))
                } else {
                    ~""
                };

                let comment_str = fmt!("id %d: %s%s%s",
                                       id, entry_str, gens_str, kills_str);
                pprust::synth_comment(ps, comment_str);
                pp::space(ps.s);
            }
        };

        let post: @fn(pprust::ann_node) = |_| {
        };

        let ps = pprust::rust_printer_annotated(
            wr, self.tcx.sess.intr(),
            pprust::pp_ann {pre:pre, post:post});
        pprust::cbox(ps, pprust::indent_unit);
        pprust::ibox(ps, 0u);
        pprust::print_block(ps, blk);
        pp::eof(ps.s);
    }
}

impl<'self, O:DataFlowOperator> PropagationContext<'self, O> {
    fn tcx(&self) -> ty::ctxt {
        self.dfcx.tcx
    }

    fn walk_block(&mut self,
                  blk: &ast::blk,
                  in_out: &mut [uint],
                  loop_scopes: &mut ~[LoopScope]) {
        debug!("DataFlowContext::walk_block(blk.node.id=%?, in_out=%s)",
               blk.node.id, bits_to_str(reslice(in_out)));

        self.merge_with_entry_set(blk.node.id, in_out);

        for blk.node.stmts.iter().advance |&stmt| {
            self.walk_stmt(stmt, in_out, loop_scopes);
        }

        self.walk_opt_expr(blk.node.expr, in_out, loop_scopes);

        self.dfcx.apply_gen_kill(blk.node.id, in_out);
    }

    fn walk_stmt(&mut self,
                 stmt: @ast::stmt,
                 in_out: &mut [uint],
                 loop_scopes: &mut ~[LoopScope]) {
        match stmt.node {
            ast::stmt_decl(decl, _) => {
                self.walk_decl(decl, in_out, loop_scopes);
            }

            ast::stmt_expr(expr, _) | ast::stmt_semi(expr, _) => {
                self.walk_expr(expr, in_out, loop_scopes);
            }

            ast::stmt_mac(*) => {
                self.tcx().sess.span_bug(stmt.span, "unexpanded macro");
            }
        }
    }

    fn walk_decl(&mut self,
                 decl: @ast::decl,
                 in_out: &mut [uint],
                 loop_scopes: &mut ~[LoopScope]) {
        match decl.node {
            ast::decl_local(local) => {
                self.walk_pat(local.node.pat, in_out, loop_scopes);
                self.walk_opt_expr(local.node.init, in_out, loop_scopes);
            }

            ast::decl_item(_) => {}
        }
    }

    fn walk_expr(&mut self,
                 expr: @ast::expr,
                 in_out: &mut [uint],
                 loop_scopes: &mut ~[LoopScope]) {
        debug!("DataFlowContext::walk_expr(expr=%s, in_out=%s)",
               expr.repr(self.dfcx.tcx), bits_to_str(reslice(in_out)));

        self.merge_with_entry_set(expr.id, in_out);

        match expr.node {
            ast::expr_fn_block(ref decl, ref body) => {
                if self.dfcx.oper.walk_closures() {
                    // In the absence of once fns, we must assume that
                    // every function body will execute more than
                    // once. Thus we treat every function body like a
                    // loop.
                    //
                    // What is subtle and a bit tricky, also, is how
                    // to deal with the "output" bits---that is, what
                    // do we consider to be the successor of a
                    // function body, given that it could be called
                    // from any point within its lifetime? What we do
                    // is to add their effects immediately as of the
                    // point of creation. Of course we have to ensure
                    // that this is sound for the analyses which make
                    // use of dataflow.
                    //
                    // In the case of the initedness checker (which
                    // does not currently use dataflow, but I hope to
                    // convert at some point), we will simply not walk
                    // closures at all, so it's a moot point.
                    //
                    // In the case of the borrow checker, this means
                    // the loans which would be created by calling a
                    // function come into effect immediately when the
                    // function is created. This is guaranteed to be
                    // earlier than the point at which the loan
                    // actually comes into scope (which is the point
                    // at which the closure is *called*). Because
                    // loans persist until the scope of the loans is
                    // exited, it is always a safe approximation to
                    // have a loan begin earlier than it actually will
                    // at runtime, so this should be sound.
                    //
                    // We stil have to be careful in the region
                    // checker and borrow checker to treat function
                    // bodies like loops, which implies some
                    // limitations. For example, a closure cannot root
                    // a managed box for longer than its body.
                    //
                    // General control flow looks like this:
                    //
                    //  +- (expr) <----------+
                    //  |    |               |
                    //  |    v               |
                    //  |  (body) -----------+--> (exit)
                    //  |    |               |
                    //  |    + (break/loop) -+
                    //  |                    |
                    //  +--------------------+
                    //
                    // This is a bit more conservative than a loop.
                    // Note that we must assume that even after a
                    // `break` occurs (e.g., in a `for` loop) that the
                    // closure may be reinvoked.
                    //
                    // One difference from other loops is that `loop`
                    // and `break` statements which target a closure
                    // both simply add to the `break_bits`.

                    // func_bits represents the state when the function
                    // returns
                    let mut func_bits = reslice(in_out).to_owned();

                    loop_scopes.push(LoopScope {
                        loop_id: expr.id,
                        loop_kind: ForLoop,
                        break_bits: reslice(in_out).to_owned()
                    });
                    for decl.inputs.iter().advance |input| {
                        self.walk_pat(input.pat, func_bits, loop_scopes);
                    }
                    self.walk_block(body, func_bits, loop_scopes);

                    // add the bits from any early return via `break`,
                    // `continue`, or `return` into `func_bits`
                    let loop_scope = loop_scopes.pop();
                    join_bits(&self.dfcx.oper, loop_scope.break_bits, func_bits);

                    // add `func_bits` to the entry bits for `expr`,
                    // since we must assume the function may be called
                    // more than once
                    self.add_to_entry_set(expr.id, reslice(func_bits));

                    // the final exit bits include whatever was present
                    // in the original, joined with the bits from the function
                    join_bits(&self.dfcx.oper, func_bits, in_out);
                }
            }

            ast::expr_if(cond, ref then, els) => {
                //
                //     (cond)
                //       |
                //       v
                //      ( )
                //     /   \
                //    |     |
                //    v     v
                //  (then)(els)
                //    |     |
                //    v     v
                //   (  succ  )
                //
                self.walk_expr(cond, in_out, loop_scopes);

                let mut then_bits = reslice(in_out).to_owned();
                self.walk_block(then, then_bits, loop_scopes);

                self.walk_opt_expr(els, in_out, loop_scopes);
                join_bits(&self.dfcx.oper, then_bits, in_out);
            }

            ast::expr_while(cond, ref blk) => {
                //
                //     (expr) <--+
                //       |       |
                //       v       |
                //  +--(cond)    |
                //  |    |       |
                //  |    v       |
                //  v  (blk) ----+
                //       |
                //    <--+ (break)
                //

                self.walk_expr(cond, in_out, loop_scopes);

                let mut body_bits = reslice(in_out).to_owned();
                loop_scopes.push(LoopScope {
                    loop_id: expr.id,
                    loop_kind: TrueLoop,
                    break_bits: reslice(in_out).to_owned()
                });
                self.walk_block(blk, body_bits, loop_scopes);
                self.add_to_entry_set(expr.id, body_bits);
                let new_loop_scope = loop_scopes.pop();
                copy_bits(new_loop_scope.break_bits, in_out);
            }

            ast::expr_loop(ref blk, _) => {
                //
                //     (expr) <--+
                //       |       |
                //       v       |
                //     (blk) ----+
                //       |
                //    <--+ (break)
                //

                let mut body_bits = reslice(in_out).to_owned();
                self.reset(in_out);
                loop_scopes.push(LoopScope {
                    loop_id: expr.id,
                    loop_kind: TrueLoop,
                    break_bits: reslice(in_out).to_owned()
                });
                self.walk_block(blk, body_bits, loop_scopes);
                self.add_to_entry_set(expr.id, body_bits);

                let new_loop_scope = loop_scopes.pop();
                assert_eq!(new_loop_scope.loop_id, expr.id);
                copy_bits(new_loop_scope.break_bits, in_out);
            }

            ast::expr_match(discr, ref arms) => {
                //
                //    (discr)
                //     / | \
                //    |  |  |
                //    v  v  v
                //   (..arms..)
                //    |  |  |
                //    v  v  v
                //   (  succ  )
                //
                //
                self.walk_expr(discr, in_out, loop_scopes);

                let mut guards = reslice(in_out).to_owned();

                // We know that exactly one arm will be taken, so we
                // can start out with a blank slate and just union
                // together the bits from each arm:
                self.reset(in_out);

                for arms.iter().advance |arm| {
                    // in_out reflects the discr and all guards to date
                    self.walk_opt_expr(arm.guard, guards, loop_scopes);

                    // determine the bits for the body and then union
                    // them into `in_out`, which reflects all bodies to date
                    let mut body = reslice(guards).to_owned();
                    self.walk_pat_alternatives(arm.pats, body, loop_scopes);
                    self.walk_block(&arm.body, body, loop_scopes);
                    join_bits(&self.dfcx.oper, body, in_out);
                }
            }

            ast::expr_ret(o_e) => {
                self.walk_opt_expr(o_e, in_out, loop_scopes);

                // is this a return from a `for`-loop closure?
                match loop_scopes.iter().position_(|s| s.loop_kind == ForLoop) {
                    Some(i) => {
                        // if so, add the in_out bits to the state
                        // upon exit. Remember that we cannot count
                        // upon the `for` loop function not to invoke
                        // the closure again etc.
                        self.break_from_to(expr, &mut loop_scopes[i], in_out);
                    }

                    None => {}
                }

                self.reset(in_out);
            }

            ast::expr_break(label) => {
                let scope = self.find_scope(expr, label, loop_scopes);
                self.break_from_to(expr, scope, in_out);
                self.reset(in_out);
            }

            ast::expr_again(label) => {
                let scope = self.find_scope(expr, label, loop_scopes);

                match scope.loop_kind {
                    TrueLoop => {
                        self.pop_scopes(expr, scope, in_out);
                        self.add_to_entry_set(scope.loop_id, reslice(in_out));
                    }

                    ForLoop => {
                        // If this `loop` construct is looping back to a `for`
                        // loop, then `loop` is really just a return from the
                        // closure. Therefore, we treat it the same as `break`.
                        // See case for `expr_fn_block` for more details.
                        self.break_from_to(expr, scope, in_out);
                    }
                }

                self.reset(in_out);
            }

            ast::expr_assign(l, r) |
            ast::expr_assign_op(_, _, l, r) => {
                self.walk_expr(r, in_out, loop_scopes);
                self.walk_expr(l, in_out, loop_scopes);
            }

            ast::expr_vec(ref exprs, _) => {
                self.walk_exprs(*exprs, in_out, loop_scopes)
            }

            ast::expr_repeat(l, r, _) => {
                self.walk_expr(l, in_out, loop_scopes);
                self.walk_expr(r, in_out, loop_scopes);
            }

            ast::expr_struct(_, ref fields, with_expr) => {
                for fields.iter().advance |field| {
                    self.walk_expr(field.node.expr, in_out, loop_scopes);
                }
                self.walk_opt_expr(with_expr, in_out, loop_scopes);
            }

            ast::expr_call(f, ref args, _) => {
                self.walk_call(f.id, expr.id,
                               f, *args, in_out, loop_scopes);
            }

            ast::expr_method_call(callee_id, rcvr, _, _, ref args, _) => {
                self.walk_call(callee_id, expr.id,
                               rcvr, *args, in_out, loop_scopes);
            }

            ast::expr_index(callee_id, l, r) |
            ast::expr_binary(callee_id, _, l, r) if self.is_method_call(expr) => {
                self.walk_call(callee_id, expr.id,
                               l, [r], in_out, loop_scopes);
            }

            ast::expr_unary(callee_id, _, e) if self.is_method_call(expr) => {
                self.walk_call(callee_id, expr.id,
                               e, [], in_out, loop_scopes);
            }

            ast::expr_tup(ref exprs) => {
                self.walk_exprs(*exprs, in_out, loop_scopes);
            }

            ast::expr_binary(_, op, l, r) if ast_util::lazy_binop(op) => {
                self.walk_expr(l, in_out, loop_scopes);
                let temp = reslice(in_out).to_owned();
                self.walk_expr(r, in_out, loop_scopes);
                join_bits(&self.dfcx.oper, temp, in_out);
            }

            ast::expr_log(l, r) |
            ast::expr_index(_, l, r) |
            ast::expr_binary(_, _, l, r) => {
                self.walk_exprs([l, r], in_out, loop_scopes);
            }

            ast::expr_lit(*) |
            ast::expr_path(*) |
            ast::expr_self => {
            }

            ast::expr_addr_of(_, e) |
            ast::expr_copy(e) |
            ast::expr_loop_body(e) |
            ast::expr_do_body(e) |
            ast::expr_cast(e, _) |
            ast::expr_unary(_, _, e) |
            ast::expr_paren(e) |
            ast::expr_vstore(e, _) |
            ast::expr_field(e, _, _) => {
                self.walk_expr(e, in_out, loop_scopes);
            }

            ast::expr_inline_asm(ref inline_asm) => {
                for inline_asm.inputs.iter().advance |&(_, expr)| {
                    self.walk_expr(expr, in_out, loop_scopes);
                }
                for inline_asm.outputs.iter().advance |&(_, expr)| {
                    self.walk_expr(expr, in_out, loop_scopes);
                }
            }

            ast::expr_block(ref blk) => {
                self.walk_block(blk, in_out, loop_scopes);
            }

            ast::expr_mac(*) => {
                self.tcx().sess.span_bug(expr.span, "unexpanded macro");
            }
        }

        self.dfcx.apply_gen_kill(expr.id, in_out);
    }

    fn pop_scopes(&mut self,
                  from_expr: @ast::expr,
                  to_scope: &mut LoopScope,
                  in_out: &mut [uint]) {
        //! Whenever you have a `break` or a `loop` statement, flow
        //! exits through any number of enclosing scopes on its
        //! way to the new destination. This function applies the kill
        //! sets of those enclosing scopes to `in_out` (those kill sets
        //! concern items that are going out of scope).

        let tcx = self.tcx();
        let region_maps = tcx.region_maps;

        debug!("pop_scopes(from_expr=%s, to_scope=%?, in_out=%s)",
               from_expr.repr(tcx), to_scope.loop_id,
               bits_to_str(reslice(in_out)));

        let mut id = from_expr.id;
        while id != to_scope.loop_id {
            self.dfcx.apply_kill(id, in_out);

            match region_maps.opt_encl_scope(id) {
                Some(i) => { id = i; }
                None => {
                    tcx.sess.span_bug(
                        from_expr.span,
                        fmt!("pop_scopes(from_expr=%s, to_scope=%?) \
                              to_scope does not enclose from_expr",
                             from_expr.repr(tcx), to_scope.loop_id));
                }
            }
        }
    }

    fn break_from_to(&mut self,
                     from_expr: @ast::expr,
                     to_scope: &mut LoopScope,
                     in_out: &mut [uint]) {
        self.pop_scopes(from_expr, to_scope, in_out);
        self.dfcx.apply_kill(from_expr.id, in_out);
        join_bits(&self.dfcx.oper, reslice(in_out), to_scope.break_bits);
        debug!("break_from_to(from_expr=%s, to_scope=%?) final break_bits=%s",
               from_expr.repr(self.tcx()),
               to_scope.loop_id,
               bits_to_str(reslice(in_out)));
    }

    fn walk_exprs(&mut self,
                  exprs: &[@ast::expr],
                  in_out: &mut [uint],
                  loop_scopes: &mut ~[LoopScope]) {
        for exprs.iter().advance |&expr| {
            self.walk_expr(expr, in_out, loop_scopes);
        }
    }

    fn walk_opt_expr(&mut self,
                     opt_expr: Option<@ast::expr>,
                     in_out: &mut [uint],
                     loop_scopes: &mut ~[LoopScope]) {
        for opt_expr.iter().advance |&expr| {
            self.walk_expr(expr, in_out, loop_scopes);
        }
    }

    fn walk_call(&mut self,
                 _callee_id: ast::node_id,
                 call_id: ast::node_id,
                 arg0: @ast::expr,
                 args: &[@ast::expr],
                 in_out: &mut [uint],
                 loop_scopes: &mut ~[LoopScope]) {
        self.walk_expr(arg0, in_out, loop_scopes);
        self.walk_exprs(args, in_out, loop_scopes);

        // FIXME(#6268) nested method calls
        // self.merge_with_entry_set(callee_id, in_out);
        // self.dfcx.apply_gen_kill(callee_id, in_out);

        let return_ty = ty::node_id_to_type(self.tcx(), call_id);
        let fails = ty::type_is_bot(return_ty);
        if fails {
            self.reset(in_out);
        }
    }

    fn walk_pat(&mut self,
                pat: @ast::pat,
                in_out: &mut [uint],
                _loop_scopes: &mut ~[LoopScope]) {
        debug!("DataFlowContext::walk_pat(pat=%s, in_out=%s)",
               pat.repr(self.dfcx.tcx), bits_to_str(reslice(in_out)));

        for ast_util::walk_pat(pat) |p| {
            debug!("  p.id=%? in_out=%s", p.id, bits_to_str(reslice(in_out)));
            self.merge_with_entry_set(p.id, in_out);
            self.dfcx.apply_gen_kill(p.id, in_out);
        }
    }

    fn walk_pat_alternatives(&mut self,
                             pats: &[@ast::pat],
                             in_out: &mut [uint],
                             loop_scopes: &mut ~[LoopScope]) {
        if pats.len() == 1 {
            // Common special case:
            return self.walk_pat(pats[0], in_out, loop_scopes);
        }

        // In the general case, the patterns in `pats` are
        // alternatives, so we must treat this like an N-way select
        // statement.
        let initial_state = reslice(in_out).to_owned();
        for pats.iter().advance |&pat| {
            let mut temp = copy initial_state;
            self.walk_pat(pat, temp, loop_scopes);
            join_bits(&self.dfcx.oper, temp, in_out);
        }
    }

    fn find_scope<'a>(&self,
                      expr: @ast::expr,
                      label: Option<ast::ident>,
                      loop_scopes: &'a mut ~[LoopScope]) -> &'a mut LoopScope {
        let index = match label {
            None => {
                let len = loop_scopes.len();
                len - 1
            }

            Some(_) => {
                match self.tcx().def_map.find(&expr.id) {
                    Some(&ast::def_label(loop_id)) => {
                        match loop_scopes.iter().position_(|l| l.loop_id == loop_id) {
                            Some(i) => i,
                            None => {
                                self.tcx().sess.span_bug(
                                    expr.span,
                                    fmt!("No loop scope for id %?", loop_id));
                            }
                        }
                    }

                    r => {
                        self.tcx().sess.span_bug(
                            expr.span,
                            fmt!("Bad entry `%?` in def_map for label", r));
                    }
                }
            }
        };

        &mut loop_scopes[index]
    }

    fn is_method_call(&self, expr: @ast::expr) -> bool {
        self.dfcx.method_map.contains_key(&expr.id)
    }

    fn reset(&mut self, bits: &mut [uint]) {
        let e = if self.dfcx.oper.initial_value() {uint::max_value} else {0};
        for bits.mut_iter().advance |b| { *b = e; }
    }

    fn add_to_entry_set(&mut self, id: ast::node_id, pred_bits: &[uint]) {
        debug!("add_to_entry_set(id=%?, pred_bits=%s)",
               id, bits_to_str(pred_bits));
        let (start, end) = self.dfcx.compute_id_range(id);
        let changed = { // FIXME(#5074) awkward construction
            let on_entry = self.dfcx.on_entry.mut_slice(start, end);
            join_bits(&self.dfcx.oper, pred_bits, on_entry)
        };
        if changed {
            debug!("changed entry set for %? to %s",
                   id, bits_to_str(self.dfcx.on_entry.slice(start, end)));
            self.changed = true;
        }
    }

    fn merge_with_entry_set(&mut self,
                            id: ast::node_id,
                            pred_bits: &mut [uint]) {
        debug!("merge_with_entry_set(id=%?, pred_bits=%s)",
               id, mut_bits_to_str(pred_bits));
        let (start, end) = self.dfcx.compute_id_range(id);
        let changed = { // FIXME(#5074) awkward construction
            let on_entry = self.dfcx.on_entry.mut_slice(start, end);
            let changed = join_bits(&self.dfcx.oper, reslice(pred_bits), on_entry);
            copy_bits(reslice(on_entry), pred_bits);
            changed
        };
        if changed {
            debug!("changed entry set for %? to %s",
                   id, bits_to_str(self.dfcx.on_entry.slice(start, end)));
            self.changed = true;
        }
    }
}

fn mut_bits_to_str(words: &mut [uint]) -> ~str {
    bits_to_str(reslice(words))
}

fn bits_to_str(words: &[uint]) -> ~str {
    let mut result = ~"";
    let mut sep = '[';

    // Note: this is a little endian printout of bytes.

    for words.iter().advance |&word| {
        let mut v = word;
        for uint::range(0, uint::bytes) |_| {
            result.push_char(sep);
            result.push_str(fmt!("%02x", v & 0xFF));
            v >>= 8;
            sep = '-';
        }
    }
    result.push_char(']');
    return result;
}

fn copy_bits(in_vec: &[uint], out_vec: &mut [uint]) -> bool {
    bitwise(out_vec, in_vec, |_, b| b)
}

fn join_bits<O:DataFlowOperator>(oper: &O,
                                 in_vec: &[uint],
                                 out_vec: &mut [uint]) -> bool {
    bitwise(out_vec, in_vec, |a, b| oper.join(a, b))
}

#[inline]
fn bitwise(out_vec: &mut [uint],
           in_vec: &[uint],
           op: &fn(uint, uint) -> uint) -> bool {
    assert_eq!(out_vec.len(), in_vec.len());
    let mut changed = false;
    for uint::range(0, out_vec.len()) |i| {
        let old_val = out_vec[i];
        let new_val = op(old_val, in_vec[i]);
        out_vec[i] = new_val;
        changed |= (old_val != new_val);
    }
    return changed;
}

fn set_bit(words: &mut [uint], bit: uint) -> bool {
    debug!("set_bit: words=%s bit=%s",
           mut_bits_to_str(words), bit_str(bit));
    let word = bit / uint::bits;
    let bit_in_word = bit % uint::bits;
    let bit_mask = 1 << bit_in_word;
    debug!("word=%u bit_in_word=%u bit_mask=%u", word, bit_in_word, word);
    let oldv = words[word];
    let newv = oldv | bit_mask;
    words[word] = newv;
    oldv != newv
}

fn bit_str(bit: uint) -> ~str {
    let byte = bit >> 8;
    let lobits = 1 << (bit & 0xFF);
    fmt!("[%u:%u-%02x]", bit, byte, lobits)
}

fn reslice<'a>(v: &'a mut [uint]) -> &'a [uint] {
    // bFIXME(#5074) this function should not be necessary at all
    unsafe {
        cast::transmute(v)
    }
}