mmtk/plan/tracing/gc_work/
closure.rs

1use std::marker::PhantomData;
2
3use crate::{
4    plan::{
5        tracing::{gc_work::DefaultObjectTracerContext, SlotOfTrace, Trace},
6        VectorObjectQueue, VectorQueue,
7    },
8    scheduler::{GCWork, GCWorker, GCWorkerShared, WorkBucketStage},
9    util::{ObjectReference, VMWorkerThread},
10    vm::{slot::Slot, ObjectTracer, ObjectTracerContext, Scanning, VMBinding},
11    MMTK,
12};
13
14/// A work packet for processing slots during a stop-the-world tracing GC and the final mark pause
15/// of a concurrent GC.
16///
17/// It will call `trace_object` on the value of each slot, and updates the slot if the object is
18/// moved or forwarded.  It will spawn or immediately run the [`ProcessNodes`] work packet to
19/// scan newly traced objects.
20pub struct ProcessSlots<T: Trace> {
21    slots: Vec<SlotOfTrace<T>>,
22    bucket: WorkBucketStage,
23    roots: bool,
24}
25
26impl<T: Trace> ProcessSlots<T> {
27    const SCAN_OBJECTS_IMMEDIATELY: bool = true;
28
29    pub fn new(slots: Vec<SlotOfTrace<T>>, bucket: WorkBucketStage, roots: bool) -> Self {
30        Self {
31            slots,
32            bucket,
33            roots,
34        }
35    }
36
37    fn process_slots(
38        &mut self,
39        worker: &mut GCWorker<T::VM>,
40        trace: T,
41    ) -> VectorQueue<ObjectReference> {
42        let mut queue = VectorObjectQueue::new();
43
44        for slot in self.slots.iter() {
45            if let Some(object) = slot.load() {
46                let new_object = trace.trace_object(worker, object, &mut queue);
47                if T::may_move_objects() && new_object != object {
48                    slot.store(new_object);
49                }
50            }
51        }
52
53        queue
54    }
55
56    fn flush(&mut self, worker: &mut GCWorker<T::VM>, mut queue: VectorQueue<ObjectReference>) {
57        if queue.is_empty() {
58            return;
59        }
60
61        let queued_objects = queue.take();
62        let mut work = ProcessNodes::<T>::new(queued_objects, self.bucket);
63
64        if Self::SCAN_OBJECTS_IMMEDIATELY {
65            work.do_work(worker, worker.mmtk);
66        } else {
67            worker.add_work(self.bucket, work);
68        }
69    }
70}
71
72impl<T: Trace> GCWork<T::VM> for ProcessSlots<T> {
73    fn do_work(&mut self, worker: &mut GCWorker<T::VM>, mmtk: &'static MMTK<T::VM>) {
74        probe!(mmtk, process_slots, self.slots.len(), self.roots);
75
76        let trace = T::from_mmtk(mmtk);
77
78        #[cfg(feature = "extreme_assertions")]
79        if crate::util::slot_logger::should_check_duplicate_slots(mmtk.get_plan()) {
80            for slot in self.slots.iter() {
81                // log slot, panic if already logged
82                mmtk.slot_logger.log_slot(*slot);
83            }
84        }
85
86        let queue = self.process_slots(worker, trace);
87
88        self.flush(worker, queue);
89    }
90}
91
92/// A work packet for scanning objects and optionally do node-enqueuing tracing during a
93/// stop-the-world tracing GC and the final mark pause of a concurrent GC.
94///
95/// It will scan each object.  For objects that supports slot enqueuing, it will collect their slots
96/// and spawn [`ProcessSlots`] work packets to trace them.  For objects that don't support slot
97/// enqueuing, it will immediately trace their slots and spawn other [`ProcessNodes`] work packets
98/// to process their newly traced children.  It is the VM's responsibility to implement
99/// [`Scanning::scan_object_and_trace_edges`] to update the references to point to the new addresses
100/// in such a case.
101pub struct ProcessNodes<T: Trace> {
102    objects: Vec<ObjectReference>,
103    bucket: WorkBucketStage,
104    phantom_data: PhantomData<T>,
105}
106
107impl<T: Trace> ProcessNodes<T> {
108    pub fn new(objects: Vec<ObjectReference>, bucket: WorkBucketStage) -> Self {
109        Self {
110            objects,
111            bucket,
112            phantom_data: PhantomData,
113        }
114    }
115
116    fn try_enqueue_slots(
117        &mut self,
118        worker: &mut GCWorker<T::VM>,
119        tls: VMWorkerThread,
120        trace: &T,
121    ) -> Vec<ObjectReference> {
122        // We record objects that don't support slot-enqueuing tracing and process them later.
123        let mut scan_later = Vec::new();
124
125        let mut slots = VectorQueue::new();
126
127        let flush = |slots: &mut VectorQueue<_>, worker: &mut GCWorker<T::VM>| {
128            let buffer = slots.take();
129            let work_packet = ProcessSlots::<T>::new(buffer, self.bucket, false);
130            worker.add_work(self.bucket, work_packet);
131        };
132
133        // For any object we need to scan, we count its live bytes.
134        // Check the option outside the loop for better performance.
135        //
136        // TODO: Currently all objects reached in a GC will be processed here,
137        // so it is a good place to do statistics for all reachable objects.
138        // In the future, when we refactor the ProcessNodes and ProcessSlots work packets
139        // so that each of them can compute the transitive closure alone (i.e. removing double enqueuing),
140        // we need to make sure both work packets will count the live bytes.
141        if crate::util::rust_util::unlikely(*worker.mmtk.get_options().count_live_bytes_in_gc) {
142            // Borrow before the loop.
143            let mut live_bytes_stats = worker.shared.live_bytes_per_space.borrow_mut();
144            for object in self.objects.iter().copied() {
145                GCWorkerShared::<T::VM>::increase_live_bytes(&mut live_bytes_stats, object);
146            }
147        }
148
149        for object in self.objects.iter().copied() {
150            if <T::VM as VMBinding>::VMScanning::support_slot_enqueuing(tls, object) {
151                trace!("Scan object (slot) {}", object);
152                // If an object supports slot-enqueuing, we enqueue its slots.
153                <T::VM as VMBinding>::VMScanning::scan_object(tls, object, &mut |slot| {
154                    slots.push(slot);
155                    if slots.is_full() {
156                        flush(&mut slots, worker);
157                    }
158                });
159                trace.post_scan_object(object);
160            } else {
161                // If an object does not support slot-enqueuing, we have to use
162                // `Scanning::scan_object_and_trace_edges` and offload the job of updating the
163                // reference field to the VM.
164                //
165                // TODO: We may refactor this work packet to do slot-enqueuing and node-enqueuing in
166                // one loop.
167                scan_later.push(object);
168            }
169        }
170
171        if !slots.is_empty() {
172            flush(&mut slots, worker);
173        }
174
175        scan_later
176    }
177
178    fn do_node_enqueuing_tracing(
179        &mut self,
180        worker: &mut GCWorker<T::VM>,
181        tls: VMWorkerThread,
182        trace: T,
183        scan_later: Vec<ObjectReference>,
184    ) {
185        if scan_later.is_empty() {
186            return;
187        }
188
189        let mut num_visited_slots = 0;
190
191        let object_tracer_context = DefaultObjectTracerContext::<T>::new(self.bucket);
192
193        object_tracer_context.with_tracer(worker, |object_tracer| {
194            // Scan objects and trace their outgoing edges at the same time.
195            for object in scan_later.iter().copied() {
196                trace!("Scan object (node) {}", object);
197                <T::VM as VMBinding>::VMScanning::scan_object_and_trace_edges(
198                    tls,
199                    object,
200                    &mut |child| {
201                        num_visited_slots += 1;
202                        object_tracer.trace_object(child)
203                    },
204                );
205                trace.post_scan_object(object);
206            }
207        });
208
209        probe!(mmtk, do_node_enqueuing_tracing, num_visited_slots);
210    }
211}
212
213impl<T: Trace> GCWork<T::VM> for ProcessNodes<T> {
214    fn do_work(&mut self, worker: &mut GCWorker<T::VM>, mmtk: &'static MMTK<T::VM>) {
215        trace!("ScanObjects");
216
217        let tls = worker.tls;
218        let trace = T::from_mmtk(mmtk);
219
220        // Go through the object list and scan objects that supports slot-enququing.
221        let scan_later = self.try_enqueue_slots(worker, tls, &trace);
222
223        let total_objects = self.objects.len();
224        let scan_and_trace = scan_later.len();
225        probe!(mmtk, process_nodes, total_objects, scan_and_trace);
226
227        // If any objects do not support slot-enqueuing, we process them now.
228        self.do_node_enqueuing_tracing(worker, tls, trace, scan_later);
229
230        trace!("ScanObjects End");
231    }
232}