1 // Copyright 2012-2016 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.
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.
11 use syntax::ast::{self, MetaItem};
13 use rustc_data_structures::bit_set::{BitSet, BitSetOperator, HybridBitSet};
14 use rustc_data_structures::indexed_vec::Idx;
15 use rustc_data_structures::work_queue::WorkQueue;
17 use rustc::ty::{self, TyCtxt};
18 use rustc::mir::{self, Mir, BasicBlock, BasicBlockData, Location, Statement, Terminator};
19 use rustc::mir::traversal;
20 use rustc::session::Session;
22 use std::borrow::Borrow;
25 use std::path::PathBuf;
28 pub use self::impls::{MaybeStorageLive};
29 pub use self::impls::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
30 pub use self::impls::DefinitelyInitializedPlaces;
31 pub use self::impls::EverInitializedPlaces;
32 pub use self::impls::borrows::Borrows;
33 pub use self::impls::HaveBeenBorrowedLocals;
34 pub use self::at_location::{FlowAtLocation, FlowsAtLocation};
35 pub(crate) use self::drop_flag_effects::*;
37 use self::move_paths::MoveData;
40 pub mod drop_flag_effects;
45 pub(crate) use self::move_paths::indexes;
47 pub(crate) struct DataflowBuilder<'a, 'tcx: 'a, BD> where BD: BitDenotation
50 flow_state: DataflowAnalysis<'a, 'tcx, BD>,
51 print_preflow_to: Option<String>,
52 print_postflow_to: Option<String>,
55 /// `DebugFormatted` encapsulates the "{:?}" rendering of some
56 /// arbitrary value. This way: you pay cost of allocating an extra
57 /// string (as well as that of rendering up-front); in exchange, you
58 /// don't have to hand over ownership of your value or deal with
60 pub(crate) struct DebugFormatted(String);
63 pub fn new(input: &dyn fmt::Debug) -> DebugFormatted {
64 DebugFormatted(format!("{:?}", input))
68 impl fmt::Debug for DebugFormatted {
69 fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
70 write!(w, "{}", self.0)
74 pub(crate) trait Dataflow<BD: BitDenotation> {
75 /// Sets up and runs the dataflow problem, using `p` to render results if
76 /// implementation so chooses.
77 fn dataflow<P>(&mut self, p: P) where P: Fn(&BD, BD::Idx) -> DebugFormatted {
78 let _ = p; // default implementation does not instrument process.
83 /// Sets up the entry, gen, and kill sets for this instance of a dataflow problem.
84 fn build_sets(&mut self);
86 /// Finds a fixed-point solution to this instance of a dataflow problem.
87 fn propagate(&mut self);
90 impl<'a, 'tcx: 'a, BD> Dataflow<BD> for DataflowBuilder<'a, 'tcx, BD> where BD: BitDenotation
92 fn dataflow<P>(&mut self, p: P) where P: Fn(&BD, BD::Idx) -> DebugFormatted {
93 self.flow_state.build_sets();
94 self.pre_dataflow_instrumentation(|c,i| p(c,i)).unwrap();
95 self.flow_state.propagate();
96 self.post_dataflow_instrumentation(|c,i| p(c,i)).unwrap();
99 fn build_sets(&mut self) { self.flow_state.build_sets(); }
100 fn propagate(&mut self) { self.flow_state.propagate(); }
103 pub(crate) fn has_rustc_mir_with(attrs: &[ast::Attribute], name: &str) -> Option<MetaItem> {
105 if attr.check_name("rustc_mir") {
106 let items = attr.meta_item_list();
107 for item in items.iter().flat_map(|l| l.iter()) {
108 match item.meta_item() {
109 Some(mi) if mi.check_name(name) => return Some(mi.clone()),
118 pub struct MoveDataParamEnv<'gcx, 'tcx> {
119 pub(crate) move_data: MoveData<'tcx>,
120 pub(crate) param_env: ty::ParamEnv<'gcx>,
123 pub(crate) fn do_dataflow<'a, 'gcx, 'tcx, BD, P>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
125 node_id: ast::NodeId,
126 attributes: &[ast::Attribute],
127 dead_unwinds: &BitSet<BasicBlock>,
130 -> DataflowResults<BD>
131 where BD: BitDenotation + InitialFlow,
132 P: Fn(&BD, BD::Idx) -> DebugFormatted
134 let flow_state = DataflowAnalysis::new(mir, dead_unwinds, bd);
135 flow_state.run(tcx, node_id, attributes, p)
138 impl<'a, 'gcx: 'tcx, 'tcx: 'a, BD> DataflowAnalysis<'a, 'tcx, BD> where BD: BitDenotation
140 pub(crate) fn run<P>(self,
141 tcx: TyCtxt<'a, 'gcx, 'tcx>,
142 node_id: ast::NodeId,
143 attributes: &[ast::Attribute],
144 p: P) -> DataflowResults<BD>
145 where P: Fn(&BD, BD::Idx) -> DebugFormatted
147 let name_found = |sess: &Session, attrs: &[ast::Attribute], name| -> Option<String> {
148 if let Some(item) = has_rustc_mir_with(attrs, name) {
149 if let Some(s) = item.value_str() {
150 return Some(s.to_string())
154 &format!("{} attribute requires a path", item.ident));
161 let print_preflow_to =
162 name_found(tcx.sess, attributes, "borrowck_graphviz_preflow");
163 let print_postflow_to =
164 name_found(tcx.sess, attributes, "borrowck_graphviz_postflow");
166 let mut mbcx = DataflowBuilder {
168 print_preflow_to, print_postflow_to, flow_state: self,
172 mbcx.flow_state.results()
176 struct PropagationContext<'b, 'a: 'b, 'tcx: 'a, O> where O: 'b + BitDenotation
178 builder: &'b mut DataflowAnalysis<'a, 'tcx, O>,
181 impl<'a, 'tcx: 'a, BD> DataflowAnalysis<'a, 'tcx, BD> where BD: BitDenotation
183 fn propagate(&mut self) {
184 let mut temp = BitSet::new_empty(self.flow_state.sets.bits_per_block);
185 let mut propcx = PropagationContext {
188 propcx.walk_cfg(&mut temp);
191 fn build_sets(&mut self) {
192 // First we need to build the entry-, gen- and kill-sets.
195 let sets = &mut self.flow_state.sets.for_block(mir::START_BLOCK.index());
196 self.flow_state.operator.start_block_effect(&mut sets.on_entry);
199 for (bb, data) in self.mir.basic_blocks().iter_enumerated() {
200 let &mir::BasicBlockData { ref statements, ref terminator, is_cleanup: _ } = data;
202 let mut interim_state;
203 let sets = &mut self.flow_state.sets.for_block(bb.index());
204 let track_intrablock = BD::accumulates_intrablock_state();
205 if track_intrablock {
206 debug!("swapping in mutable on_entry, initially {:?}", sets.on_entry);
207 interim_state = sets.on_entry.to_owned();
208 sets.on_entry = &mut interim_state;
210 for j_stmt in 0..statements.len() {
211 let location = Location { block: bb, statement_index: j_stmt };
212 self.flow_state.operator.before_statement_effect(sets, location);
213 self.flow_state.operator.statement_effect(sets, location);
214 if track_intrablock {
215 sets.apply_local_effect();
219 if terminator.is_some() {
220 let location = Location { block: bb, statement_index: statements.len() };
221 self.flow_state.operator.before_terminator_effect(sets, location);
222 self.flow_state.operator.terminator_effect(sets, location);
223 if track_intrablock {
224 sets.apply_local_effect();
231 impl<'b, 'a: 'b, 'tcx: 'a, BD> PropagationContext<'b, 'a, 'tcx, BD> where BD: BitDenotation
233 fn walk_cfg(&mut self, in_out: &mut BitSet<BD::Idx>) {
234 let mut dirty_queue: WorkQueue<mir::BasicBlock> =
235 WorkQueue::with_all(self.builder.mir.basic_blocks().len());
236 let mir = self.builder.mir;
237 while let Some(bb) = dirty_queue.pop() {
238 let bb_data = &mir[bb];
240 let sets = self.builder.flow_state.sets.for_block(bb.index());
241 debug_assert!(in_out.words().len() == sets.on_entry.words().len());
242 in_out.overwrite(sets.on_entry);
243 in_out.union(sets.gen_set);
244 in_out.subtract(sets.kill_set);
246 self.builder.propagate_bits_into_graph_successors_of(
247 in_out, (bb, bb_data), &mut dirty_queue);
252 fn dataflow_path(context: &str, path: &str) -> PathBuf {
253 let mut path = PathBuf::from(path);
254 let new_file_name = {
255 let orig_file_name = path.file_name().unwrap().to_str().unwrap();
256 format!("{}_{}", context, orig_file_name)
258 path.set_file_name(new_file_name);
262 impl<'a, 'tcx: 'a, BD> DataflowBuilder<'a, 'tcx, BD> where BD: BitDenotation
264 fn pre_dataflow_instrumentation<P>(&self, p: P) -> io::Result<()>
265 where P: Fn(&BD, BD::Idx) -> DebugFormatted
267 if let Some(ref path_str) = self.print_preflow_to {
268 let path = dataflow_path(BD::name(), path_str);
269 graphviz::print_borrowck_graph_to(self, &path, p)
275 fn post_dataflow_instrumentation<P>(&self, p: P) -> io::Result<()>
276 where P: Fn(&BD, BD::Idx) -> DebugFormatted
278 if let Some(ref path_str) = self.print_postflow_to {
279 let path = dataflow_path(BD::name(), path_str);
280 graphviz::print_borrowck_graph_to(self, &path, p)
287 /// DataflowResultsConsumer abstracts over walking the MIR with some
288 /// already constructed dataflow results.
290 /// It abstracts over the FlowState and also completely hides the
291 /// underlying flow analysis results, because it needs to handle cases
292 /// where we are combining the results of *multiple* flow analyses
293 /// (e.g. borrows + inits + uninits).
294 pub(crate) trait DataflowResultsConsumer<'a, 'tcx: 'a> {
295 type FlowState: FlowsAtLocation;
297 // Observation Hooks: override (at least one of) these to get analysis feedback.
298 fn visit_block_entry(&mut self,
300 _flow_state: &Self::FlowState) {}
302 fn visit_statement_entry(&mut self,
304 _stmt: &Statement<'tcx>,
305 _flow_state: &Self::FlowState) {}
307 fn visit_terminator_entry(&mut self,
309 _term: &Terminator<'tcx>,
310 _flow_state: &Self::FlowState) {}
312 // Main entry point: this drives the processing of results.
314 fn analyze_results(&mut self, flow_uninit: &mut Self::FlowState) {
315 let flow = flow_uninit;
316 for (bb, _) in traversal::reverse_postorder(self.mir()) {
317 flow.reset_to_entry_of(bb);
318 self.process_basic_block(bb, flow);
322 fn process_basic_block(&mut self, bb: BasicBlock, flow_state: &mut Self::FlowState) {
323 let BasicBlockData { ref statements, ref terminator, is_cleanup: _ } =
325 let mut location = Location { block: bb, statement_index: 0 };
326 for stmt in statements.iter() {
327 flow_state.reconstruct_statement_effect(location);
328 self.visit_statement_entry(location, stmt, flow_state);
329 flow_state.apply_local_effect(location);
330 location.statement_index += 1;
333 if let Some(ref term) = *terminator {
334 flow_state.reconstruct_terminator_effect(location);
335 self.visit_terminator_entry(location, term, flow_state);
337 // We don't need to apply the effect of the terminator,
338 // since we are only visiting dataflow state on control
339 // flow entry to the various nodes. (But we still need to
340 // reconstruct the effect, because the visit method might
345 // Delegated Hooks: Provide access to the MIR and process the flow state.
347 fn mir(&self) -> &'a Mir<'tcx>;
350 pub fn state_for_location<'tcx, T: BitDenotation>(loc: Location,
352 result: &DataflowResults<T>,
355 let mut on_entry = result.sets().on_entry_set_for(loc.block.index()).to_owned();
356 let mut kill_set = on_entry.to_hybrid();
357 let mut gen_set = kill_set.clone();
360 let mut sets = BlockSets {
361 on_entry: &mut on_entry,
362 kill_set: &mut kill_set,
363 gen_set: &mut gen_set,
366 for stmt in 0..loc.statement_index {
367 let mut stmt_loc = loc;
368 stmt_loc.statement_index = stmt;
369 analysis.before_statement_effect(&mut sets, stmt_loc);
370 analysis.statement_effect(&mut sets, stmt_loc);
373 // Apply the pre-statement effect of the statement we're evaluating.
374 if loc.statement_index == mir[loc.block].statements.len() {
375 analysis.before_terminator_effect(&mut sets, loc);
377 analysis.before_statement_effect(&mut sets, loc);
384 pub struct DataflowAnalysis<'a, 'tcx: 'a, O> where O: BitDenotation
386 flow_state: DataflowState<O>,
387 dead_unwinds: &'a BitSet<mir::BasicBlock>,
391 impl<'a, 'tcx: 'a, O> DataflowAnalysis<'a, 'tcx, O> where O: BitDenotation
393 pub fn results(self) -> DataflowResults<O> {
394 DataflowResults(self.flow_state)
397 pub fn mir(&self) -> &'a Mir<'tcx> { self.mir }
400 pub struct DataflowResults<O>(pub(crate) DataflowState<O>) where O: BitDenotation;
402 impl<O: BitDenotation> DataflowResults<O> {
403 pub fn sets(&self) -> &AllSets<O::Idx> {
407 pub fn operator(&self) -> &O {
412 /// State of a dataflow analysis; couples a collection of bit sets
413 /// with operator used to initialize and merge bits during analysis.
414 pub struct DataflowState<O: BitDenotation>
416 /// All the sets for the analysis. (Factored into its
417 /// own structure so that we can borrow it mutably
418 /// on its own separate from other fields.)
419 pub sets: AllSets<O::Idx>,
421 /// operator used to initialize, combine, and interpret bits.
422 pub(crate) operator: O,
425 impl<O: BitDenotation> DataflowState<O> {
426 pub(crate) fn interpret_set<'c, P>(&self,
428 set: &BitSet<O::Idx>,
430 -> Vec<DebugFormatted>
431 where P: Fn(&O, O::Idx) -> DebugFormatted
433 set.iter().map(|i| render_idx(o, i)).collect()
436 pub(crate) fn interpret_hybrid_set<'c, P>(&self,
438 set: &HybridBitSet<O::Idx>,
440 -> Vec<DebugFormatted>
441 where P: Fn(&O, O::Idx) -> DebugFormatted
443 set.iter().map(|i| render_idx(o, i)).collect()
448 pub struct AllSets<E: Idx> {
449 /// Analysis bitwidth for each block.
450 bits_per_block: usize,
452 /// For each block, bits valid on entry to the block.
453 on_entry_sets: Vec<BitSet<E>>,
455 /// For each block, bits generated by executing the statements +
456 /// terminator in the block -- with one caveat. In particular, for
457 /// *call terminators*, the effect of storing the destination is
458 /// not included, since that only takes effect on the **success**
459 /// edge (and not the unwind edge).
460 gen_sets: Vec<HybridBitSet<E>>,
462 /// For each block, bits killed by executing the statements +
463 /// terminator in the block -- with one caveat. In particular, for
464 /// *call terminators*, the effect of storing the destination is
465 /// not included, since that only takes effect on the **success**
466 /// edge (and not the unwind edge).
467 kill_sets: Vec<HybridBitSet<E>>,
470 /// Triple of sets associated with a given block.
472 /// Generally, one sets up `on_entry`, `gen_set`, and `kill_set` for
473 /// each block individually, and then runs the dataflow analysis which
474 /// iteratively modifies the various `on_entry` sets (but leaves the
475 /// other two sets unchanged, since they represent the effect of the
476 /// block, which should be invariant over the course of the analysis).
478 /// It is best to ensure that the intersection of `gen_set` and
479 /// `kill_set` is empty; otherwise the results of the dataflow will
480 /// have a hidden dependency on what order the bits are generated and
481 /// killed during the iteration. (This is such a good idea that the
482 /// `fn gen` and `fn kill` methods that set their state enforce this
485 pub struct BlockSets<'a, E: Idx> {
486 /// Dataflow state immediately before control flow enters the given block.
487 pub(crate) on_entry: &'a mut BitSet<E>,
489 /// Bits that are set to 1 by the time we exit the given block. Hybrid
490 /// because it usually contains only 0 or 1 elements.
491 pub(crate) gen_set: &'a mut HybridBitSet<E>,
493 /// Bits that are set to 0 by the time we exit the given block. Hybrid
494 /// because it usually contains only 0 or 1 elements.
495 pub(crate) kill_set: &'a mut HybridBitSet<E>,
498 impl<'a, E:Idx> BlockSets<'a, E> {
499 fn gen(&mut self, e: E) {
500 self.gen_set.insert(e);
501 self.kill_set.remove(e);
503 fn gen_all<I>(&mut self, i: I)
504 where I: IntoIterator,
508 self.gen(*j.borrow());
512 fn kill(&mut self, e: E) {
513 self.gen_set.remove(e);
514 self.kill_set.insert(e);
517 fn kill_all<I>(&mut self, i: I)
518 where I: IntoIterator,
522 self.kill(*j.borrow());
526 fn apply_local_effect(&mut self) {
527 self.on_entry.union(self.gen_set);
528 self.on_entry.subtract(self.kill_set);
532 impl<E:Idx> AllSets<E> {
533 pub fn bits_per_block(&self) -> usize { self.bits_per_block }
534 pub fn for_block(&mut self, block_idx: usize) -> BlockSets<E> {
536 on_entry: &mut self.on_entry_sets[block_idx],
537 gen_set: &mut self.gen_sets[block_idx],
538 kill_set: &mut self.kill_sets[block_idx],
542 pub fn on_entry_set_for(&self, block_idx: usize) -> &BitSet<E> {
543 &self.on_entry_sets[block_idx]
545 pub fn gen_set_for(&self, block_idx: usize) -> &HybridBitSet<E> {
546 &self.gen_sets[block_idx]
548 pub fn kill_set_for(&self, block_idx: usize) -> &HybridBitSet<E> {
549 &self.kill_sets[block_idx]
553 /// Parameterization for the precise form of data flow that is used.
554 /// `InitialFlow` handles initializing the bitvectors before any
555 /// code is inspected by the analysis. Analyses that need more nuanced
556 /// initialization (e.g. they need to consult the results of some other
557 /// dataflow analysis to set up the initial bitvectors) should not
559 pub trait InitialFlow {
560 /// Specifies the initial value for each bit in the `on_entry` set
561 fn bottom_value() -> bool;
564 pub trait BitDenotation: BitSetOperator {
565 /// Specifies what index type is used to access the bitvector.
568 /// Some analyses want to accumulate knowledge within a block when
569 /// analyzing its statements for building the gen/kill sets. Override
570 /// this method to return true in such cases.
572 /// When this returns true, the statement-effect (re)construction
573 /// will clone the `on_entry` state and pass along a reference via
574 /// `sets.on_entry` to that local clone into `statement_effect` and
575 /// `terminator_effect`).
577 /// When it's false, no local clone is constructed; instead a
578 /// reference directly into `on_entry` is passed along via
579 /// `sets.on_entry` instead, which represents the flow state at
580 /// the block's start, not necessarily the state immediately prior
581 /// to the statement/terminator under analysis.
583 /// In either case, the passed reference is mutable; but this is a
584 /// wart from using the `BlockSets` type in the API; the intention
585 /// is that the `statement_effect` and `terminator_effect` methods
586 /// mutate only the gen/kill sets.
588 /// FIXME: We should consider enforcing the intention described in
589 /// the previous paragraph by passing the three sets in separate
590 /// parameters to encode their distinct mutabilities.
591 fn accumulates_intrablock_state() -> bool { false }
593 /// A name describing the dataflow analysis that this
594 /// BitDenotation is supporting. The name should be something
595 /// suitable for plugging in as part of a filename e.g. avoid
596 /// space-characters or other things that tend to look bad on a
597 /// file system, like slashes or periods. It is also better for
598 /// the name to be reasonably short, again because it will be
599 /// plugged into a filename.
600 fn name() -> &'static str;
602 /// Size of each bitvector allocated for each block in the analysis.
603 fn bits_per_block(&self) -> usize;
605 /// Mutates the entry set according to the effects that
606 /// have been established *prior* to entering the start
607 /// block. This can't access the gen/kill sets, because
608 /// these won't be accounted for correctly.
610 /// (For example, establishing the call arguments.)
611 fn start_block_effect(&self, entry_set: &mut BitSet<Self::Idx>);
613 /// Similar to `statement_effect`, except it applies
614 /// *just before* the statement rather than *just after* it.
616 /// This matters for "dataflow at location" APIs, because the
617 /// before-statement effect is visible while visiting the
618 /// statement, while the after-statement effect only becomes
619 /// visible at the next statement.
621 /// Both the before-statement and after-statement effects are
622 /// applied, in that order, before moving for the next
624 fn before_statement_effect(&self,
625 _sets: &mut BlockSets<Self::Idx>,
626 _location: Location) {}
628 /// Mutates the block-sets (the flow sets for the given
629 /// basic block) according to the effects of evaluating statement.
631 /// This is used, in particular, for building up the
632 /// "transfer-function" representing the overall-effect of the
633 /// block, represented via GEN and KILL sets.
635 /// The statement is identified as `bb_data[idx_stmt]`, where
636 /// `bb_data` is the sequence of statements identified by `bb` in
638 fn statement_effect(&self,
639 sets: &mut BlockSets<Self::Idx>,
642 /// Similar to `terminator_effect`, except it applies
643 /// *just before* the terminator rather than *just after* it.
645 /// This matters for "dataflow at location" APIs, because the
646 /// before-terminator effect is visible while visiting the
647 /// terminator, while the after-terminator effect only becomes
648 /// visible at the terminator's successors.
650 /// Both the before-terminator and after-terminator effects are
651 /// applied, in that order, before moving for the next
653 fn before_terminator_effect(&self,
654 _sets: &mut BlockSets<Self::Idx>,
655 _location: Location) {}
657 /// Mutates the block-sets (the flow sets for the given
658 /// basic block) according to the effects of evaluating
661 /// This is used, in particular, for building up the
662 /// "transfer-function" representing the overall-effect of the
663 /// block, represented via GEN and KILL sets.
665 /// The effects applied here cannot depend on which branch the
667 fn terminator_effect(&self,
668 sets: &mut BlockSets<Self::Idx>,
671 /// Mutates the block-sets according to the (flow-dependent)
672 /// effect of a successful return from a Call terminator.
674 /// If basic-block BB_x ends with a call-instruction that, upon
675 /// successful return, flows to BB_y, then this method will be
676 /// called on the exit flow-state of BB_x in order to set up the
677 /// entry flow-state of BB_y.
679 /// This is used, in particular, as a special case during the
680 /// "propagate" loop where all of the basic blocks are repeatedly
681 /// visited. Since the effects of a Call terminator are
682 /// flow-dependent, the current MIR cannot encode them via just
683 /// GEN and KILL sets attached to the block, and so instead we add
684 /// this extra machinery to represent the flow-dependent effect.
686 /// FIXME: Right now this is a bit of a wart in the API. It might
687 /// be better to represent this as an additional gen- and
688 /// kill-sets associated with each edge coming out of the basic
690 fn propagate_call_return(&self,
691 in_out: &mut BitSet<Self::Idx>,
692 call_bb: mir::BasicBlock,
693 dest_bb: mir::BasicBlock,
694 dest_place: &mir::Place);
697 impl<'a, 'tcx, D> DataflowAnalysis<'a, 'tcx, D> where D: BitDenotation
699 pub fn new(mir: &'a Mir<'tcx>,
700 dead_unwinds: &'a BitSet<mir::BasicBlock>,
701 denotation: D) -> Self where D: InitialFlow {
702 let bits_per_block = denotation.bits_per_block();
703 let num_blocks = mir.basic_blocks().len();
705 let on_entry_sets = if D::bottom_value() {
706 vec![BitSet::new_filled(bits_per_block); num_blocks]
708 vec![BitSet::new_empty(bits_per_block); num_blocks]
710 let gen_sets = vec![HybridBitSet::new_empty(bits_per_block); num_blocks];
711 let kill_sets = gen_sets.clone();
716 flow_state: DataflowState {
723 operator: denotation,
729 impl<'a, 'tcx: 'a, D> DataflowAnalysis<'a, 'tcx, D> where D: BitDenotation
731 /// Propagates the bits of `in_out` into all the successors of `bb`,
732 /// using bitwise operator denoted by `self.operator`.
734 /// For most blocks, this is entirely uniform. However, for blocks
735 /// that end with a call terminator, the effect of the call on the
736 /// dataflow state may depend on whether the call returned
737 /// successfully or unwound.
739 /// To reflect this, the `propagate_call_return` method of the
740 /// `BitDenotation` mutates `in_out` when propagating `in_out` via
741 /// a call terminator; such mutation is performed *last*, to
742 /// ensure its side-effects do not leak elsewhere (e.g. into
744 fn propagate_bits_into_graph_successors_of(
746 in_out: &mut BitSet<D::Idx>,
747 (bb, bb_data): (mir::BasicBlock, &mir::BasicBlockData),
748 dirty_list: &mut WorkQueue<mir::BasicBlock>)
750 match bb_data.terminator().kind {
751 mir::TerminatorKind::Return |
752 mir::TerminatorKind::Resume |
753 mir::TerminatorKind::Abort |
754 mir::TerminatorKind::GeneratorDrop |
755 mir::TerminatorKind::Unreachable => {}
756 mir::TerminatorKind::Goto { target } |
757 mir::TerminatorKind::Assert { target, cleanup: None, .. } |
758 mir::TerminatorKind::Yield { resume: target, drop: None, .. } |
759 mir::TerminatorKind::Drop { target, location: _, unwind: None } |
760 mir::TerminatorKind::DropAndReplace {
761 target, value: _, location: _, unwind: None
763 self.propagate_bits_into_entry_set_for(in_out, target, dirty_list);
765 mir::TerminatorKind::Yield { resume: target, drop: Some(drop), .. } => {
766 self.propagate_bits_into_entry_set_for(in_out, target, dirty_list);
767 self.propagate_bits_into_entry_set_for(in_out, drop, dirty_list);
769 mir::TerminatorKind::Assert { target, cleanup: Some(unwind), .. } |
770 mir::TerminatorKind::Drop { target, location: _, unwind: Some(unwind) } |
771 mir::TerminatorKind::DropAndReplace {
772 target, value: _, location: _, unwind: Some(unwind)
774 self.propagate_bits_into_entry_set_for(in_out, target, dirty_list);
775 if !self.dead_unwinds.contains(bb) {
776 self.propagate_bits_into_entry_set_for(in_out, unwind, dirty_list);
779 mir::TerminatorKind::SwitchInt { ref targets, .. } => {
780 for target in targets {
781 self.propagate_bits_into_entry_set_for(in_out, *target, dirty_list);
784 mir::TerminatorKind::Call { cleanup, ref destination, .. } => {
785 if let Some(unwind) = cleanup {
786 if !self.dead_unwinds.contains(bb) {
787 self.propagate_bits_into_entry_set_for(in_out, unwind, dirty_list);
790 if let Some((ref dest_place, dest_bb)) = *destination {
791 // N.B.: This must be done *last*, after all other
792 // propagation, as documented in comment above.
793 self.flow_state.operator.propagate_call_return(
794 in_out, bb, dest_bb, dest_place);
795 self.propagate_bits_into_entry_set_for(in_out, dest_bb, dirty_list);
798 mir::TerminatorKind::FalseEdges { real_target, ref imaginary_targets } => {
799 self.propagate_bits_into_entry_set_for(in_out, real_target, dirty_list);
800 for target in imaginary_targets {
801 self.propagate_bits_into_entry_set_for(in_out, *target, dirty_list);
804 mir::TerminatorKind::FalseUnwind { real_target, unwind } => {
805 self.propagate_bits_into_entry_set_for(in_out, real_target, dirty_list);
806 if let Some(unwind) = unwind {
807 if !self.dead_unwinds.contains(bb) {
808 self.propagate_bits_into_entry_set_for(in_out, unwind, dirty_list);
815 fn propagate_bits_into_entry_set_for(&mut self,
816 in_out: &BitSet<D::Idx>,
818 dirty_queue: &mut WorkQueue<mir::BasicBlock>) {
819 let entry_set = &mut self.flow_state.sets.for_block(bb.index()).on_entry;
820 let set_changed = self.flow_state.operator.join(entry_set, &in_out);
822 dirty_queue.insert(bb);