blob: dd096c2613d08edfe0760874805e8ee536e359ce [file] [log] [blame]
Chris Lattner8100d742008-04-12 22:00:40 +00001//===--- DeltaTree.cpp - B-Tree for Rewrite Delta tracking ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the DeltaTree and related classes.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Rewrite/DeltaTree.h"
15#include "llvm/Support/Casting.h"
16#include <cstring>
Chris Lattner3b7ff0d2008-04-13 08:52:45 +000017#include <cstdio>
Chris Lattner8100d742008-04-12 22:00:40 +000018using namespace clang;
19using llvm::cast;
20using llvm::dyn_cast;
21
22namespace {
23 struct SourceDelta;
24 class DeltaTreeNode;
25 class DeltaTreeInteriorNode;
26}
27
28/// The DeltaTree class is a multiway search tree (BTree) structure with some
29/// fancy features. B-Trees are are generally more memory and cache efficient
30/// than binary trees, because they store multiple keys/values in each node.
31///
32/// DeltaTree implements a key/value mapping from FileIndex to Delta, allowing
33/// fast lookup by FileIndex. However, an added (important) bonus is that it
34/// can also efficiently tell us the full accumulated delta for a specific
35/// file offset as well, without traversing the whole tree.
36///
37/// The nodes of the tree are made up of instances of two classes:
38/// DeltaTreeNode and DeltaTreeInteriorNode. The later subclasses the
39/// former and adds children pointers. Each node knows the full delta of all
40/// entries (recursively) contained inside of it, which allows us to get the
41/// full delta implied by a whole subtree in constant time.
42
43namespace {
44 /// SourceDelta - As code in the original input buffer is added and deleted,
45 /// SourceDelta records are used to keep track of how the input SourceLocation
46 /// object is mapped into the output buffer.
47 struct SourceDelta {
48 unsigned FileLoc;
49 int Delta;
50
51 static SourceDelta get(unsigned Loc, int D) {
52 SourceDelta Delta;
53 Delta.FileLoc = Loc;
54 Delta.Delta = D;
55 return Delta;
56 }
57 };
58} // end anonymous namespace
59
Chris Lattnerb169e902008-04-13 08:22:30 +000060
61struct InsertResult {
62 DeltaTreeNode *LHS, *RHS;
63 SourceDelta Split;
Chris Lattnerb169e902008-04-13 08:22:30 +000064};
65
66
Chris Lattner8100d742008-04-12 22:00:40 +000067namespace {
68 /// DeltaTreeNode - The common part of all nodes.
69 ///
70 class DeltaTreeNode {
71 friend class DeltaTreeInteriorNode;
72
73 /// WidthFactor - This controls the number of K/V slots held in the BTree:
74 /// how wide it is. Each level of the BTree is guaranteed to have at least
75 /// WidthFactor-1 K/V pairs (unless the whole tree is less full than that)
76 /// and may have at most 2*WidthFactor-1 K/V pairs.
77 enum { WidthFactor = 8 };
78
79 /// Values - This tracks the SourceDelta's currently in this node.
80 ///
81 SourceDelta Values[2*WidthFactor-1];
82
83 /// NumValuesUsed - This tracks the number of values this node currently
84 /// holds.
85 unsigned char NumValuesUsed;
86
87 /// IsLeaf - This is true if this is a leaf of the btree. If false, this is
88 /// an interior node, and is actually an instance of DeltaTreeInteriorNode.
89 bool IsLeaf;
90
91 /// FullDelta - This is the full delta of all the values in this node and
92 /// all children nodes.
93 int FullDelta;
94 public:
95 DeltaTreeNode(bool isLeaf = true)
Chris Lattnerb169e902008-04-13 08:22:30 +000096 : NumValuesUsed(0), IsLeaf(isLeaf), FullDelta(0) {}
Chris Lattner8100d742008-04-12 22:00:40 +000097
98 bool isLeaf() const { return IsLeaf; }
99 int getFullDelta() const { return FullDelta; }
100 bool isFull() const { return NumValuesUsed == 2*WidthFactor-1; }
101
102 unsigned getNumValuesUsed() const { return NumValuesUsed; }
103 const SourceDelta &getValue(unsigned i) const {
104 assert(i < NumValuesUsed && "Invalid value #");
105 return Values[i];
106 }
107 SourceDelta &getValue(unsigned i) {
108 assert(i < NumValuesUsed && "Invalid value #");
109 return Values[i];
110 }
111
Chris Lattner3b7ff0d2008-04-13 08:52:45 +0000112 /// DoInsertion - Do an insertion of the specified FileIndex/Delta pair into
113 /// this node. If insertion is easy, do it and return false. Otherwise,
114 /// split the node, populate InsertRes with info about the split, and return
115 /// true.
116 bool DoInsertion(unsigned FileIndex, int Delta, InsertResult *InsertRes);
117
Chris Lattnerb169e902008-04-13 08:22:30 +0000118 void DoSplit(InsertResult &InsertRes);
119
120
Chris Lattner8100d742008-04-12 22:00:40 +0000121 /// RecomputeFullDeltaLocally - Recompute the FullDelta field by doing a
122 /// local walk over our contained deltas.
123 void RecomputeFullDeltaLocally();
124
125 void Destroy();
126
127 static inline bool classof(const DeltaTreeNode *) { return true; }
128 };
129} // end anonymous namespace
130
131namespace {
132 /// DeltaTreeInteriorNode - When isLeaf = false, a node has child pointers.
133 /// This class tracks them.
134 class DeltaTreeInteriorNode : public DeltaTreeNode {
135 DeltaTreeNode *Children[2*WidthFactor];
136 ~DeltaTreeInteriorNode() {
137 for (unsigned i = 0, e = NumValuesUsed+1; i != e; ++i)
138 Children[i]->Destroy();
139 }
140 friend class DeltaTreeNode;
141 public:
142 DeltaTreeInteriorNode() : DeltaTreeNode(false /*nonleaf*/) {}
143
144 DeltaTreeInteriorNode(DeltaTreeNode *FirstChild)
145 : DeltaTreeNode(false /*nonleaf*/) {
146 FullDelta = FirstChild->FullDelta;
147 Children[0] = FirstChild;
148 }
149
Chris Lattner3b7ff0d2008-04-13 08:52:45 +0000150 DeltaTreeInteriorNode(const InsertResult &IR)
151 : DeltaTreeNode(false /*nonleaf*/) {
152 Children[0] = IR.LHS;
153 Children[1] = IR.RHS;
154 Values[0] = IR.Split;
155 FullDelta = IR.LHS->getFullDelta()+IR.RHS->getFullDelta()+IR.Split.Delta;
156 NumValuesUsed = 1;
157 }
158
Chris Lattner8100d742008-04-12 22:00:40 +0000159 const DeltaTreeNode *getChild(unsigned i) const {
160 assert(i < getNumValuesUsed()+1 && "Invalid child");
161 return Children[i];
162 }
163 DeltaTreeNode *getChild(unsigned i) {
164 assert(i < getNumValuesUsed()+1 && "Invalid child");
165 return Children[i];
166 }
167
168 static inline bool classof(const DeltaTreeInteriorNode *) { return true; }
169 static inline bool classof(const DeltaTreeNode *N) { return !N->isLeaf(); }
Chris Lattner8100d742008-04-12 22:00:40 +0000170 };
171}
172
173
174/// Destroy - A 'virtual' destructor.
175void DeltaTreeNode::Destroy() {
176 if (isLeaf())
177 delete this;
178 else
179 delete cast<DeltaTreeInteriorNode>(this);
180}
181
182/// RecomputeFullDeltaLocally - Recompute the FullDelta field by doing a
183/// local walk over our contained deltas.
184void DeltaTreeNode::RecomputeFullDeltaLocally() {
185 int NewFullDelta = 0;
186 for (unsigned i = 0, e = getNumValuesUsed(); i != e; ++i)
187 NewFullDelta += Values[i].Delta;
188 if (DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(this))
189 for (unsigned i = 0, e = getNumValuesUsed()+1; i != e; ++i)
190 NewFullDelta += IN->getChild(i)->getFullDelta();
191 FullDelta = NewFullDelta;
192}
193
Chris Lattner3b7ff0d2008-04-13 08:52:45 +0000194/// DoInsertion - Do an insertion of the specified FileIndex/Delta pair into
195/// this node. If insertion is easy, do it and return false. Otherwise,
196/// split the node, populate InsertRes with info about the split, and return
197/// true.
198bool DeltaTreeNode::DoInsertion(unsigned FileIndex, int Delta,
199 InsertResult *InsertRes) {
Chris Lattner8100d742008-04-12 22:00:40 +0000200 // Maintain full delta for this node.
201 FullDelta += Delta;
202
203 // Find the insertion point, the first delta whose index is >= FileIndex.
204 unsigned i = 0, e = getNumValuesUsed();
205 while (i != e && FileIndex > getValue(i).FileLoc)
206 ++i;
207
208 // If we found an a record for exactly this file index, just merge this
Chris Lattner3b7ff0d2008-04-13 08:52:45 +0000209 // value into the pre-existing record and finish early.
Chris Lattner8100d742008-04-12 22:00:40 +0000210 if (i != e && getValue(i).FileLoc == FileIndex) {
Chris Lattner3b7ff0d2008-04-13 08:52:45 +0000211 // NOTE: Delta could drop to zero here. This means that the delta entry is
212 // useless and could be removed. Supporting erases is more complex than
213 // leaving an entry with Delta=0, so we just leave an entry with Delta=0 in
214 // the tree.
Chris Lattner8100d742008-04-12 22:00:40 +0000215 Values[i].Delta += Delta;
Chris Lattner3b7ff0d2008-04-13 08:52:45 +0000216 return false;
Chris Lattner8100d742008-04-12 22:00:40 +0000217 }
Chris Lattner3b7ff0d2008-04-13 08:52:45 +0000218
219 // Otherwise, we found an insertion point, and we know that the value at the
220 // specified index is > FileIndex. Handle the leaf case first.
221 if (isLeaf()) {
222 if (!isFull()) {
223 // For an insertion into a non-full leaf node, just insert the value in
224 // its sorted position. This requires moving later values over.
225 if (i != e)
226 memmove(&Values[i+1], &Values[i], sizeof(Values[0])*(e-i));
227 Values[i] = SourceDelta::get(FileIndex, Delta);
228 ++NumValuesUsed;
229 return false;
Chris Lattner8100d742008-04-12 22:00:40 +0000230 }
231
Chris Lattner3b7ff0d2008-04-13 08:52:45 +0000232 // Otherwise, if this is leaf is full, split the node at its median, insert
233 // the value into one of the children, and return the result.
234 assert(InsertRes && "No result location specified");
235 DoSplit(*InsertRes);
236
237 if (InsertRes->Split.FileLoc > FileIndex)
238 InsertRes->LHS->DoInsertion(FileIndex, Delta, 0 /*can't fail*/);
239 else
240 InsertRes->RHS->DoInsertion(FileIndex, Delta, 0 /*can't fail*/);
241 return true;
Chris Lattner8100d742008-04-12 22:00:40 +0000242 }
Chris Lattner3b7ff0d2008-04-13 08:52:45 +0000243
244 // Otherwise, this is an interior node. Send the request down the tree.
245 DeltaTreeInteriorNode *IN = cast<DeltaTreeInteriorNode>(this);
246 if (!IN->Children[i]->DoInsertion(FileIndex, Delta, InsertRes))
247 return false; // If there was space in the child, just return.
248
249 // Okay, this split the subtree, producing a new value and two children to
250 // insert here. If this node is non-full, we can just insert it directly.
251 if (!isFull()) {
252 // Now that we have two nodes and a new element, insert the perclated value
253 // into ourself by moving all the later values/children down, then inserting
254 // the new one.
255 if (i != e)
256 memmove(&IN->Children[i+2], &IN->Children[i+1],
257 (e-i)*sizeof(IN->Children[0]));
258 IN->Children[i] = InsertRes->LHS;
259 IN->Children[i+1] = InsertRes->RHS;
260
261 if (e != i)
262 memmove(&Values[i+1], &Values[i], (e-i)*sizeof(Values[0]));
263 Values[i] = InsertRes->Split;
264 ++NumValuesUsed;
265 return false;
266 }
267
268 // Finally, if this interior node was full and a node is percolated up, split
269 // ourself and return that up the chain. Start by saving all our info to
270 // avoid having the split clobber it.
271 IN->Children[i] = InsertRes->LHS;
272 DeltaTreeNode *SubRHS = InsertRes->RHS;
273 SourceDelta SubSplit = InsertRes->Split;
274
275 // Do the split.
276 DoSplit(*InsertRes);
277
278 // Figure out where to insert SubRHS/NewSplit.
279 DeltaTreeInteriorNode *InsertSide;
280 if (SubSplit.FileLoc < InsertRes->Split.FileLoc)
281 InsertSide = cast<DeltaTreeInteriorNode>(InsertRes->LHS);
282 else
283 InsertSide = cast<DeltaTreeInteriorNode>(InsertRes->RHS);
284
285 // We now have a non-empty interior node 'InsertSide' to insert
286 // SubRHS/SubSplit into. Find out where to insert SubSplit.
287
288 // Find the insertion point, the first delta whose index is >SubSplit.FileLoc.
289 i = 0; e = InsertSide->getNumValuesUsed();
290 while (i != e && SubSplit.FileLoc > InsertSide->getValue(i).FileLoc)
291 ++i;
292
293 // Now we know that i is the place to insert the split value into. Insert it
294 // and the child right after it.
295 if (i != e)
296 memmove(&InsertSide->Children[i+2], &InsertSide->Children[i+1],
297 (e-i)*sizeof(IN->Children[0]));
298 InsertSide->Children[i+1] = SubRHS;
299
300 if (e != i)
301 memmove(&InsertSide->Values[i+1], &InsertSide->Values[i],
302 (e-i)*sizeof(Values[0]));
303 InsertSide->Values[i] = SubSplit;
304 ++InsertSide->NumValuesUsed;
305 InsertSide->FullDelta += SubSplit.Delta + SubRHS->getFullDelta();
306 return true;
Chris Lattner8100d742008-04-12 22:00:40 +0000307}
308
Chris Lattner3b7ff0d2008-04-13 08:52:45 +0000309/// DoSplit - Split the currently full node (which has 2*WidthFactor-1 values)
310/// into two subtrees each with "WidthFactor-1" values and a pivot value.
311/// Return the pieces in InsertRes.
Chris Lattnerb169e902008-04-13 08:22:30 +0000312void DeltaTreeNode::DoSplit(InsertResult &InsertRes) {
313 assert(isFull() && "Why split a non-full node?");
314
315 // Since this node is full, it contains 2*WidthFactor-1 values. We move
316 // the first 'WidthFactor-1' values to the LHS child (which we leave in this
317 // node), propagate one value up, and move the last 'WidthFactor-1' values
318 // into the RHS child.
319
320 // Create the new child node.
321 DeltaTreeNode *NewNode;
322 if (DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(this)) {
323 // If this is an interior node, also move over 'WidthFactor' children
324 // into the new node.
325 DeltaTreeInteriorNode *New = new DeltaTreeInteriorNode();
326 memcpy(&New->Children[0], &IN->Children[WidthFactor],
327 WidthFactor*sizeof(IN->Children[0]));
328 NewNode = New;
329 } else {
330 // Just create the new leaf node.
331 NewNode = new DeltaTreeNode();
332 }
333
334 // Move over the last 'WidthFactor-1' values from here to NewNode.
335 memcpy(&NewNode->Values[0], &Values[WidthFactor],
336 (WidthFactor-1)*sizeof(Values[0]));
337
338 // Decrease the number of values in the two nodes.
339 NewNode->NumValuesUsed = NumValuesUsed = WidthFactor-1;
340
341 // Recompute the two nodes' full delta.
342 NewNode->RecomputeFullDeltaLocally();
343 RecomputeFullDeltaLocally();
344
345 InsertRes.LHS = this;
346 InsertRes.RHS = NewNode;
347 InsertRes.Split = Values[WidthFactor-1];
348}
349
350
Chris Lattner8100d742008-04-12 22:00:40 +0000351
352//===----------------------------------------------------------------------===//
353// DeltaTree Implementation
354//===----------------------------------------------------------------------===//
355
Chris Lattner22cb2822008-04-12 22:04:18 +0000356//#define VERIFY_TREE
Chris Lattner8100d742008-04-12 22:00:40 +0000357
Chris Lattner22cb2822008-04-12 22:04:18 +0000358#ifdef VERIFY_TREE
Chris Lattner8100d742008-04-12 22:00:40 +0000359/// VerifyTree - Walk the btree performing assertions on various properties to
360/// verify consistency. This is useful for debugging new changes to the tree.
361static void VerifyTree(const DeltaTreeNode *N) {
362 const DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(N);
363 if (IN == 0) {
364 // Verify leaves, just ensure that FullDelta matches up and the elements
365 // are in proper order.
366 int FullDelta = 0;
367 for (unsigned i = 0, e = N->getNumValuesUsed(); i != e; ++i) {
368 if (i)
369 assert(N->getValue(i-1).FileLoc < N->getValue(i).FileLoc);
370 FullDelta += N->getValue(i).Delta;
371 }
372 assert(FullDelta == N->getFullDelta());
373 return;
374 }
375
376 // Verify interior nodes: Ensure that FullDelta matches up and the
377 // elements are in proper order and the children are in proper order.
378 int FullDelta = 0;
379 for (unsigned i = 0, e = IN->getNumValuesUsed(); i != e; ++i) {
380 const SourceDelta &IVal = N->getValue(i);
381 const DeltaTreeNode *IChild = IN->getChild(i);
382 if (i)
383 assert(IN->getValue(i-1).FileLoc < IVal.FileLoc);
384 FullDelta += IVal.Delta;
385 FullDelta += IChild->getFullDelta();
386
387 // The largest value in child #i should be smaller than FileLoc.
388 assert(IChild->getValue(IChild->getNumValuesUsed()-1).FileLoc <
389 IVal.FileLoc);
390
391 // The smallest value in child #i+1 should be larger than FileLoc.
392 assert(IN->getChild(i+1)->getValue(0).FileLoc > IVal.FileLoc);
393 VerifyTree(IChild);
394 }
395
396 FullDelta += IN->getChild(IN->getNumValuesUsed())->getFullDelta();
397
398 assert(FullDelta == N->getFullDelta());
399}
Chris Lattner22cb2822008-04-12 22:04:18 +0000400#endif // VERIFY_TREE
Chris Lattner8100d742008-04-12 22:00:40 +0000401
402static DeltaTreeNode *getRoot(void *Root) {
403 return (DeltaTreeNode*)Root;
404}
405
406DeltaTree::DeltaTree() {
407 Root = new DeltaTreeNode();
408}
409DeltaTree::DeltaTree(const DeltaTree &RHS) {
410 // Currently we only support copying when the RHS is empty.
411 assert(getRoot(RHS.Root)->getNumValuesUsed() == 0 &&
412 "Can only copy empty tree");
413 Root = new DeltaTreeNode();
414}
415
416DeltaTree::~DeltaTree() {
417 getRoot(Root)->Destroy();
418}
419
420/// getDeltaAt - Return the accumulated delta at the specified file offset.
421/// This includes all insertions or delections that occurred *before* the
422/// specified file index.
423int DeltaTree::getDeltaAt(unsigned FileIndex) const {
424 const DeltaTreeNode *Node = getRoot(Root);
425
426 int Result = 0;
427
428 // Walk down the tree.
429 while (1) {
430 // For all nodes, include any local deltas before the specified file
431 // index by summing them up directly. Keep track of how many were
432 // included.
433 unsigned NumValsGreater = 0;
434 for (unsigned e = Node->getNumValuesUsed(); NumValsGreater != e;
435 ++NumValsGreater) {
436 const SourceDelta &Val = Node->getValue(NumValsGreater);
437
438 if (Val.FileLoc >= FileIndex)
439 break;
440 Result += Val.Delta;
441 }
442
443 // If we have an interior node, include information about children and
444 // recurse. Otherwise, if we have a leaf, we're done.
445 const DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(Node);
446 if (!IN) return Result;
447
448 // Include any children to the left of the values we skipped, all of
449 // their deltas should be included as well.
450 for (unsigned i = 0; i != NumValsGreater; ++i)
451 Result += IN->getChild(i)->getFullDelta();
452
453 // If we found exactly the value we were looking for, break off the
454 // search early. There is no need to search the RHS of the value for
455 // partial results.
456 if (NumValsGreater != Node->getNumValuesUsed() &&
457 Node->getValue(NumValsGreater).FileLoc == FileIndex)
458 return Result;
459
460 // Otherwise, traverse down the tree. The selected subtree may be
461 // partially included in the range.
462 Node = IN->getChild(NumValsGreater);
463 }
464 // NOT REACHED.
465}
466
Chris Lattner8100d742008-04-12 22:00:40 +0000467/// AddDelta - When a change is made that shifts around the text buffer,
468/// this method is used to record that info. It inserts a delta of 'Delta'
469/// into the current DeltaTree at offset FileIndex.
470void DeltaTree::AddDelta(unsigned FileIndex, int Delta) {
471 assert(Delta && "Adding a noop?");
Chris Lattnerb169e902008-04-13 08:22:30 +0000472 DeltaTreeNode *MyRoot = getRoot(Root);
Chris Lattner8100d742008-04-12 22:00:40 +0000473
Chris Lattner3b7ff0d2008-04-13 08:52:45 +0000474 InsertResult InsertRes;
475 if (MyRoot->DoInsertion(FileIndex, Delta, &InsertRes)) {
476 Root = MyRoot = new DeltaTreeInteriorNode(InsertRes);
477 }
Chris Lattner8100d742008-04-12 22:00:40 +0000478
Chris Lattner22cb2822008-04-12 22:04:18 +0000479#ifdef VERIFY_TREE
Chris Lattnerb169e902008-04-13 08:22:30 +0000480 VerifyTree(MyRoot);
Chris Lattner22cb2822008-04-12 22:04:18 +0000481#endif
Chris Lattner8100d742008-04-12 22:00:40 +0000482}
483