1 // Splay tree utilities -*- C++ -*-
2 // Copyright (C) 2020-2024 Free Software Foundation, Inc.
4 // This file is part of GCC.
6 // GCC is free software; you can redistribute it and/or modify it under
7 // the terms of the GNU General Public License as published by the Free
8 // Software Foundation; either version 3, or (at your option) any later
11 // GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 // WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 // You should have received a copy of the GNU General Public License
17 // along with GCC; see the file COPYING3. If not see
18 // <http://www.gnu.org/licenses/>.
20 // INDEX is either 0 or 1. If it is 0, return NODE's left child,
21 // otherwise return NODE's right child.
22 template<typename Accessors>
23 inline typename base_splay_tree<Accessors>::node_type
24 base_splay_tree<Accessors>::get_child (node_type node, unsigned int index)
26 return Accessors::child (node, index);
29 // INDEX is either 0 or 1. If it is 0, change NODE's left child to CHILD,
30 // otherwise change NODE's right child to CHILD. If CHILD has a parent
31 // field, record that its parent is now NODE.
32 template<typename Accessors>
34 base_splay_tree<Accessors>::set_child (node_type node, unsigned int index,
37 Accessors::child (node, index) = child;
39 set_parent (child, node);
42 // Rotate the tree to promote child number INDEX of NODE, so that that
43 // child becomes a parent of NODE. Return the promoted node.
45 // The caller has the responsibility of assigning a correct parent
46 // to the returned node.
47 template<typename Accessors>
48 inline typename base_splay_tree<Accessors>::node_type
49 base_splay_tree<Accessors>::promote_child (node_type node, unsigned int index)
51 node_type promoted = get_child (node, index);
52 set_child (node, index, get_child (promoted, 1 - index));
53 set_child (promoted, 1 - index, node);
57 // Treat child number INDEX of NODE as being CHILD and rotate the tree
58 // so that CHILD becomes a parent of NODE.
60 // The caller has the responsibility of assigning a correct parent to CHILD.
61 template<typename Accessors>
63 base_splay_tree<Accessors>::promote_child (node_type node, unsigned int index,
66 set_child (node, index, get_child (child, 1 - index));
67 set_child (child, 1 - index, node);
70 // Print NODE to PP, using PRINTER (PP, N) to print the contents of node N.
71 // Prefix each new line with INDENT_STRING. CODE is 'T' if NODE is the root
72 // node, 'L' if NODE is the left child of its parent, or 'R' if NODE is the
73 // right child of its parent.
74 template<typename Accessors>
75 template<typename Printer>
77 base_splay_tree<Accessors>::print (pretty_printer *pp, node_type node,
78 Printer printer, char code,
79 vec<char> &indent_string)
81 // In the comments below, PREFIX refers to the incoming contents
83 node_type left = get_child (node, 0);
84 node_type right = get_child (node, 1);
86 auto orig_indent_len = indent_string.length ();
87 indent_string.safe_grow (orig_indent_len + 3);
88 char *extra_indent = indent_string.address () + orig_indent_len;
90 // Print [T], [L], or [R].
91 extra_indent[0] = '[';
92 extra_indent[1] = code;
93 extra_indent[2] = ']';
94 pp_append_text (pp, extra_indent, indent_string.end ());
97 // Print the node itself, using PREFIX + " | " or PREFIX + " " to indent
98 // new lines under the "[_]" that we just printed.
99 extra_indent[0] = ' ';
100 extra_indent[1] = (left || right ? '|' : ' ');
101 extra_indent[2] = ' ';
103 pretty_printer sub_pp;
104 printer (&sub_pp, node);
105 const char *text = pp_formatted_text (&sub_pp);
106 while (const char *end = strchr (text, '\n'))
108 pp_append_text (pp, text, end);
109 pp_newline_and_indent (pp, 0);
110 pp_append_text (pp, indent_string.begin (), indent_string.end ());
113 pp_string (pp, text);
118 // Print PREFIX + " +-" for the first line of the left subtree,
119 // to be followed by "[L]".
120 extra_indent[1] = '+';
121 extra_indent[2] = '-';
122 pp_newline_and_indent (pp, 0);
123 pp_append_text (pp, indent_string.begin (), indent_string.end ());
125 // Print the left subtree, using PREFIX + " | " or PREFIX + " "
126 // to indent under the PREFIX + " +-" that we just printed.
127 extra_indent[1] = right ? '|' : ' ';
128 extra_indent[2] = ' ';
129 print (pp, left, printer, 'L', indent_string);
130 extra_indent = indent_string.address () + orig_indent_len;
132 // If LEFT is not a leaf and we also have a right subtree, use a
133 // PREFIX + " |" line to separate them.
134 if (right && (get_child (left, 0) || get_child (left, 1)))
136 pp_newline_and_indent (pp, 0);
137 pp_append_text (pp, indent_string.begin (), &extra_indent[2]);
142 // Print PREFIX + " +-" for the first line of the right subtree,
143 // to be followed by "[R]".
144 extra_indent[1] = '+';
145 extra_indent[2] = '-';
146 pp_newline_and_indent (pp, 0);
147 pp_append_text (pp, indent_string.begin (), indent_string.end ());
149 // Print the right subtree, using PREFIX + " " to indent under the
150 // PREFIX + " +-" that we just printed.
151 extra_indent[1] = ' ';
152 extra_indent[2] = ' ';
153 print (pp, right, printer, 'R', indent_string);
155 indent_string.truncate (orig_indent_len);
158 // See the comment above the declaration.
159 template<typename Accessors>
160 template<typename Printer>
162 base_splay_tree<Accessors>::print (pretty_printer *pp, node_type node,
167 pp_string (pp, "null");
170 auto_vec<char, 64> indent_string;
171 print (pp, node, printer, 'T', indent_string);
174 // If N is 1, splay the last (rightmost) node reachable from START
175 // to the position that START current holds and return the splayed node.
176 // START is not itself the last node.
178 // If N is 0, splay the first (leftmost) node reachable from START
179 // to the position that START current holds and return the splayed node.
180 // START is not itself the first node.
182 // The caller has the responsibility of updating the parent of the
184 template<typename Accessors>
185 template<unsigned int N>
186 typename base_splay_tree<Accessors>::node_type
187 base_splay_tree<Accessors>::splay_limit (node_type start)
189 // This essentially follows the simpilfied top-down method described
190 // in Sleator and Tarjan's "Self-adjusting Binary Search Trees", but
191 // specialized for the case in which the comparison result is fixed.
192 // The first iteration is peeled to avoid the need for stack temporaries.
194 // The comments and names reflect the behavior for N == 1, but the
195 // N == 0 case behaves analogously.
197 // Rotate the tree to promote the right child of START to the root.
198 node_type node = promote_child (start, N);
199 if (node_type right = get_child (node, N))
201 // Perform the link left step, which for this first iteration
202 // means making NODE the root of the left tree.
204 // NODE will become left child of the final node. For a right
205 // spine starting at NODE of the form:
207 // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> ... -> N
212 // the next step is to create a subtree of N whose right spine contains
213 // the odd-numbered nodes, as follows:
218 // 1 ------> 3 ------> 5 ------> 7 -> .... -> NL
221 // A 2 -> C 4 -> E 6 -> G
226 // First record 1 as the left child of the final root (N) and move
228 node_type final_child = node;
229 node_type new_spine_end = node;
231 while (node_type right = get_child (node, N))
233 // Perform another rotate left step.
235 // We've built the tree rooted at 1 in the diagram above up to,
236 // but not including, an even-numbered node NODE on the original
237 // right spine. Rotate the tree at NODE to promote the following
238 // odd-numbered node.
239 promote_child (node, N, right);
241 if (node_type right = get_child (node, N))
243 // Perform another link left step.
245 // Add the promoted odd-numbered node to the right spine of the
246 // tree rooted at 1 and move on to the next even-numbered node.
247 set_child (new_spine_end, N, node);
248 new_spine_end = node;
252 // Perform the assembly step.
254 // Add NL to the new spine and make N the new root.
255 set_child (new_spine_end, N, get_child (node, 1 - N));
256 set_child (node, 1 - N, final_child);
261 // Remove NODE from its position in the splay tree. If NODE has at least
262 // one child node, return the node that should now hold NODE's position in
263 // the splay tree. If NODE has no children, return null.
265 // The caller has the responsibility of updating the parent of the
267 template<typename Accessors>
268 inline typename base_splay_tree<Accessors>::node_type
269 base_splay_tree<Accessors>::remove_node_internal (node_type node)
271 node_type left = get_child (node, 0);
272 node_type right = get_child (node, 1);
279 if (get_child (left, 1))
281 left = splay_limit<1> (left);
282 gcc_checking_assert (!get_child (left, 1));
284 set_child (left, 1, right);
288 // See the comment above the declaration.
289 template<typename Accessors>
291 base_splay_tree<Accessors>::insert_child (node_type node, unsigned int index,
294 gcc_checking_assert (!get_child (child, 0) && !get_child (child, 1));
295 set_child (child, index, get_child (node, index));
296 set_child (node, index, child);
299 // Implement splay_next_node if N == 1 and splay_prev_node if N == 0.
300 template<typename Accessors>
301 template<unsigned int N>
303 rooted_splay_tree<Accessors>::splay_neighbor ()
305 node_type node = m_root;
306 node_type new_root = get_child (node, N);
310 if (get_child (new_root, 1 - N))
312 // NEW_ROOT is not itself the required node, so splay the required
313 // node into its place.
314 new_root = parent::template splay_limit<1 - N> (new_root);
315 gcc_checking_assert (!get_child (new_root, 1 - N));
316 set_child (node, N, node_type ());
317 set_child (new_root, 1 - N, node);
320 promote_child (node, N, new_root);
321 set_parent (new_root, node_type ());
326 // See the comment above the declaration.
327 template<typename Accessors>
328 template<typename Comparator>
330 rooted_splay_tree<Accessors>::insert (node_type new_node, Comparator compare)
332 gcc_checking_assert (!get_child (new_node, 0) && !get_child (new_node, 1));
339 int comparison = lookup (compare);
343 // Insert NEW_NODE before M_ROOT if COMPARISON < 0 and after M_ROOT
345 set_child (new_node, comparison < 0, m_root);
346 set_child (new_node, comparison > 0, get_child (m_root, comparison > 0));
347 set_child (m_root, comparison > 0, nullptr);
352 // See the comment above the declaration.
353 template<typename Accessors>
355 rooted_splay_tree<Accessors>::insert_max_node (node_type new_node)
357 gcc_checking_assert (!get_child (new_node, 0) && !get_child (new_node, 1));
358 set_child (new_node, 0, m_root);
362 // See the comment above the declaration.
363 template<typename Accessors>
365 rooted_splay_tree<Accessors>::splice_next_tree (rooted_splay_tree next_tree)
368 set_child (m_root, 1, next_tree.m_root);
371 // See the comment above the declaration.
372 template<typename Accessors>
374 rooted_splay_tree<Accessors>::replace_max_node_at_root (node_type new_node)
376 node_type old_node = m_root;
377 gcc_checking_assert (!get_child (new_node, 0)
378 && !get_child (new_node, 1)
379 && !get_child (old_node, 1));
380 set_child (new_node, 0, get_child (old_node, 0));
381 // Clear the links from OLD_NODE. Its parent and right child are
382 // already node_type ().
383 set_child (old_node, 0, node_type ());
387 // See the comment above the declaration.
388 template<typename Accessors>
390 rooted_splay_tree<Accessors>::remove_root ()
392 node_type node = m_root;
393 m_root = parent::remove_node_internal (node);
395 set_parent (m_root, node_type ());
396 // Clear the links from NODE. Its parent is already node_type ().
397 set_child (node, 0, node_type ());
398 set_child (node, 1, node_type ());
401 // See the comment above the declaration.
402 template<typename Accessors>
403 inline rooted_splay_tree<Accessors>
404 rooted_splay_tree<Accessors>::split_before_root ()
406 node_type new_root = get_child (m_root, 0);
407 set_child (m_root, 0, node_type ());
408 set_parent (new_root, node_type ());
412 // See the comment above the declaration.
413 template<typename Accessors>
414 inline rooted_splay_tree<Accessors>
415 rooted_splay_tree<Accessors>::split_after_root ()
417 node_type new_root = get_child (m_root, 1);
418 set_child (m_root, 1, node_type ());
419 set_parent (new_root, node_type ());
423 // See the comment above the declaration.
424 template<typename Accessors>
426 rooted_splay_tree<Accessors>::splay_prev_node ()
428 return splay_neighbor<0> ();
431 // See the comment above the declaration.
432 template<typename Accessors>
434 rooted_splay_tree<Accessors>::splay_next_node ()
436 return splay_neighbor<1> ();
439 // See the comment above the declaration.
440 template<typename Accessors>
442 rooted_splay_tree<Accessors>::splay_min_node ()
444 if (m_root && get_child (m_root, 0))
446 m_root = parent::template splay_limit<0> (m_root);
447 set_parent (m_root, node_type ());
451 // See the comment above the declaration.
452 template<typename Accessors>
454 rooted_splay_tree<Accessors>::splay_max_node ()
456 if (m_root && get_child (m_root, 1))
458 m_root = parent::template splay_limit<1> (m_root);
459 set_parent (m_root, node_type ());
463 // See the comment above the declaration.
464 template<typename Accessors>
465 inline typename rooted_splay_tree<Accessors>::node_type
466 rooted_splay_tree<Accessors>::min_node ()
472 // See the comment above the declaration.
473 template<typename Accessors>
474 inline typename rooted_splay_tree<Accessors>::node_type
475 rooted_splay_tree<Accessors>::max_node ()
481 // See the comment above the declaration.
482 template<typename Accessors>
483 template<typename Comparator>
485 rooted_splay_tree<Accessors>::lookup (Comparator compare)
486 -> decltype (compare (m_root))
488 // This essentially follows the simpilfied top-down method described
489 // in Sleator and Tarjan's "Self-adjusting Binary Search Trees", but
490 // with the complication that the comparisons are done only once.
491 using result_type = decltype (compare (m_root));
493 // The roots of the left and right trees.
494 node_type link_left_root = node_type ();
495 node_type link_right_root = node_type ();
497 // Where to add new nodes to the left and right trees.
498 node_type *link_left_ptr = &link_left_root;
499 node_type *link_right_ptr = &link_right_root;
501 // The nodes that contain *LINK_LEFT_PTR and *LINK_RIGHT_PTR,
502 // once they no longer point to the roots above.
503 node_type link_left_parent = node_type ();
504 node_type link_right_parent = node_type ();
506 auto link_left = [&](node_type node)
508 *link_left_ptr = node;
509 link_left_ptr = &Accessors::child (node, 1);
510 set_parent (node, link_left_parent);
511 link_left_parent = node;
514 auto link_right = [&](node_type node)
516 *link_right_ptr = node;
517 link_right_ptr = &Accessors::child (node, 0);
518 set_parent (node, link_right_parent);
519 link_right_parent = node;
522 node_type node = m_root;
523 node_type parent = node_type ();
525 result_type old_result = 0;
528 // OLD_RESULT is 0 if NODE is the root of the middle tree.
529 // Otherwise, PARENT is the root of the middle tree and OLD_RESULT
530 // is how it compared.
533 // < 0 if we want something smaller.
534 // = 0 if we found the right node.
535 // > 0 if we want something bigger.
536 result = compare (node);
541 // SEARCH < NODE < PARENT
543 // Promote NODE (rotate right).
544 promote_child (parent, 0, node);
545 node_type next = get_child (node, 0);
551 // NEXT is now the root of the middle tree.
557 // SEARCH >= NODE, NODE < PARENT
560 else if (old_result > 0)
564 // SEARCH > NODE > PARENT
566 // Promote NODE (rotate left).
567 promote_child (parent, 1, node);
568 node_type next = get_child (node, 1);
574 // NEXT is now the root of the middle tree.
580 // SEARCH <= NODE, NODE > PARENT
584 // Microoptimization to allow NODE to be read even if RESULT == 0.
585 node_type next = get_child (node, result >= 0);
586 if (result == 0 || !next)
589 // NODE is now the root of the tree.
595 node_type new_left = link_left_root;
596 node_type new_right = link_right_root;
600 node_type old_left = get_child (node, 0);
601 *link_left_ptr = old_left;
603 set_parent (old_left, link_left_parent);
604 set_child (node, 0, new_left);
609 node_type old_right = get_child (node, 1);
610 *link_right_ptr = old_right;
612 set_parent (old_right, link_right_parent);
613 set_child (node, 1, new_right);
616 set_parent (node, node_type ());
621 // See the comment above the declaration.
622 template<typename Accessors>
623 template<typename LeftPredicate, typename RightPredicate>
625 rooted_splay_tree<Accessors>::lookup (LeftPredicate want_something_smaller,
626 RightPredicate want_something_bigger)
628 // This essentially follows the simpilfied top-down method described
629 // in Sleator and Tarjan's "Self-adjusting Binary Search Trees"
630 // (and follows it more closely than the single-comparator version above).
632 // The roots of the left and right trees.
633 node_type link_left_root = node_type ();
634 node_type link_right_root = node_type ();
636 // Where to add new nodes to the left and right trees.
637 node_type *link_left_ptr = &link_left_root;
638 node_type *link_right_ptr = &link_right_root;
640 // The nodes that contain *LINK_LEFT_PTR and *LINK_RIGHT_PTR,
641 // once they no longer point to the roots above.
642 node_type link_left_parent = node_type ();
643 node_type link_right_parent = node_type ();
645 node_type node = m_root;
649 // NODE is the root of the middle tree.
650 if (want_something_smaller (node))
653 node_type next = get_child (node, 0);
657 if (want_something_smaller (next))
659 // Promote NODE (rotate right).
660 promote_child (node, 0, next);
662 next = get_child (node, 0);
667 // Add NODE to the right tree (link right).
668 *link_right_ptr = node;
669 link_right_ptr = &Accessors::child (node, 0);
670 set_parent (node, link_right_parent);
671 link_right_parent = node;
675 else if (want_something_bigger (node))
678 node_type next = get_child (node, 1);
682 if (want_something_bigger (next))
684 // Promote NODE (rotate left).
685 promote_child (node, 1, next);
687 next = get_child (node, 1);
692 // Add NODE to the left tree (link left).
693 *link_left_ptr = node;
694 link_left_ptr = &Accessors::child (node, 1);
695 set_parent (node, link_left_parent);
696 link_left_parent = node;
707 node_type new_left = link_left_root;
708 node_type new_right = link_right_root;
712 node_type old_left = get_child (node, 0);
713 *link_left_ptr = old_left;
715 set_parent (old_left, link_left_parent);
716 set_child (node, 0, new_left);
721 node_type old_right = get_child (node, 1);
722 *link_right_ptr = old_right;
724 set_parent (old_right, link_right_parent);
725 set_child (node, 1, new_right);
728 set_parent (node, node_type ());
733 // See the comment above the declaration.
734 template<typename Accessors>
735 template<typename Printer>
737 rooted_splay_tree<Accessors>::print (pretty_printer *pp, Printer printer) const
739 print (pp, m_root, printer);
742 // Return NODE's current parent.
743 template<typename Accessors>
744 inline typename rootless_splay_tree<Accessors>::node_type
745 rootless_splay_tree<Accessors>::get_parent (node_type node)
747 return Accessors::parent (node);
750 // CHILD is known to be a child of PARENT. Return which index it has.
751 template<typename Accessors>
753 rootless_splay_tree<Accessors>::child_index (node_type parent, node_type child)
755 return get_child (parent, 1) == child;
758 // If N == 1, implement splay_known_max_node, otherwise implement
759 // splay_known_min_node.
760 template<typename Accessors>
761 template<unsigned int N>
763 rootless_splay_tree<Accessors>::splay_known_limit (node_type node)
765 node_type child = node;
766 node_type parent = get_parent (child);
771 // At this point, NODE conceptually replaces CHILD as a child of
772 // PARENT, but we haven't yet updated PARENT accordingly.
773 if (node_type grandparent = get_parent (parent))
775 node_type greatgrandparent = get_parent (grandparent);
776 promote_child (grandparent, N, parent);
777 promote_child (parent, N, node);
779 parent = greatgrandparent;
783 promote_child (parent, N, node);
787 set_parent (node, node_type ());
790 // See the comment above the declaration.
791 template<typename Accessors>
792 typename rootless_splay_tree<Accessors>::node_type
793 rootless_splay_tree<Accessors>::remove_node (node_type node)
795 node_type replacement = parent::remove_node_internal (node);
796 if (node_type parent = get_parent (node))
797 set_child (parent, child_index (parent, node), replacement);
798 else if (replacement)
799 set_parent (replacement, node_type ());
800 // Clear the links from NODE.
801 set_parent (node, node_type ());
802 set_child (node, 0, node_type ());
803 set_child (node, 1, node_type ());
807 // See the comment above the declaration.
808 template<typename Accessors>
810 rootless_splay_tree<Accessors>::splay (node_type node)
812 node_type child = node;
813 node_type parent = get_parent (child);
819 // At this point, NODE conceptually replaces CHILD as a child of
820 // PARENT, but we haven't yet updated PARENT accordingly.
821 unsigned int index = child_index (parent, child);
822 if (node_type grandparent = get_parent (parent))
824 node_type greatgrandparent = get_parent (grandparent);
825 unsigned int parent_index = child_index (grandparent, parent);
826 if (index == parent_index)
828 promote_child (grandparent, parent_index, parent);
829 promote_child (parent, index, node);
833 promote_child (parent, index, node);
834 promote_child (grandparent, parent_index, node);
837 parent = greatgrandparent;
841 promote_child (parent, index, node);
846 set_parent (node, node_type ());
849 // See the comment above the declaration.
850 template<typename Accessors>
852 rootless_splay_tree<Accessors>::splay_known_min_node (node_type node)
854 splay_known_limit<0> (node);
857 // See the comment above the declaration.
858 template<typename Accessors>
860 rootless_splay_tree<Accessors>::splay_known_max_node (node_type node)
862 splay_known_limit<1> (node);
865 // See the comment above the declaration.
866 template<typename Accessors>
867 template<typename DefaultResult, typename Predicate>
869 rootless_splay_tree<Accessors>::
870 splay_and_search (node_type node, DefaultResult default_result,
872 -> decltype (predicate (node, 0))
874 using Result = decltype (predicate (node, 0));
876 node_type child = node;
877 node_type parent = get_parent (child);
879 return default_result;
883 // At this point, NODE conceptually replaces CHILD as a child of
884 // PARENT, but we haven't yet updated PARENT accordingly.
885 unsigned int index = child_index (parent, child);
886 if (Result result = predicate (parent, index))
888 set_child (parent, index, node);
891 if (node_type grandparent = get_parent (parent))
893 node_type greatgrandparent = get_parent (grandparent);
894 unsigned int parent_index = child_index (grandparent, parent);
895 if (Result result = predicate (grandparent, parent_index))
897 set_child (parent, index, node);
900 if (index == parent_index)
902 promote_child (grandparent, parent_index, parent);
903 promote_child (parent, index, node);
907 promote_child (parent, index, node);
908 promote_child (grandparent, parent_index, node);
911 parent = greatgrandparent;
915 promote_child (parent, index, node);
920 set_parent (node, node_type ());
921 return default_result;
924 // Splay NODE1 looking to see if one of its ancestors is NODE2. If it is,
925 // return -1 if NODE1 comes before NODE2 or 1 if NODE1 comes after NODE2.
926 // Return 0 if NODE2 is not an ancestor of NODE1.
927 template<typename Accessors>
929 rootless_splay_tree<Accessors>::compare_nodes_one_way (node_type node1,
932 auto compare = [&](node_type parent, unsigned int index) -> int
935 return index ? 1 : -1;
938 return splay_and_search (node1, 0, compare);
941 // See the comment above the declaration.
942 template<typename Accessors>
944 rootless_splay_tree<Accessors>::compare_nodes (node_type node1,
950 // Splay NODE1 looking for NODE2.
951 int cmp = compare_nodes_one_way (node1, node2);
955 // That failed, but NODE1 is now the root of the tree. Splay NODE2
956 // to see on which side of NODE1 it falls.
957 cmp = compare_nodes_one_way (node2, node1);
958 gcc_checking_assert (cmp);