miden_core/mast/merger/
mod.rs

1use alloc::{collections::BTreeMap, vec::Vec};
2
3use miden_crypto::{hash::blake::Blake3Digest, utils::collections::KvMap};
4
5use crate::mast::{
6    DecoratorId, MastForest, MastForestError, MastNode, MastNodeFingerprint, MastNodeId,
7    MultiMastForestIteratorItem, MultiMastForestNodeIter,
8};
9
10#[cfg(test)]
11mod tests;
12
13/// A type that allows merging [`MastForest`]s.
14///
15/// This functionality is exposed via [`MastForest::merge`]. See its documentation for more details.
16pub(crate) struct MastForestMerger {
17    mast_forest: MastForest,
18    // Internal indices needed for efficient duplicate checking and MastNodeFingerprint
19    // computation.
20    //
21    // These are always in-sync with the nodes in `mast_forest`, i.e. all nodes added to the
22    // `mast_forest` are also added to the indices.
23    node_id_by_hash: BTreeMap<MastNodeFingerprint, MastNodeId>,
24    hash_by_node_id: BTreeMap<MastNodeId, MastNodeFingerprint>,
25    decorators_by_hash: BTreeMap<Blake3Digest<32>, DecoratorId>,
26    /// Mappings from old decorator and node ids to their new ids.
27    ///
28    /// Any decorator in `mast_forest` is present as the target of some mapping in this map.
29    decorator_id_mappings: Vec<DecoratorIdMap>,
30    /// Mappings from previous `MastNodeId`s to their new ids.
31    ///
32    /// Any `MastNodeId` in `mast_forest` is present as the target of some mapping in this map.
33    node_id_mappings: Vec<MastForestNodeIdMap>,
34}
35
36impl MastForestMerger {
37    /// Creates a new merger with an initially empty forest and merges all provided [`MastForest`]s
38    /// into it.
39    pub(crate) fn merge<'forest>(
40        forests: impl IntoIterator<Item = &'forest MastForest>,
41    ) -> Result<(MastForest, MastForestRootMap), MastForestError> {
42        let forests = forests.into_iter().collect::<Vec<_>>();
43        let decorator_id_mappings = Vec::with_capacity(forests.len());
44        let node_id_mappings = vec![MastForestNodeIdMap::new(); forests.len()];
45
46        let mut merger = Self {
47            node_id_by_hash: BTreeMap::new(),
48            hash_by_node_id: BTreeMap::new(),
49            decorators_by_hash: BTreeMap::new(),
50            mast_forest: MastForest::new(),
51            decorator_id_mappings,
52            node_id_mappings,
53        };
54
55        merger.merge_inner(forests.clone())?;
56
57        let Self { mast_forest, node_id_mappings, .. } = merger;
58
59        let root_maps = MastForestRootMap::from_node_id_map(node_id_mappings, forests);
60
61        Ok((mast_forest, root_maps))
62    }
63
64    /// Merges all `forests` into self.
65    ///
66    /// It does this in three steps:
67    ///
68    /// 1. Merge all advice maps, checking for key collisions.
69    /// 2. Merge all decorators, which is a case of deduplication and creating a decorator id
70    ///    mapping which contains how existing [`DecoratorId`]s map to [`DecoratorId`]s in the
71    ///    merged forest.
72    /// 3. Merge all nodes of forests.
73    ///    - Similar to decorators, node indices might move during merging, so the merger keeps a
74    ///      node id mapping as it merges nodes.
75    ///    - This is a depth-first traversal over all forests to ensure all children are processed
76    ///      before their parents. See the documentation of [`MultiMastForestNodeIter`] for details
77    ///      on this traversal.
78    ///    - Because all parents are processed after their children, we can use the node id mapping
79    ///      to remap all [`MastNodeId`]s of the children to their potentially new id in the merged
80    ///      forest.
81    ///    - If any external node is encountered during this traversal with a digest `foo` for which
82    ///      a `replacement` node exists in another forest with digest `foo`, then the external node
83    ///      will be replaced by that node. In particular, it means we do not want to add the
84    ///      external node to the merged forest, so it is never yielded from the iterator.
85    ///      - Assuming the simple case, where the `replacement` was not visited yet and is just a
86    ///        single node (not a tree), the iterator would first yield the `replacement` node which
87    ///        means it is going to be merged into the forest.
88    ///      - Next the iterator yields [`MultiMastForestIteratorItem::ExternalNodeReplacement`]
89    ///        which signals that an external node was replaced by another node. In this example,
90    ///        the `replacement_*` indices contained in that variant would point to the
91    ///        `replacement` node. Now we can simply add a mapping from the external node to the
92    ///        `replacement` node in our node id mapping which means all nodes that referenced the
93    ///        external node will point to the `replacement` instead.
94    /// 4. Finally, we merge all roots of all forests. Here we map the existing root indices to
95    ///    their potentially new indices in the merged forest and add them to the forest,
96    ///    deduplicating in the process, too.
97    fn merge_inner(&mut self, forests: Vec<&MastForest>) -> Result<(), MastForestError> {
98        for other_forest in forests.iter() {
99            self.merge_advice_map(other_forest)?;
100        }
101        for other_forest in forests.iter() {
102            self.merge_decorators(other_forest)?;
103        }
104
105        let iterator = MultiMastForestNodeIter::new(forests.clone());
106        for item in iterator {
107            match item {
108                MultiMastForestIteratorItem::Node { forest_idx, node_id } => {
109                    let node = &forests[forest_idx][node_id];
110                    self.merge_node(forest_idx, node_id, node)?;
111                },
112                MultiMastForestIteratorItem::ExternalNodeReplacement {
113                    // forest index of the node which replaces the external node
114                    replacement_forest_idx,
115                    // ID of the node that replaces the external node
116                    replacement_mast_node_id,
117                    // forest index of the external node
118                    replaced_forest_idx,
119                    // ID of the external node
120                    replaced_mast_node_id,
121                } => {
122                    // The iterator is not aware of the merged forest, so the node indices it yields
123                    // are for the existing forests. That means we have to map the ID of the
124                    // replacement to its new location, since it was previously merged and its IDs
125                    // have very likely changed.
126                    let mapped_replacement = self.node_id_mappings[replacement_forest_idx]
127                        .get(&replacement_mast_node_id)
128                        .copied()
129                        .expect("every merged node id should be mapped");
130
131                    // SAFETY: The iterator only yields valid forest indices, so it is safe to index
132                    // directly.
133                    self.node_id_mappings[replaced_forest_idx]
134                        .insert(replaced_mast_node_id, mapped_replacement);
135                },
136            }
137        }
138
139        for (forest_idx, forest) in forests.iter().enumerate() {
140            self.merge_roots(forest_idx, forest)?;
141        }
142
143        Ok(())
144    }
145
146    fn merge_decorators(&mut self, other_forest: &MastForest) -> Result<(), MastForestError> {
147        let mut decorator_id_remapping = DecoratorIdMap::new(other_forest.decorators.len());
148
149        for (merging_id, merging_decorator) in other_forest.decorators.iter().enumerate() {
150            let merging_decorator_hash = merging_decorator.fingerprint();
151            let new_decorator_id = if let Some(existing_decorator) =
152                self.decorators_by_hash.get(&merging_decorator_hash)
153            {
154                *existing_decorator
155            } else {
156                let new_decorator_id = self.mast_forest.add_decorator(merging_decorator.clone())?;
157                self.decorators_by_hash.insert(merging_decorator_hash, new_decorator_id);
158                new_decorator_id
159            };
160
161            decorator_id_remapping
162                .insert(DecoratorId::new_unchecked(merging_id as u32), new_decorator_id);
163        }
164
165        self.decorator_id_mappings.push(decorator_id_remapping);
166
167        Ok(())
168    }
169
170    fn merge_advice_map(&mut self, other_forest: &MastForest) -> Result<(), MastForestError> {
171        for (digest, values) in other_forest.advice_map.iter() {
172            if let Some(stored_values) = self.mast_forest.advice_map().get(digest) {
173                if stored_values != values {
174                    return Err(MastForestError::AdviceMapKeyCollisionOnMerge(*digest));
175                }
176            } else {
177                self.mast_forest.advice_map_mut().insert(*digest, values.clone());
178            }
179        }
180        Ok(())
181    }
182
183    fn merge_node(
184        &mut self,
185        forest_idx: usize,
186        merging_id: MastNodeId,
187        node: &MastNode,
188    ) -> Result<(), MastForestError> {
189        // We need to remap the node prior to computing the MastNodeFingerprint.
190        //
191        // This is because the MastNodeFingerprint computation looks up its descendants and
192        // decorators in the internal index, and if we were to pass the original node to
193        // that computation, it would look up the incorrect descendants and decorators
194        // (since the descendant's indices may have changed).
195        //
196        // Remapping at this point is guaranteed to be "complete", meaning all ids of children
197        // will be present in the node id mapping since the DFS iteration guarantees
198        // that all children of this `node` have been processed before this node and
199        // their indices have been added to the mappings.
200        let remapped_node = self.remap_node(forest_idx, node)?;
201
202        let node_fingerprint = MastNodeFingerprint::from_mast_node(
203            &self.mast_forest,
204            &self.hash_by_node_id,
205            &remapped_node,
206        )
207        .expect(
208            "hash_by_node_id should contain the fingerprints of all children of `remapped_node`",
209        );
210
211        match self.lookup_node_by_fingerprint(&node_fingerprint) {
212            Some(matching_node_id) => {
213                // If a node with a matching fingerprint exists, then the merging node is a
214                // duplicate and we remap it to the existing node.
215                self.node_id_mappings[forest_idx].insert(merging_id, matching_node_id);
216            },
217            None => {
218                // If no node with a matching fingerprint exists, then the merging node is
219                // unique and we can add it to the merged forest.
220                let new_node_id = self.mast_forest.add_node(remapped_node)?;
221                self.node_id_mappings[forest_idx].insert(merging_id, new_node_id);
222
223                // We need to update the indices with the newly inserted nodes
224                // since the MastNodeFingerprint computation requires all descendants of a node
225                // to be in this index. Hence when we encounter a node in the merging forest
226                // which has descendants (Call, Loop, Split, ...), then their descendants need to be
227                // in the indices.
228                self.node_id_by_hash.insert(node_fingerprint, new_node_id);
229                self.hash_by_node_id.insert(new_node_id, node_fingerprint);
230            },
231        }
232
233        Ok(())
234    }
235
236    fn merge_roots(
237        &mut self,
238        forest_idx: usize,
239        other_forest: &MastForest,
240    ) -> Result<(), MastForestError> {
241        for root_id in other_forest.roots.iter() {
242            // Map the previous root to its possibly new id.
243            let new_root = self.node_id_mappings[forest_idx]
244                .get(root_id)
245                .expect("all node ids should have an entry");
246            // This takes O(n) where n is the number of roots in the merged forest every time to
247            // check if the root already exists. As the number of roots is relatively low generally,
248            // this should be okay.
249            self.mast_forest.make_root(*new_root);
250        }
251
252        Ok(())
253    }
254
255    /// Remaps a nodes' potentially contained children and decorators to their new IDs according to
256    /// the given maps.
257    fn remap_node(&self, forest_idx: usize, node: &MastNode) -> Result<MastNode, MastForestError> {
258        let map_decorator_id = |decorator_id: &DecoratorId| {
259            self.decorator_id_mappings[forest_idx].get(decorator_id).ok_or_else(|| {
260                MastForestError::DecoratorIdOverflow(
261                    *decorator_id,
262                    self.decorator_id_mappings[forest_idx].len(),
263                )
264            })
265        };
266        let map_decorators = |decorators: &[DecoratorId]| -> Result<Vec<_>, MastForestError> {
267            decorators.iter().map(map_decorator_id).collect()
268        };
269
270        let map_node_id = |node_id: MastNodeId| {
271            self.node_id_mappings[forest_idx]
272                .get(&node_id)
273                .copied()
274                .expect("every node id should have an entry")
275        };
276
277        // Due to DFS postorder iteration all children of node's should have been inserted before
278        // their parents which is why we can `expect` the constructor calls here.
279        let mut mapped_node = match node {
280            MastNode::Join(join_node) => {
281                let first = map_node_id(join_node.first());
282                let second = map_node_id(join_node.second());
283
284                MastNode::new_join(first, second, &self.mast_forest)
285                    .expect("JoinNode children should have been mapped to a lower index")
286            },
287            MastNode::Split(split_node) => {
288                let if_branch = map_node_id(split_node.on_true());
289                let else_branch = map_node_id(split_node.on_false());
290
291                MastNode::new_split(if_branch, else_branch, &self.mast_forest)
292                    .expect("SplitNode children should have been mapped to a lower index")
293            },
294            MastNode::Loop(loop_node) => {
295                let body = map_node_id(loop_node.body());
296                MastNode::new_loop(body, &self.mast_forest)
297                    .expect("LoopNode children should have been mapped to a lower index")
298            },
299            MastNode::Call(call_node) => {
300                let callee = map_node_id(call_node.callee());
301                MastNode::new_call(callee, &self.mast_forest)
302                    .expect("CallNode children should have been mapped to a lower index")
303            },
304            // Other nodes are simply copied.
305            MastNode::Block(basic_block_node) => {
306                MastNode::new_basic_block(
307                    basic_block_node.operations().copied().collect(),
308                    // Operation Indices of decorators stay the same while decorator IDs need to be
309                    // mapped.
310                    Some(
311                        basic_block_node
312                            .decorators()
313                            .iter()
314                            .map(|(idx, decorator_id)| match map_decorator_id(decorator_id) {
315                                Ok(mapped_decorator) => Ok((*idx, mapped_decorator)),
316                                Err(err) => Err(err),
317                            })
318                            .collect::<Result<Vec<_>, _>>()?,
319                    ),
320                )
321                .expect("previously valid BasicBlockNode should still be valid")
322            },
323            MastNode::Dyn(_) => MastNode::new_dyn(),
324            MastNode::External(external_node) => MastNode::new_external(external_node.digest()),
325        };
326
327        // Decorators must be handled specially for basic block nodes.
328        // For other node types we can handle it centrally.
329        if !mapped_node.is_basic_block() {
330            mapped_node.set_before_enter(map_decorators(node.before_enter())?);
331            mapped_node.set_after_exit(map_decorators(node.after_exit())?);
332        }
333
334        Ok(mapped_node)
335    }
336
337    // HELPERS
338    // ================================================================================================
339
340    /// Returns a slice of nodes in the merged forest which have the given `mast_root`.
341    fn lookup_node_by_fingerprint(&self, fingerprint: &MastNodeFingerprint) -> Option<MastNodeId> {
342        self.node_id_by_hash.get(fingerprint).copied()
343    }
344}
345
346// MAST FOREST ROOT MAP
347// ================================================================================================
348
349/// A mapping for the new location of the roots of a [`MastForest`] after a merge.
350///
351/// It maps the roots ([`MastNodeId`]s) of a forest to their new [`MastNodeId`] in the merged
352/// forest. See [`MastForest::merge`] for more details.
353#[derive(Debug, Clone, PartialEq, Eq)]
354pub struct MastForestRootMap {
355    root_maps: Vec<BTreeMap<MastNodeId, MastNodeId>>,
356}
357
358impl MastForestRootMap {
359    fn from_node_id_map(id_map: Vec<MastForestNodeIdMap>, forests: Vec<&MastForest>) -> Self {
360        let mut root_maps = vec![BTreeMap::new(); forests.len()];
361
362        for (forest_idx, forest) in forests.into_iter().enumerate() {
363            for root in forest.procedure_roots() {
364                let new_id = id_map[forest_idx]
365                    .get(root)
366                    .copied()
367                    .expect("every node id should be mapped to its new id");
368                root_maps[forest_idx].insert(*root, new_id);
369            }
370        }
371
372        Self { root_maps }
373    }
374
375    /// Maps the given root to its new location in the merged forest, if such a mapping exists.
376    ///
377    /// It is guaranteed that every root of the map's corresponding forest is contained in the map.
378    pub fn map_root(&self, forest_index: usize, root: &MastNodeId) -> Option<MastNodeId> {
379        self.root_maps.get(forest_index).and_then(|map| map.get(root)).copied()
380    }
381}
382
383// DECORATOR ID MAP
384// ================================================================================================
385
386/// A specialized map from [`DecoratorId`] -> [`DecoratorId`].
387///
388/// When mapping Decorator IDs during merging, we always map all IDs of the merging
389/// forest to new ids. Hence it is more efficient to use a `Vec` instead of, say, a `BTreeMap`.
390///
391/// In other words, this type is similar to `BTreeMap<ID, ID>` but takes advantage of the fact that
392/// the keys are contiguous.
393///
394/// This type is meant to encapsulates some guarantees:
395///
396/// - Indexing into the vector for any ID is safe if that ID is valid for the corresponding forest.
397///   Despite that, we still cannot index unconditionally in case a node with invalid
398///   [`DecoratorId`]s is passed to `merge`.
399/// - The entry itself can be either None or Some. However:
400///   - For `DecoratorId`s we iterate and insert all decorators into this map before retrieving any
401///     entry, so all entries contain `Some`. Because of this, we can use `expect` in `get` for the
402///     `Option` value.
403/// - Similarly, inserting any ID from the corresponding forest is safe as the map contains a
404///   pre-allocated `Vec` of the appropriate size.
405struct DecoratorIdMap {
406    inner: Vec<Option<DecoratorId>>,
407}
408
409impl DecoratorIdMap {
410    fn new(num_ids: usize) -> Self {
411        Self { inner: vec![None; num_ids] }
412    }
413
414    /// Maps the given key to the given value.
415    ///
416    /// It is the caller's responsibility to only pass keys that belong to the forest for which this
417    /// map was originally created.
418    fn insert(&mut self, key: DecoratorId, value: DecoratorId) {
419        self.inner[key.as_usize()] = Some(value);
420    }
421
422    /// Retrieves the value for the given key.
423    fn get(&self, key: &DecoratorId) -> Option<DecoratorId> {
424        self.inner
425            .get(key.as_usize())
426            .map(|id| id.expect("every id should have a Some entry in the map when calling get"))
427    }
428
429    fn len(&self) -> usize {
430        self.inner.len()
431    }
432}
433
434/// A type definition for increased readability in function signatures.
435type MastForestNodeIdMap = BTreeMap<MastNodeId, MastNodeId>;