LLVM 24.0.0git
SuffixTree.cpp
Go to the documentation of this file.
1//===- llvm/Support/SuffixTree.cpp - Implement Suffix Tree ------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Suffix Tree class.
10//
11//===----------------------------------------------------------------------===//
12
17
18using namespace llvm;
19
20/// \returns the number of elements in the substring associated with \p N.
22 assert(N && "Got a null node?");
24 if (Internal->isRoot())
25 return 0;
26 return N->getEndIdx() - N->getStartIdx() + 1;
27}
28
32 Root = insertRoot();
33 Active.Node = Root;
34
35 // Keep track of the number of suffixes we have to add of the current
36 // prefix.
37 unsigned SuffixesToAdd = 0;
38
39 // Construct the suffix tree iteratively on each prefix of the string.
40 // PfxEndIdx is the end index of the current prefix.
41 // End is one past the last element in the string.
42 for (unsigned PfxEndIdx = 0, End = Str.size(); PfxEndIdx < End; PfxEndIdx++) {
43 SuffixesToAdd++;
44 LeafEndIdx = PfxEndIdx; // Extend each of the leaves.
45 SuffixesToAdd = extend(PfxEndIdx, SuffixesToAdd);
46 }
47
48 // Collect all leaf nodes of the suffix tree. And for each internal node,
49 // record the range of leaf nodes that are descendants of it.
51 setLeafNodes();
52}
53
54SuffixTreeNode *SuffixTree::insertLeaf(SuffixTreeInternalNode &Parent,
55 unsigned StartIdx, unsigned Edge) {
56 assert(StartIdx <= LeafEndIdx && "String can't start after it ends!");
57 auto *N = new (LeafNodeAllocator.Allocate())
58 SuffixTreeLeafNode(StartIdx, &LeafEndIdx);
59 // The suffix starts Parent.getConcatLen() elements before this edge.
60 // A later split advances the child's StartIdx by the same length added
61 // to its parent path, so the suffix start remains unchanged.
62 N->setSuffixIdx(StartIdx - Parent.getConcatLen());
63 Parent.Children[Edge] = N;
64 return N;
65}
66
68SuffixTree::insertInternalNode(SuffixTreeInternalNode *Parent,
69 unsigned StartIdx, unsigned EndIdx,
70 unsigned Edge) {
71 assert(StartIdx <= EndIdx && "String can't start after it ends!");
72 assert(!(!Parent && StartIdx != SuffixTreeNode::EmptyIdx) &&
73 "Non-root internal nodes must have parents!");
74 auto *N = new (InternalNodeAllocator.Allocate())
75 SuffixTreeInternalNode(StartIdx, EndIdx, Root);
76 if (Parent) {
77 // Path length = parent path length + edge length.
78 N->setConcatLen(Parent->getConcatLen() + (EndIdx - StartIdx + 1));
79 Parent->Children[Edge] = N;
80 }
81 return N;
82}
83
84SuffixTreeInternalNode *SuffixTree::insertRoot() {
85 return insertInternalNode(/*Parent = */ nullptr, SuffixTreeNode::EmptyIdx,
86 SuffixTreeNode::EmptyIdx, /*Edge = */ 0);
87}
88
89void SuffixTree::setLeafNodes() {
90 // A stack that keeps track of nodes to visit for post-order DFS traversal.
92 ToVisit.push_back(Root);
93
94 // This keeps track of the index of the next leaf node to be added to
95 // the LeafNodes vector of the suffix tree.
96 unsigned LeafCounter = 0;
97
98 // This keeps track of nodes whose children have been added to the stack.
99 // The value is a pair, representing a node's first and last children.
100 DenseMap<SuffixTreeInternalNode *,
101 std::pair<SuffixTreeNode *, SuffixTreeNode *>>
102 ChildrenMap;
103
104 // Traverse the tree in post-order.
105 while (!ToVisit.empty()) {
106 SuffixTreeNode *CurrNode = ToVisit.pop_back_val();
107 if (auto *CurrInternalNode = dyn_cast<SuffixTreeInternalNode>(CurrNode)) {
108 // The current node is an internal node.
109 auto I = ChildrenMap.find(CurrInternalNode);
110 if (I == ChildrenMap.end()) {
111 // This is the first time we visit this node.
112 // Its children have not been added to the stack yet.
113 // We add current node back, and add its children to the stack.
114 // We keep track of the first and last children of the current node.
115 auto J = CurrInternalNode->Children.begin();
116 if (J != CurrInternalNode->Children.end()) {
117 ToVisit.push_back(CurrNode);
118 SuffixTreeNode *FirstChild = J->second;
119 SuffixTreeNode *LastChild = nullptr;
120 for (; J != CurrInternalNode->Children.end(); ++J) {
121 LastChild = J->second;
122 ToVisit.push_back(LastChild);
123 }
124 ChildrenMap[CurrInternalNode] = {FirstChild, LastChild};
125 }
126 } else {
127 // This is the second time we visit this node.
128 // All of its children have already been processed.
129 // Now, we can set its LeftLeafIdx and RightLeafIdx;
130 auto [FirstChild, LastChild] = I->second;
131 // Get the first child to use its RightLeafIdx.
132 // The first child is the first one added to the stack, so it is
133 // the last one to be processed. Hence, the leaf descendants
134 // of the first child are assigned the largest index numbers.
135 CurrNode->setRightLeafIdx(FirstChild->getRightLeafIdx());
136 // Get the last child to use its LeftLeafIdx.
137 CurrNode->setLeftLeafIdx(LastChild->getLeftLeafIdx());
138 assert(CurrNode->getLeftLeafIdx() <= CurrNode->getRightLeafIdx() &&
139 "LeftLeafIdx should not be larger than RightLeafIdx");
140 }
141 } else {
142 // The current node is a leaf node.
143 // We can simply set its LeftLeafIdx and RightLeafIdx.
144 CurrNode->setLeftLeafIdx(LeafCounter);
145 CurrNode->setRightLeafIdx(LeafCounter);
146 ++LeafCounter;
147 auto *CurrLeafNode = cast<SuffixTreeLeafNode>(CurrNode);
148 LeafNodes.push_back(CurrLeafNode);
149 }
150 }
151}
152
153unsigned SuffixTree::extend(unsigned EndIdx, unsigned SuffixesToAdd) {
154 SuffixTreeInternalNode *NeedsLink = nullptr;
155
156 while (SuffixesToAdd > 0) {
157
158 // Are we waiting to add anything other than just the last character?
159 if (Active.Len == 0) {
160 // If not, then say the active index is the end index.
161 Active.Idx = EndIdx;
162 }
163
164 assert(Active.Idx <= EndIdx && "Start index can't be after end index!");
165
166 // The first character in the current substring we're looking at.
167 unsigned FirstChar = Str[Active.Idx];
168
169 // Have we inserted anything starting with FirstChar at the current node?
170 if (auto It = Active.Node->Children.find(FirstChar);
171 It == Active.Node->Children.end()) {
172 // If not, then we can just insert a leaf and move to the next step.
173 insertLeaf(*Active.Node, EndIdx, FirstChar);
174
175 // The active node is an internal node, and we visited it, so it must
176 // need a link if it doesn't have one.
177 if (NeedsLink) {
178 NeedsLink->setLink(Active.Node);
179 NeedsLink = nullptr;
180 }
181 } else {
182 // There's a match with FirstChar, so look for the point in the tree to
183 // insert a new node.
184 SuffixTreeNode *NextNode = It->second;
185
186 unsigned SubstringLen = numElementsInSubstring(NextNode);
187
188 // Is the current suffix we're trying to insert longer than the size of
189 // the child we want to move to?
190 if (Active.Len >= SubstringLen) {
191 // If yes, then consume the characters we've seen and move to the next
192 // node.
194 "Expected an internal node?");
195 Active.Idx += SubstringLen;
196 Active.Len -= SubstringLen;
197 Active.Node = cast<SuffixTreeInternalNode>(NextNode);
198 continue;
199 }
200
201 // Otherwise, the suffix we're trying to insert must be contained in the
202 // next node we want to move to.
203 unsigned LastChar = Str[EndIdx];
204
205 // Is the string we're trying to insert a substring of the next node?
206 if (Str[NextNode->getStartIdx() + Active.Len] == LastChar) {
207 // If yes, then we're done for this step. Remember our insertion point
208 // and move to the next end index. At this point, we have an implicit
209 // suffix tree.
210 if (NeedsLink && !Active.Node->isRoot()) {
211 NeedsLink->setLink(Active.Node);
212 NeedsLink = nullptr;
213 }
214
215 Active.Len++;
216 break;
217 }
218
219 // The string we're trying to insert isn't a substring of the next node,
220 // but matches up to a point. Split the node.
221 //
222 // For example, say we ended our search at a node n and we're trying to
223 // insert ABD. Then we'll create a new node s for AB, reduce n to just
224 // representing C, and insert a new leaf node l to represent d. This
225 // allows us to ensure that if n was a leaf, it remains a leaf.
226 //
227 // | ABC ---split---> | AB
228 // n s
229 // C / \ D
230 // n l
231
232 // The node s from the diagram
233 SuffixTreeInternalNode *SplitNode = insertInternalNode(
234 Active.Node, NextNode->getStartIdx(),
235 NextNode->getStartIdx() + Active.Len - 1, FirstChar);
236
237 // Insert the new node representing the new substring into the tree as
238 // a child of the split node. This is the node l from the diagram.
239 insertLeaf(*SplitNode, EndIdx, LastChar);
240
241 // Make the old node a child of the split node and update its start
242 // index. This is the node n from the diagram.
243 NextNode->incrementStartIdx(Active.Len);
244 SplitNode->Children[Str[NextNode->getStartIdx()]] = NextNode;
245
246 // SplitNode is an internal node, update the suffix link.
247 if (NeedsLink)
248 NeedsLink->setLink(SplitNode);
249
250 NeedsLink = SplitNode;
251 }
252
253 // We've added something new to the tree, so there's one less suffix to
254 // add.
255 SuffixesToAdd--;
256
257 if (Active.Node->isRoot()) {
258 if (Active.Len > 0) {
259 Active.Len--;
260 Active.Idx = EndIdx - SuffixesToAdd + 1;
261 }
262 } else {
263 // Start the next phase at the next smallest suffix.
264 Active.Node = Active.Node->getLink();
265 }
266 }
267
268 return SuffixesToAdd;
269}
270
271void SuffixTree::RepeatedSubstringIterator::advance() {
272 // Clear the current state. If we're at the end of the range, then this
273 // is the state we want to be in.
274 RS = RepeatedSubstring();
275 N = nullptr;
276
277 // Each leaf node represents a repeat of a string.
278 SmallVector<unsigned> RepeatedSubstringStarts;
279
280 // Continue visiting nodes until we find one which repeats more than once.
281 while (!InternalNodesToVisit.empty()) {
282 RepeatedSubstringStarts.clear();
283 auto *Curr = InternalNodesToVisit.pop_back_val();
284
285 // Keep track of the length of the string associated with the node. If
286 // it's too short, we'll quit.
287 unsigned Length = Curr->getConcatLen();
288
289 // Iterate over each child, saving internal nodes for visiting.
290 // Internal nodes represent individual strings, which may repeat.
291 for (auto &ChildPair : Curr->Children)
292 // Save all of this node's children for processing.
293 if (auto *InternalChild =
294 dyn_cast<SuffixTreeInternalNode>(ChildPair.second))
295 InternalNodesToVisit.push_back(InternalChild);
296
297 // If length of repeated substring is below threshold, then skip it.
298 if (Length < MinLength)
299 continue;
300
301 // The root never represents a repeated substring. If we're looking at
302 // that, then skip it.
303 if (Curr->isRoot())
304 continue;
305
306 // Collect leaf children or leaf descendants by OutlinerLeafDescendants.
307 if (OutlinerLeafDescendants) {
308 for (unsigned I = Curr->getLeftLeafIdx(); I <= Curr->getRightLeafIdx();
309 ++I)
310 RepeatedSubstringStarts.push_back(LeafNodes[I]->getSuffixIdx());
311 } else {
312 for (auto &ChildPair : Curr->Children)
313 if (auto *Leaf = dyn_cast<SuffixTreeLeafNode>(ChildPair.second))
314 RepeatedSubstringStarts.push_back(Leaf->getSuffixIdx());
315 }
316
317 // Do we have any repeated substrings?
318 if (RepeatedSubstringStarts.size() < 2)
319 continue;
320
321 // Yes. Update the state to reflect this, and then bail out.
322 N = Curr;
323 RS.Length = Length;
324 llvm::append_range(RS.StartIndices, RepeatedSubstringStarts);
325 break;
326 }
327 // At this point, either NewRS is an empty RepeatedSubstring, or it was
328 // set in the above loop. Similarly, N is either nullptr, or the node
329 // associated with NewRS.
330}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
#define I(x, y, z)
Definition MD5.cpp:57
static size_t numElementsInSubstring(const SuffixTreeNode *N)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
void push_back(const T &Elt)
LLVM_ABI SuffixTree(const ArrayRef< unsigned > &Str, bool OutlinerLeafDescendants=false)
Construct a suffix tree from a sequence of unsigned integers.
ArrayRef< unsigned > Str
Each element is an integer representing an instruction in the module.
Definition SuffixTree.h:44
bool OutlinerLeafDescendants
Whether to consider leaf descendants or only leaf children.
Definition SuffixTree.h:47
This is an optimization pass for GlobalISel generic memory operations.
@ Length
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
#define N
DenseMap< unsigned, SuffixTreeNode * > Children
The children of this node.
void setLink(SuffixTreeInternalNode *L)
Sets Link to L. Assumes L is not null.
A node in a suffix tree which represents a substring or suffix.
LLVM_ABI void incrementStartIdx(unsigned Inc)
Advance this node's StartIdx by Inc.
LLVM_ABI unsigned getLeftLeafIdx() const
LLVM_ABI unsigned getRightLeafIdx() const
LLVM_ABI void setRightLeafIdx(unsigned Idx)
Set the index of the right most leaf node of this node to Idx.
LLVM_ABI unsigned getConcatLen() const
static const unsigned EmptyIdx
Represents an undefined index in the suffix tree.
LLVM_ABI unsigned getStartIdx() const
LLVM_ABI void setLeftLeafIdx(unsigned Idx)
Set the index of the left most leaf node of this node to Idx.