]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/dataflow.rs
14ba241f62b0f1bfabdb6dd0a94a68eaef0fa1c0
[rust.git] / src / librustc / middle / dataflow.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12 //! A module for propagating forward dataflow information. The analysis
13 //! assumes that the items to be propagated can be represented as bits
14 //! and thus uses bitvectors. Your job is simply to specify the so-called
15 //! GEN and KILL bits for each expression.
16
17 pub use self::EntryOrExit::*;
18
19 use middle::cfg;
20 use middle::cfg::CFGIndex;
21 use middle::ty;
22 use std::io;
23 use std::usize;
24 use syntax::ast;
25 use syntax::ast_util::IdRange;
26 use syntax::print::pp;
27 use util::nodemap::NodeMap;
28 use rustc_front::hir;
29 use rustc_front::visit;
30 use rustc_front::print::pprust;
31
32
33 #[derive(Copy, Clone, Debug)]
34 pub enum EntryOrExit {
35     Entry,
36     Exit,
37 }
38
39 #[derive(Clone)]
40 pub struct DataFlowContext<'a, 'tcx: 'a, O> {
41     tcx: &'a ty::ctxt<'tcx>,
42
43     /// a name for the analysis using this dataflow instance
44     analysis_name: &'static str,
45
46     /// the data flow operator
47     oper: O,
48
49     /// number of bits to propagate per id
50     bits_per_id: usize,
51
52     /// number of words we will use to store bits_per_id.
53     /// equal to bits_per_id/usize::BITS rounded up.
54     words_per_id: usize,
55
56     // mapping from node to cfg node index
57     // FIXME (#6298): Shouldn't this go with CFG?
58     nodeid_to_index: NodeMap<Vec<CFGIndex>>,
59
60     // Bit sets per cfg node.  The following three fields (`gens`, `kills`,
61     // and `on_entry`) all have the same structure. For each id in
62     // `id_range`, there is a range of words equal to `words_per_id`.
63     // So, to access the bits for any given id, you take a slice of
64     // the full vector (see the method `compute_id_range()`).
65
66     /// bits generated as we exit the cfg node. Updated by `add_gen()`.
67     gens: Vec<usize>,
68
69     /// bits killed as we exit the cfg node, or non-locally jump over
70     /// it. Updated by `add_kill(KillFrom::ScopeEnd)`.
71     scope_kills: Vec<usize>,
72
73     /// bits killed as we exit the cfg node directly; if it is jumped
74     /// over, e.g. via `break`, the kills are not reflected in the
75     /// jump's effects. Updated by `add_kill(KillFrom::Execution)`.
76     action_kills: Vec<usize>,
77
78     /// bits that are valid on entry to the cfg node. Updated by
79     /// `propagate()`.
80     on_entry: Vec<usize>,
81 }
82
83 pub trait BitwiseOperator {
84     /// Joins two predecessor bits together, typically either `|` or `&`
85     fn join(&self, succ: usize, pred: usize) -> usize;
86 }
87
88 /// Parameterization for the precise form of data flow that is used.
89 pub trait DataFlowOperator : BitwiseOperator {
90     /// Specifies the initial value for each bit in the `on_entry` set
91     fn initial_value(&self) -> bool;
92 }
93
94 struct PropagationContext<'a, 'b: 'a, 'tcx: 'b, O: 'a> {
95     dfcx: &'a mut DataFlowContext<'b, 'tcx, O>,
96     changed: bool
97 }
98
99 fn get_cfg_indices<'a>(id: ast::NodeId, index: &'a NodeMap<Vec<CFGIndex>>) -> &'a [CFGIndex] {
100     let opt_indices = index.get(&id);
101     opt_indices.map(|v| &v[..]).unwrap_or(&[])
102 }
103
104 impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> {
105     fn has_bitset_for_nodeid(&self, n: ast::NodeId) -> bool {
106         assert!(n != ast::DUMMY_NODE_ID);
107         self.nodeid_to_index.contains_key(&n)
108     }
109 }
110
111 impl<'a, 'tcx, O:DataFlowOperator> pprust::PpAnn for DataFlowContext<'a, 'tcx, O> {
112     fn pre(&self,
113            ps: &mut pprust::State,
114            node: pprust::AnnNode) -> io::Result<()> {
115         let id = match node {
116             pprust::NodeIdent(_) | pprust::NodeName(_) => 0,
117             pprust::NodeExpr(expr) => expr.id,
118             pprust::NodeBlock(blk) => blk.id,
119             pprust::NodeItem(_) | pprust::NodeSubItem(_) => 0,
120             pprust::NodePat(pat) => pat.id
121         };
122
123         if !self.has_bitset_for_nodeid(id) {
124             return Ok(());
125         }
126
127         assert!(self.bits_per_id > 0);
128         let indices = get_cfg_indices(id, &self.nodeid_to_index);
129         for &cfgidx in indices {
130             let (start, end) = self.compute_id_range(cfgidx);
131             let on_entry = &self.on_entry[start.. end];
132             let entry_str = bits_to_string(on_entry);
133
134             let gens = &self.gens[start.. end];
135             let gens_str = if gens.iter().any(|&u| u != 0) {
136                 format!(" gen: {}", bits_to_string(gens))
137             } else {
138                 "".to_string()
139             };
140
141             let action_kills = &self.action_kills[start .. end];
142             let action_kills_str = if action_kills.iter().any(|&u| u != 0) {
143                 format!(" action_kill: {}", bits_to_string(action_kills))
144             } else {
145                 "".to_string()
146             };
147
148             let scope_kills = &self.scope_kills[start .. end];
149             let scope_kills_str = if scope_kills.iter().any(|&u| u != 0) {
150                 format!(" scope_kill: {}", bits_to_string(scope_kills))
151             } else {
152                 "".to_string()
153             };
154
155             try!(ps.synth_comment(
156                 format!("id {}: {}{}{}{}", id, entry_str,
157                         gens_str, action_kills_str, scope_kills_str)));
158             try!(pp::space(&mut ps.s));
159         }
160         Ok(())
161     }
162 }
163
164 fn build_nodeid_to_index(decl: Option<&hir::FnDecl>,
165                          cfg: &cfg::CFG) -> NodeMap<Vec<CFGIndex>> {
166     let mut index = NodeMap();
167
168     // FIXME (#6298): Would it be better to fold formals from decl
169     // into cfg itself?  i.e. introduce a fn-based flow-graph in
170     // addition to the current block-based flow-graph, rather than
171     // have to put traversals like this here?
172     match decl {
173         None => {}
174         Some(decl) => add_entries_from_fn_decl(&mut index, decl, cfg.entry)
175     }
176
177     cfg.graph.each_node(|node_idx, node| {
178         if let cfg::CFGNodeData::AST(id) = node.data {
179             index.entry(id).or_insert(vec![]).push(node_idx);
180         }
181         true
182     });
183
184     return index;
185
186     fn add_entries_from_fn_decl(index: &mut NodeMap<Vec<CFGIndex>>,
187                                 decl: &hir::FnDecl,
188                                 entry: CFGIndex) {
189         //! add mappings from the ast nodes for the formal bindings to
190         //! the entry-node in the graph.
191         struct Formals<'a> {
192             entry: CFGIndex,
193             index: &'a mut NodeMap<Vec<CFGIndex>>,
194         }
195         let mut formals = Formals { entry: entry, index: index };
196         visit::walk_fn_decl(&mut formals, decl);
197         impl<'a, 'v> visit::Visitor<'v> for Formals<'a> {
198             fn visit_pat(&mut self, p: &hir::Pat) {
199                 self.index.entry(p.id).or_insert(vec![]).push(self.entry);
200                 visit::walk_pat(self, p)
201             }
202         }
203     }
204 }
205
206 /// Flag used by `add_kill` to indicate whether the provided kill
207 /// takes effect only when control flows directly through the node in
208 /// question, or if the kill's effect is associated with any
209 /// control-flow directly through or indirectly over the node.
210 #[derive(Copy, Clone, PartialEq, Debug)]
211 pub enum KillFrom {
212     /// A `ScopeEnd` kill is one that takes effect when any control
213     /// flow goes over the node. A kill associated with the end of the
214     /// scope of a variable declaration `let x;` is an example of a
215     /// `ScopeEnd` kill.
216     ScopeEnd,
217
218     /// An `Execution` kill is one that takes effect only when control
219     /// flow goes through the node to completion. A kill associated
220     /// with an assignment statement `x = expr;` is an example of an
221     /// `Execution` kill.
222     Execution,
223 }
224
225 impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> {
226     pub fn new(tcx: &'a ty::ctxt<'tcx>,
227                analysis_name: &'static str,
228                decl: Option<&hir::FnDecl>,
229                cfg: &cfg::CFG,
230                oper: O,
231                id_range: IdRange,
232                bits_per_id: usize) -> DataFlowContext<'a, 'tcx, O> {
233         let words_per_id = (bits_per_id + usize::BITS - 1) / usize::BITS;
234         let num_nodes = cfg.graph.all_nodes().len();
235
236         debug!("DataFlowContext::new(analysis_name: {}, id_range={:?}, \
237                                      bits_per_id={}, words_per_id={}) \
238                                      num_nodes: {}",
239                analysis_name, id_range, bits_per_id, words_per_id,
240                num_nodes);
241
242         let entry = if oper.initial_value() { usize::MAX } else {0};
243
244         let zeroes = vec![0; num_nodes * words_per_id];
245         let gens = zeroes.clone();
246         let kills1 = zeroes.clone();
247         let kills2 = zeroes;
248         let on_entry = vec![entry; num_nodes * words_per_id];
249
250         let nodeid_to_index = build_nodeid_to_index(decl, cfg);
251
252         DataFlowContext {
253             tcx: tcx,
254             analysis_name: analysis_name,
255             words_per_id: words_per_id,
256             nodeid_to_index: nodeid_to_index,
257             bits_per_id: bits_per_id,
258             oper: oper,
259             gens: gens,
260             action_kills: kills1,
261             scope_kills: kills2,
262             on_entry: on_entry
263         }
264     }
265
266     pub fn add_gen(&mut self, id: ast::NodeId, bit: usize) {
267         //! Indicates that `id` generates `bit`
268         debug!("{} add_gen(id={}, bit={})",
269                self.analysis_name, id, bit);
270         assert!(self.nodeid_to_index.contains_key(&id));
271         assert!(self.bits_per_id > 0);
272
273         let indices = get_cfg_indices(id, &self.nodeid_to_index);
274         for &cfgidx in indices {
275             let (start, end) = self.compute_id_range(cfgidx);
276             let gens = &mut self.gens[start.. end];
277             set_bit(gens, bit);
278         }
279     }
280
281     pub fn add_kill(&mut self, kind: KillFrom, id: ast::NodeId, bit: usize) {
282         //! Indicates that `id` kills `bit`
283         debug!("{} add_kill(id={}, bit={})",
284                self.analysis_name, id, bit);
285         assert!(self.nodeid_to_index.contains_key(&id));
286         assert!(self.bits_per_id > 0);
287
288         let indices = get_cfg_indices(id, &self.nodeid_to_index);
289         for &cfgidx in indices {
290             let (start, end) = self.compute_id_range(cfgidx);
291             let kills = match kind {
292                 KillFrom::Execution => &mut self.action_kills[start.. end],
293                 KillFrom::ScopeEnd =>  &mut self.scope_kills[start.. end],
294             };
295             set_bit(kills, bit);
296         }
297     }
298
299     fn apply_gen_kill(&self, cfgidx: CFGIndex, bits: &mut [usize]) {
300         //! Applies the gen and kill sets for `cfgidx` to `bits`
301         debug!("{} apply_gen_kill(cfgidx={:?}, bits={}) [before]",
302                self.analysis_name, cfgidx, mut_bits_to_string(bits));
303         assert!(self.bits_per_id > 0);
304
305         let (start, end) = self.compute_id_range(cfgidx);
306         let gens = &self.gens[start.. end];
307         bitwise(bits, gens, &Union);
308         let kills = &self.action_kills[start.. end];
309         bitwise(bits, kills, &Subtract);
310         let kills = &self.scope_kills[start.. end];
311         bitwise(bits, kills, &Subtract);
312
313         debug!("{} apply_gen_kill(cfgidx={:?}, bits={}) [after]",
314                self.analysis_name, cfgidx, mut_bits_to_string(bits));
315     }
316
317     fn compute_id_range(&self, cfgidx: CFGIndex) -> (usize, usize) {
318         let n = cfgidx.node_id();
319         let start = n * self.words_per_id;
320         let end = start + self.words_per_id;
321
322         assert!(start < self.gens.len());
323         assert!(end <= self.gens.len());
324         assert!(self.gens.len() == self.action_kills.len());
325         assert!(self.gens.len() == self.scope_kills.len());
326         assert!(self.gens.len() == self.on_entry.len());
327
328         (start, end)
329     }
330
331
332     pub fn each_bit_on_entry<F>(&self, id: ast::NodeId, mut f: F) -> bool where
333         F: FnMut(usize) -> bool,
334     {
335         //! Iterates through each bit that is set on entry to `id`.
336         //! Only useful after `propagate()` has been called.
337         if !self.has_bitset_for_nodeid(id) {
338             return true;
339         }
340         let indices = get_cfg_indices(id, &self.nodeid_to_index);
341         for &cfgidx in indices {
342             if !self.each_bit_for_node(Entry, cfgidx, |i| f(i)) {
343                 return false;
344             }
345         }
346         return true;
347     }
348
349     pub fn each_bit_for_node<F>(&self, e: EntryOrExit, cfgidx: CFGIndex, f: F) -> bool where
350         F: FnMut(usize) -> bool,
351     {
352         //! Iterates through each bit that is set on entry/exit to `cfgidx`.
353         //! Only useful after `propagate()` has been called.
354
355         if self.bits_per_id == 0 {
356             // Skip the surprisingly common degenerate case.  (Note
357             // compute_id_range requires self.words_per_id > 0.)
358             return true;
359         }
360
361         let (start, end) = self.compute_id_range(cfgidx);
362         let on_entry = &self.on_entry[start.. end];
363         let temp_bits;
364         let slice = match e {
365             Entry => on_entry,
366             Exit => {
367                 let mut t = on_entry.to_vec();
368                 self.apply_gen_kill(cfgidx, &mut t);
369                 temp_bits = t;
370                 &temp_bits[..]
371             }
372         };
373         debug!("{} each_bit_for_node({:?}, cfgidx={:?}) bits={}",
374                self.analysis_name, e, cfgidx, bits_to_string(slice));
375         self.each_bit(slice, f)
376     }
377
378     pub fn each_gen_bit<F>(&self, id: ast::NodeId, mut f: F) -> bool where
379         F: FnMut(usize) -> bool,
380     {
381         //! Iterates through each bit in the gen set for `id`.
382         if !self.has_bitset_for_nodeid(id) {
383             return true;
384         }
385
386         if self.bits_per_id == 0 {
387             // Skip the surprisingly common degenerate case.  (Note
388             // compute_id_range requires self.words_per_id > 0.)
389             return true;
390         }
391
392         let indices = get_cfg_indices(id, &self.nodeid_to_index);
393         for &cfgidx in indices {
394             let (start, end) = self.compute_id_range(cfgidx);
395             let gens = &self.gens[start.. end];
396             debug!("{} each_gen_bit(id={}, gens={})",
397                    self.analysis_name, id, bits_to_string(gens));
398             if !self.each_bit(gens, |i| f(i)) {
399                 return false;
400             }
401         }
402         return true;
403     }
404
405     fn each_bit<F>(&self, words: &[usize], mut f: F) -> bool where
406         F: FnMut(usize) -> bool,
407     {
408         //! Helper for iterating over the bits in a bit set.
409         //! Returns false on the first call to `f` that returns false;
410         //! if all calls to `f` return true, then returns true.
411
412         for (word_index, &word) in words.iter().enumerate() {
413             if word != 0 {
414                 let base_index = word_index * usize::BITS;
415                 for offset in 0..usize::BITS {
416                     let bit = 1 << offset;
417                     if (word & bit) != 0 {
418                         // NB: we round up the total number of bits
419                         // that we store in any given bit set so that
420                         // it is an even multiple of usize::BITS.  This
421                         // means that there may be some stray bits at
422                         // the end that do not correspond to any
423                         // actual value.  So before we callback, check
424                         // whether the bit_index is greater than the
425                         // actual value the user specified and stop
426                         // iterating if so.
427                         let bit_index = base_index + offset as usize;
428                         if bit_index >= self.bits_per_id {
429                             return true;
430                         } else if !f(bit_index) {
431                             return false;
432                         }
433                     }
434                 }
435             }
436         }
437         return true;
438     }
439
440     pub fn add_kills_from_flow_exits(&mut self, cfg: &cfg::CFG) {
441         //! Whenever you have a `break` or `continue` statement, flow
442         //! exits through any number of enclosing scopes on its way to
443         //! the new destination. This function infers the kill bits of
444         //! those control operators based on the kill bits associated
445         //! with those scopes.
446         //!
447         //! This is usually called (if it is called at all), after
448         //! all add_gen and add_kill calls, but before propagate.
449
450         debug!("{} add_kills_from_flow_exits", self.analysis_name);
451         if self.bits_per_id == 0 {
452             // Skip the surprisingly common degenerate case.  (Note
453             // compute_id_range requires self.words_per_id > 0.)
454             return;
455         }
456         cfg.graph.each_edge(|_edge_index, edge| {
457             let flow_exit = edge.source();
458             let (start, end) = self.compute_id_range(flow_exit);
459             let mut orig_kills = self.scope_kills[start.. end].to_vec();
460
461             let mut changed = false;
462             for &node_id in &edge.data.exiting_scopes {
463                 let opt_cfg_idx = self.nodeid_to_index.get(&node_id);
464                 match opt_cfg_idx {
465                     Some(indices) => {
466                         for &cfg_idx in indices {
467                             let (start, end) = self.compute_id_range(cfg_idx);
468                             let kills = &self.scope_kills[start.. end];
469                             if bitwise(&mut orig_kills, kills, &Union) {
470                                 debug!("scope exits: scope id={} \
471                                         (node={:?} of {:?}) added killset: {}",
472                                        node_id, cfg_idx, indices,
473                                        bits_to_string(kills));
474                                 changed = true;
475                             }
476                         }
477                     }
478                     None => {
479                         debug!("{} add_kills_from_flow_exits flow_exit={:?} \
480                                 no cfg_idx for exiting_scope={}",
481                                self.analysis_name, flow_exit, node_id);
482                     }
483                 }
484             }
485
486             if changed {
487                 let bits = &mut self.scope_kills[start.. end];
488                 debug!("{} add_kills_from_flow_exits flow_exit={:?} bits={} [before]",
489                        self.analysis_name, flow_exit, mut_bits_to_string(bits));
490                 bits.clone_from_slice(&orig_kills[..]);
491                 debug!("{} add_kills_from_flow_exits flow_exit={:?} bits={} [after]",
492                        self.analysis_name, flow_exit, mut_bits_to_string(bits));
493             }
494             true
495         });
496     }
497 }
498
499 impl<'a, 'tcx, O:DataFlowOperator+Clone+'static> DataFlowContext<'a, 'tcx, O> {
500 //                                ^^^^^^^^^^^^^ only needed for pretty printing
501     pub fn propagate(&mut self, cfg: &cfg::CFG, blk: &hir::Block) {
502         //! Performs the data flow analysis.
503
504         if self.bits_per_id == 0 {
505             // Optimize the surprisingly common degenerate case.
506             return;
507         }
508
509         {
510             let words_per_id = self.words_per_id;
511             let mut propcx = PropagationContext {
512                 dfcx: &mut *self,
513                 changed: true
514             };
515
516             let mut temp = vec![0; words_per_id];
517             while propcx.changed {
518                 propcx.changed = false;
519                 propcx.reset(&mut temp);
520                 propcx.walk_cfg(cfg, &mut temp);
521             }
522         }
523
524         debug!("Dataflow result for {}:", self.analysis_name);
525         debug!("{}", {
526             let mut v = Vec::new();
527             self.pretty_print_to(box &mut v, blk).unwrap();
528             println!("{}", String::from_utf8(v).unwrap());
529             ""
530         });
531     }
532
533     fn pretty_print_to<'b>(&self, wr: Box<io::Write + 'b>,
534                            blk: &hir::Block) -> io::Result<()> {
535         let mut ps = pprust::rust_printer_annotated(wr, self);
536         try!(ps.cbox(pprust::indent_unit));
537         try!(ps.ibox(0));
538         try!(ps.print_block(blk));
539         pp::eof(&mut ps.s)
540     }
541 }
542
543 impl<'a, 'b, 'tcx, O:DataFlowOperator> PropagationContext<'a, 'b, 'tcx, O> {
544     fn walk_cfg(&mut self,
545                 cfg: &cfg::CFG,
546                 in_out: &mut [usize]) {
547         debug!("DataFlowContext::walk_cfg(in_out={}) {}",
548                bits_to_string(in_out), self.dfcx.analysis_name);
549         assert!(self.dfcx.bits_per_id > 0);
550
551         cfg.graph.each_node(|node_index, node| {
552             debug!("DataFlowContext::walk_cfg idx={:?} id={} begin in_out={}",
553                    node_index, node.data.id(), bits_to_string(in_out));
554
555             let (start, end) = self.dfcx.compute_id_range(node_index);
556
557             // Initialize local bitvector with state on-entry.
558             in_out.clone_from_slice(&self.dfcx.on_entry[start.. end]);
559
560             // Compute state on-exit by applying transfer function to
561             // state on-entry.
562             self.dfcx.apply_gen_kill(node_index, in_out);
563
564             // Propagate state on-exit from node into its successors.
565             self.propagate_bits_into_graph_successors_of(in_out, cfg, node_index);
566             true // continue to next node
567         });
568     }
569
570     fn reset(&mut self, bits: &mut [usize]) {
571         let e = if self.dfcx.oper.initial_value() {usize::MAX} else {0};
572         for b in bits {
573             *b = e;
574         }
575     }
576
577     fn propagate_bits_into_graph_successors_of(&mut self,
578                                                pred_bits: &[usize],
579                                                cfg: &cfg::CFG,
580                                                cfgidx: CFGIndex) {
581         for (_, edge) in cfg.graph.outgoing_edges(cfgidx) {
582             self.propagate_bits_into_entry_set_for(pred_bits, edge);
583         }
584     }
585
586     fn propagate_bits_into_entry_set_for(&mut self,
587                                          pred_bits: &[usize],
588                                          edge: &cfg::CFGEdge) {
589         let source = edge.source();
590         let cfgidx = edge.target();
591         debug!("{} propagate_bits_into_entry_set_for(pred_bits={}, {:?} to {:?})",
592                self.dfcx.analysis_name, bits_to_string(pred_bits), source, cfgidx);
593         assert!(self.dfcx.bits_per_id > 0);
594
595         let (start, end) = self.dfcx.compute_id_range(cfgidx);
596         let changed = {
597             // (scoping mutable borrow of self.dfcx.on_entry)
598             let on_entry = &mut self.dfcx.on_entry[start.. end];
599             bitwise(on_entry, pred_bits, &self.dfcx.oper)
600         };
601         if changed {
602             debug!("{} changed entry set for {:?} to {}",
603                    self.dfcx.analysis_name, cfgidx,
604                    bits_to_string(&self.dfcx.on_entry[start.. end]));
605             self.changed = true;
606         }
607     }
608 }
609
610 fn mut_bits_to_string(words: &mut [usize]) -> String {
611     bits_to_string(words)
612 }
613
614 fn bits_to_string(words: &[usize]) -> String {
615     let mut result = String::new();
616     let mut sep = '[';
617
618     // Note: this is a little endian printout of bytes.
619
620     for &word in words {
621         let mut v = word;
622         for _ in 0..usize::BYTES {
623             result.push(sep);
624             result.push_str(&format!("{:02x}", v & 0xFF));
625             v >>= 8;
626             sep = '-';
627         }
628     }
629     result.push(']');
630     return result
631 }
632
633 #[inline]
634 fn bitwise<Op:BitwiseOperator>(out_vec: &mut [usize],
635                                in_vec: &[usize],
636                                op: &Op) -> bool {
637     assert_eq!(out_vec.len(), in_vec.len());
638     let mut changed = false;
639     for (out_elt, in_elt) in out_vec.iter_mut().zip(in_vec) {
640         let old_val = *out_elt;
641         let new_val = op.join(old_val, *in_elt);
642         *out_elt = new_val;
643         changed |= old_val != new_val;
644     }
645     changed
646 }
647
648 fn set_bit(words: &mut [usize], bit: usize) -> bool {
649     debug!("set_bit: words={} bit={}",
650            mut_bits_to_string(words), bit_str(bit));
651     let word = bit / usize::BITS;
652     let bit_in_word = bit % usize::BITS;
653     let bit_mask = 1 << bit_in_word;
654     debug!("word={} bit_in_word={} bit_mask={}", word, bit_in_word, word);
655     let oldv = words[word];
656     let newv = oldv | bit_mask;
657     words[word] = newv;
658     oldv != newv
659 }
660
661 fn bit_str(bit: usize) -> String {
662     let byte = bit >> 8;
663     let lobits = 1 << (bit & 0xFF);
664     format!("[{}:{}-{:02x}]", bit, byte, lobits)
665 }
666
667 struct Union;
668 impl BitwiseOperator for Union {
669     fn join(&self, a: usize, b: usize) -> usize { a | b }
670 }
671 struct Subtract;
672 impl BitwiseOperator for Subtract {
673     fn join(&self, a: usize, b: usize) -> usize { a & !b }
674 }