blob: 291133d7543d481a0fc72f263656d66886c62061 [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>
17using namespace clang;
18using llvm::cast;
19using llvm::dyn_cast;
20
21namespace {
22 struct SourceDelta;
23 class DeltaTreeNode;
24 class DeltaTreeInteriorNode;
25}
26
27/// The DeltaTree class is a multiway search tree (BTree) structure with some
28/// fancy features. B-Trees are are generally more memory and cache efficient
29/// than binary trees, because they store multiple keys/values in each node.
30///
31/// DeltaTree implements a key/value mapping from FileIndex to Delta, allowing
32/// fast lookup by FileIndex. However, an added (important) bonus is that it
33/// can also efficiently tell us the full accumulated delta for a specific
34/// file offset as well, without traversing the whole tree.
35///
36/// The nodes of the tree are made up of instances of two classes:
37/// DeltaTreeNode and DeltaTreeInteriorNode. The later subclasses the
38/// former and adds children pointers. Each node knows the full delta of all
39/// entries (recursively) contained inside of it, which allows us to get the
40/// full delta implied by a whole subtree in constant time.
41
42namespace {
43 /// SourceDelta - As code in the original input buffer is added and deleted,
44 /// SourceDelta records are used to keep track of how the input SourceLocation
45 /// object is mapped into the output buffer.
46 struct SourceDelta {
47 unsigned FileLoc;
48 int Delta;
49
50 static SourceDelta get(unsigned Loc, int D) {
51 SourceDelta Delta;
52 Delta.FileLoc = Loc;
53 Delta.Delta = D;
54 return Delta;
55 }
56 };
57} // end anonymous namespace
58
Chris Lattnerb169e902008-04-13 08:22:30 +000059
60struct InsertResult {
61 DeltaTreeNode *LHS, *RHS;
62 SourceDelta Split;
63 InsertResult() : LHS(0) {}
64};
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 Lattnerb169e902008-04-13 08:22:30 +0000112 void DoSplit(InsertResult &InsertRes);
113
114
Chris Lattner8100d742008-04-12 22:00:40 +0000115 /// AddDeltaNonFull - Add a delta to this tree and/or it's children, knowing
116 /// that this node is not currently full.
117 void AddDeltaNonFull(unsigned FileIndex, int Delta);
118
119 /// RecomputeFullDeltaLocally - Recompute the FullDelta field by doing a
120 /// local walk over our contained deltas.
121 void RecomputeFullDeltaLocally();
122
123 void Destroy();
124
125 static inline bool classof(const DeltaTreeNode *) { return true; }
126 };
127} // end anonymous namespace
128
129namespace {
130 /// DeltaTreeInteriorNode - When isLeaf = false, a node has child pointers.
131 /// This class tracks them.
132 class DeltaTreeInteriorNode : public DeltaTreeNode {
133 DeltaTreeNode *Children[2*WidthFactor];
134 ~DeltaTreeInteriorNode() {
135 for (unsigned i = 0, e = NumValuesUsed+1; i != e; ++i)
136 Children[i]->Destroy();
137 }
138 friend class DeltaTreeNode;
139 public:
140 DeltaTreeInteriorNode() : DeltaTreeNode(false /*nonleaf*/) {}
141
142 DeltaTreeInteriorNode(DeltaTreeNode *FirstChild)
143 : DeltaTreeNode(false /*nonleaf*/) {
144 FullDelta = FirstChild->FullDelta;
145 Children[0] = FirstChild;
146 }
147
148 const DeltaTreeNode *getChild(unsigned i) const {
149 assert(i < getNumValuesUsed()+1 && "Invalid child");
150 return Children[i];
151 }
152 DeltaTreeNode *getChild(unsigned i) {
153 assert(i < getNumValuesUsed()+1 && "Invalid child");
154 return Children[i];
155 }
156
157 static inline bool classof(const DeltaTreeInteriorNode *) { return true; }
158 static inline bool classof(const DeltaTreeNode *N) { return !N->isLeaf(); }
159 private:
160 void SplitChild(unsigned ChildNo);
161 };
162}
163
164
165/// Destroy - A 'virtual' destructor.
166void DeltaTreeNode::Destroy() {
167 if (isLeaf())
168 delete this;
169 else
170 delete cast<DeltaTreeInteriorNode>(this);
171}
172
173/// RecomputeFullDeltaLocally - Recompute the FullDelta field by doing a
174/// local walk over our contained deltas.
175void DeltaTreeNode::RecomputeFullDeltaLocally() {
176 int NewFullDelta = 0;
177 for (unsigned i = 0, e = getNumValuesUsed(); i != e; ++i)
178 NewFullDelta += Values[i].Delta;
179 if (DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(this))
180 for (unsigned i = 0, e = getNumValuesUsed()+1; i != e; ++i)
181 NewFullDelta += IN->getChild(i)->getFullDelta();
182 FullDelta = NewFullDelta;
183}
184
185
186/// AddDeltaNonFull - Add a delta to this tree and/or it's children, knowing
187/// that this node is not currently full.
188void DeltaTreeNode::AddDeltaNonFull(unsigned FileIndex, int Delta) {
189 assert(!isFull() && "AddDeltaNonFull on a full tree?");
190
191 // Maintain full delta for this node.
192 FullDelta += Delta;
193
194 // Find the insertion point, the first delta whose index is >= FileIndex.
195 unsigned i = 0, e = getNumValuesUsed();
196 while (i != e && FileIndex > getValue(i).FileLoc)
197 ++i;
198
199 // If we found an a record for exactly this file index, just merge this
200 // value into the preexisting record and finish early.
201 if (i != e && getValue(i).FileLoc == FileIndex) {
202 // NOTE: Delta could drop to zero here. This means that the next delta
203 // entry is useless and could be removed. Supporting erases is
204 // significantly more complex though, so we just leave an entry with
205 // Delta=0 in the tree.
206 Values[i].Delta += Delta;
207 return;
208 }
209
210 if (DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(this)) {
211 // Insertion into an interior node propagates the value down to a child.
212 DeltaTreeNode *Child = IN->getChild(i);
213
214 // If the child tree is full, split it, pulling an element up into our
215 // node.
216 if (Child->isFull()) {
217 IN->SplitChild(i);
218 SourceDelta &MedianVal = getValue(i);
219
220 // If the median value we pulled up is exactly our insert position, add
221 // the delta and return.
222 if (MedianVal.FileLoc == FileIndex) {
223 MedianVal.Delta += Delta;
224 return;
225 }
226
227 // If the median value pulled up is less than our current search point,
228 // include those deltas and search down the RHS now.
229 if (MedianVal.FileLoc < FileIndex)
230 Child = IN->getChild(i+1);
231 }
232
233 Child->AddDeltaNonFull(FileIndex, Delta);
234 } else {
235 // For an insertion into a non-full leaf node, just insert the value in
236 // its sorted position. This requires moving later values over.
237 if (i != e)
238 memmove(&Values[i+1], &Values[i], sizeof(Values[0])*(e-i));
239 Values[i] = SourceDelta::get(FileIndex, Delta);
240 ++NumValuesUsed;
241 }
242}
243
244/// SplitChild - At this point, we know that the current node is not full and
245/// that the specified child of this node is. Split the child in half at its
246/// median, propagating one value up into us. Child may be either an interior
247/// or leaf node.
248void DeltaTreeInteriorNode::SplitChild(unsigned ChildNo) {
249 DeltaTreeNode *Child = getChild(ChildNo);
250 assert(!isFull() && Child->isFull() && "Inconsistent constraints");
251
Chris Lattnerb169e902008-04-13 08:22:30 +0000252 InsertResult SplitRes;
253 Child->DoSplit(SplitRes);
Chris Lattner8100d742008-04-12 22:00:40 +0000254
255 // Now that we have two nodes and a new element, insert the median value
256 // into ourself by moving all the later values/children down, then inserting
257 // the new one.
258 if (getNumValuesUsed() != ChildNo)
259 memmove(&Children[ChildNo+2], &Children[ChildNo+1],
260 (getNumValuesUsed()-ChildNo)*sizeof(Children[0]));
Chris Lattnerb169e902008-04-13 08:22:30 +0000261 Children[ChildNo] = SplitRes.LHS;
262 Children[ChildNo+1] = SplitRes.RHS;
Chris Lattner8100d742008-04-12 22:00:40 +0000263
264 if (getNumValuesUsed() != ChildNo)
265 memmove(&Values[ChildNo+1], &Values[ChildNo],
266 (getNumValuesUsed()-ChildNo)*sizeof(Values[0]));
Chris Lattnerb169e902008-04-13 08:22:30 +0000267 Values[ChildNo] = SplitRes.Split;
Chris Lattner8100d742008-04-12 22:00:40 +0000268 ++NumValuesUsed;
269}
270
Chris Lattnerb169e902008-04-13 08:22:30 +0000271void DeltaTreeNode::DoSplit(InsertResult &InsertRes) {
272 assert(isFull() && "Why split a non-full node?");
273
274 // Since this node is full, it contains 2*WidthFactor-1 values. We move
275 // the first 'WidthFactor-1' values to the LHS child (which we leave in this
276 // node), propagate one value up, and move the last 'WidthFactor-1' values
277 // into the RHS child.
278
279 // Create the new child node.
280 DeltaTreeNode *NewNode;
281 if (DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(this)) {
282 // If this is an interior node, also move over 'WidthFactor' children
283 // into the new node.
284 DeltaTreeInteriorNode *New = new DeltaTreeInteriorNode();
285 memcpy(&New->Children[0], &IN->Children[WidthFactor],
286 WidthFactor*sizeof(IN->Children[0]));
287 NewNode = New;
288 } else {
289 // Just create the new leaf node.
290 NewNode = new DeltaTreeNode();
291 }
292
293 // Move over the last 'WidthFactor-1' values from here to NewNode.
294 memcpy(&NewNode->Values[0], &Values[WidthFactor],
295 (WidthFactor-1)*sizeof(Values[0]));
296
297 // Decrease the number of values in the two nodes.
298 NewNode->NumValuesUsed = NumValuesUsed = WidthFactor-1;
299
300 // Recompute the two nodes' full delta.
301 NewNode->RecomputeFullDeltaLocally();
302 RecomputeFullDeltaLocally();
303
304 InsertRes.LHS = this;
305 InsertRes.RHS = NewNode;
306 InsertRes.Split = Values[WidthFactor-1];
307}
308
309
Chris Lattner8100d742008-04-12 22:00:40 +0000310
311//===----------------------------------------------------------------------===//
312// DeltaTree Implementation
313//===----------------------------------------------------------------------===//
314
Chris Lattner22cb2822008-04-12 22:04:18 +0000315//#define VERIFY_TREE
Chris Lattner8100d742008-04-12 22:00:40 +0000316
Chris Lattner22cb2822008-04-12 22:04:18 +0000317#ifdef VERIFY_TREE
Chris Lattner8100d742008-04-12 22:00:40 +0000318/// VerifyTree - Walk the btree performing assertions on various properties to
319/// verify consistency. This is useful for debugging new changes to the tree.
320static void VerifyTree(const DeltaTreeNode *N) {
321 const DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(N);
322 if (IN == 0) {
323 // Verify leaves, just ensure that FullDelta matches up and the elements
324 // are in proper order.
325 int FullDelta = 0;
326 for (unsigned i = 0, e = N->getNumValuesUsed(); i != e; ++i) {
327 if (i)
328 assert(N->getValue(i-1).FileLoc < N->getValue(i).FileLoc);
329 FullDelta += N->getValue(i).Delta;
330 }
331 assert(FullDelta == N->getFullDelta());
332 return;
333 }
334
335 // Verify interior nodes: Ensure that FullDelta matches up and the
336 // elements are in proper order and the children are in proper order.
337 int FullDelta = 0;
338 for (unsigned i = 0, e = IN->getNumValuesUsed(); i != e; ++i) {
339 const SourceDelta &IVal = N->getValue(i);
340 const DeltaTreeNode *IChild = IN->getChild(i);
341 if (i)
342 assert(IN->getValue(i-1).FileLoc < IVal.FileLoc);
343 FullDelta += IVal.Delta;
344 FullDelta += IChild->getFullDelta();
345
346 // The largest value in child #i should be smaller than FileLoc.
347 assert(IChild->getValue(IChild->getNumValuesUsed()-1).FileLoc <
348 IVal.FileLoc);
349
350 // The smallest value in child #i+1 should be larger than FileLoc.
351 assert(IN->getChild(i+1)->getValue(0).FileLoc > IVal.FileLoc);
352 VerifyTree(IChild);
353 }
354
355 FullDelta += IN->getChild(IN->getNumValuesUsed())->getFullDelta();
356
357 assert(FullDelta == N->getFullDelta());
358}
Chris Lattner22cb2822008-04-12 22:04:18 +0000359#endif // VERIFY_TREE
Chris Lattner8100d742008-04-12 22:00:40 +0000360
361static DeltaTreeNode *getRoot(void *Root) {
362 return (DeltaTreeNode*)Root;
363}
364
365DeltaTree::DeltaTree() {
366 Root = new DeltaTreeNode();
367}
368DeltaTree::DeltaTree(const DeltaTree &RHS) {
369 // Currently we only support copying when the RHS is empty.
370 assert(getRoot(RHS.Root)->getNumValuesUsed() == 0 &&
371 "Can only copy empty tree");
372 Root = new DeltaTreeNode();
373}
374
375DeltaTree::~DeltaTree() {
376 getRoot(Root)->Destroy();
377}
378
379/// getDeltaAt - Return the accumulated delta at the specified file offset.
380/// This includes all insertions or delections that occurred *before* the
381/// specified file index.
382int DeltaTree::getDeltaAt(unsigned FileIndex) const {
383 const DeltaTreeNode *Node = getRoot(Root);
384
385 int Result = 0;
386
387 // Walk down the tree.
388 while (1) {
389 // For all nodes, include any local deltas before the specified file
390 // index by summing them up directly. Keep track of how many were
391 // included.
392 unsigned NumValsGreater = 0;
393 for (unsigned e = Node->getNumValuesUsed(); NumValsGreater != e;
394 ++NumValsGreater) {
395 const SourceDelta &Val = Node->getValue(NumValsGreater);
396
397 if (Val.FileLoc >= FileIndex)
398 break;
399 Result += Val.Delta;
400 }
401
402 // If we have an interior node, include information about children and
403 // recurse. Otherwise, if we have a leaf, we're done.
404 const DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(Node);
405 if (!IN) return Result;
406
407 // Include any children to the left of the values we skipped, all of
408 // their deltas should be included as well.
409 for (unsigned i = 0; i != NumValsGreater; ++i)
410 Result += IN->getChild(i)->getFullDelta();
411
412 // If we found exactly the value we were looking for, break off the
413 // search early. There is no need to search the RHS of the value for
414 // partial results.
415 if (NumValsGreater != Node->getNumValuesUsed() &&
416 Node->getValue(NumValsGreater).FileLoc == FileIndex)
417 return Result;
418
419 // Otherwise, traverse down the tree. The selected subtree may be
420 // partially included in the range.
421 Node = IN->getChild(NumValsGreater);
422 }
423 // NOT REACHED.
424}
425
426
427/// AddDelta - When a change is made that shifts around the text buffer,
428/// this method is used to record that info. It inserts a delta of 'Delta'
429/// into the current DeltaTree at offset FileIndex.
430void DeltaTree::AddDelta(unsigned FileIndex, int Delta) {
431 assert(Delta && "Adding a noop?");
Chris Lattnerb169e902008-04-13 08:22:30 +0000432 DeltaTreeNode *MyRoot = getRoot(Root);
Chris Lattner8100d742008-04-12 22:00:40 +0000433
434 // If the root is full, create a new dummy (non-empty) interior node that
435 // points to it, allowing the old root to be split.
Chris Lattnerb169e902008-04-13 08:22:30 +0000436 if (MyRoot->isFull())
437 Root = MyRoot = new DeltaTreeInteriorNode(MyRoot);
Chris Lattner8100d742008-04-12 22:00:40 +0000438
Chris Lattnerb169e902008-04-13 08:22:30 +0000439 MyRoot->AddDeltaNonFull(FileIndex, Delta);
Chris Lattner8100d742008-04-12 22:00:40 +0000440
Chris Lattner22cb2822008-04-12 22:04:18 +0000441#ifdef VERIFY_TREE
Chris Lattnerb169e902008-04-13 08:22:30 +0000442 VerifyTree(MyRoot);
Chris Lattner22cb2822008-04-12 22:04:18 +0000443#endif
Chris Lattner8100d742008-04-12 22:00:40 +0000444}
445