DeltaTree.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. //===--- 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. #include "clang/Rewrite/DeltaTree.h"
  14. #include "llvm/Support/Casting.h"
  15. #include <cstring>
  16. #include <cstdio>
  17. using namespace clang;
  18. using llvm::cast;
  19. using llvm::dyn_cast;
  20. /// The DeltaTree class is a multiway search tree (BTree) structure with some
  21. /// fancy features. B-Trees are generally more memory and cache efficient
  22. /// than binary trees, because they store multiple keys/values in each node.
  23. ///
  24. /// DeltaTree implements a key/value mapping from FileIndex to Delta, allowing
  25. /// fast lookup by FileIndex. However, an added (important) bonus is that it
  26. /// can also efficiently tell us the full accumulated delta for a specific
  27. /// file offset as well, without traversing the whole tree.
  28. ///
  29. /// The nodes of the tree are made up of instances of two classes:
  30. /// DeltaTreeNode and DeltaTreeInteriorNode. The later subclasses the
  31. /// former and adds children pointers. Each node knows the full delta of all
  32. /// entries (recursively) contained inside of it, which allows us to get the
  33. /// full delta implied by a whole subtree in constant time.
  34. namespace {
  35. /// SourceDelta - As code in the original input buffer is added and deleted,
  36. /// SourceDelta records are used to keep track of how the input SourceLocation
  37. /// object is mapped into the output buffer.
  38. struct SourceDelta {
  39. unsigned FileLoc;
  40. int Delta;
  41. static SourceDelta get(unsigned Loc, int D) {
  42. SourceDelta Delta;
  43. Delta.FileLoc = Loc;
  44. Delta.Delta = D;
  45. return Delta;
  46. }
  47. };
  48. /// DeltaTreeNode - The common part of all nodes.
  49. ///
  50. class DeltaTreeNode {
  51. public:
  52. struct InsertResult {
  53. DeltaTreeNode *LHS, *RHS;
  54. SourceDelta Split;
  55. };
  56. private:
  57. friend class DeltaTreeInteriorNode;
  58. /// WidthFactor - This controls the number of K/V slots held in the BTree:
  59. /// how wide it is. Each level of the BTree is guaranteed to have at least
  60. /// WidthFactor-1 K/V pairs (except the root) and may have at most
  61. /// 2*WidthFactor-1 K/V pairs.
  62. enum { WidthFactor = 8 };
  63. /// Values - This tracks the SourceDelta's currently in this node.
  64. ///
  65. SourceDelta Values[2*WidthFactor-1];
  66. /// NumValuesUsed - This tracks the number of values this node currently
  67. /// holds.
  68. unsigned char NumValuesUsed;
  69. /// IsLeaf - This is true if this is a leaf of the btree. If false, this is
  70. /// an interior node, and is actually an instance of DeltaTreeInteriorNode.
  71. bool IsLeaf;
  72. /// FullDelta - This is the full delta of all the values in this node and
  73. /// all children nodes.
  74. int FullDelta;
  75. public:
  76. DeltaTreeNode(bool isLeaf = true)
  77. : NumValuesUsed(0), IsLeaf(isLeaf), FullDelta(0) {}
  78. bool isLeaf() const { return IsLeaf; }
  79. int getFullDelta() const { return FullDelta; }
  80. bool isFull() const { return NumValuesUsed == 2*WidthFactor-1; }
  81. unsigned getNumValuesUsed() const { return NumValuesUsed; }
  82. const SourceDelta &getValue(unsigned i) const {
  83. assert(i < NumValuesUsed && "Invalid value #");
  84. return Values[i];
  85. }
  86. SourceDelta &getValue(unsigned i) {
  87. assert(i < NumValuesUsed && "Invalid value #");
  88. return Values[i];
  89. }
  90. /// DoInsertion - Do an insertion of the specified FileIndex/Delta pair into
  91. /// this node. If insertion is easy, do it and return false. Otherwise,
  92. /// split the node, populate InsertRes with info about the split, and return
  93. /// true.
  94. bool DoInsertion(unsigned FileIndex, int Delta, InsertResult *InsertRes);
  95. void DoSplit(InsertResult &InsertRes);
  96. /// RecomputeFullDeltaLocally - Recompute the FullDelta field by doing a
  97. /// local walk over our contained deltas.
  98. void RecomputeFullDeltaLocally();
  99. void Destroy();
  100. //static inline bool classof(const DeltaTreeNode *) { return true; }
  101. };
  102. } // end anonymous namespace
  103. namespace {
  104. /// DeltaTreeInteriorNode - When isLeaf = false, a node has child pointers.
  105. /// This class tracks them.
  106. class DeltaTreeInteriorNode : public DeltaTreeNode {
  107. DeltaTreeNode *Children[2*WidthFactor];
  108. ~DeltaTreeInteriorNode() {
  109. for (unsigned i = 0, e = NumValuesUsed+1; i != e; ++i)
  110. Children[i]->Destroy();
  111. }
  112. friend class DeltaTreeNode;
  113. public:
  114. DeltaTreeInteriorNode() : DeltaTreeNode(false /*nonleaf*/) {}
  115. DeltaTreeInteriorNode(const InsertResult &IR)
  116. : DeltaTreeNode(false /*nonleaf*/) {
  117. Children[0] = IR.LHS;
  118. Children[1] = IR.RHS;
  119. Values[0] = IR.Split;
  120. FullDelta = IR.LHS->getFullDelta()+IR.RHS->getFullDelta()+IR.Split.Delta;
  121. NumValuesUsed = 1;
  122. }
  123. const DeltaTreeNode *getChild(unsigned i) const {
  124. assert(i < getNumValuesUsed()+1 && "Invalid child");
  125. return Children[i];
  126. }
  127. DeltaTreeNode *getChild(unsigned i) {
  128. assert(i < getNumValuesUsed()+1 && "Invalid child");
  129. return Children[i];
  130. }
  131. //static inline bool classof(const DeltaTreeInteriorNode *) { return true; }
  132. static inline bool classof(const DeltaTreeNode *N) { return !N->isLeaf(); }
  133. };
  134. }
  135. /// Destroy - A 'virtual' destructor.
  136. void DeltaTreeNode::Destroy() {
  137. if (isLeaf())
  138. delete this;
  139. else
  140. delete cast<DeltaTreeInteriorNode>(this);
  141. }
  142. /// RecomputeFullDeltaLocally - Recompute the FullDelta field by doing a
  143. /// local walk over our contained deltas.
  144. void DeltaTreeNode::RecomputeFullDeltaLocally() {
  145. int NewFullDelta = 0;
  146. for (unsigned i = 0, e = getNumValuesUsed(); i != e; ++i)
  147. NewFullDelta += Values[i].Delta;
  148. if (DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(this))
  149. for (unsigned i = 0, e = getNumValuesUsed()+1; i != e; ++i)
  150. NewFullDelta += IN->getChild(i)->getFullDelta();
  151. FullDelta = NewFullDelta;
  152. }
  153. /// DoInsertion - Do an insertion of the specified FileIndex/Delta pair into
  154. /// this node. If insertion is easy, do it and return false. Otherwise,
  155. /// split the node, populate InsertRes with info about the split, and return
  156. /// true.
  157. bool DeltaTreeNode::DoInsertion(unsigned FileIndex, int Delta,
  158. InsertResult *InsertRes) {
  159. // Maintain full delta for this node.
  160. FullDelta += Delta;
  161. // Find the insertion point, the first delta whose index is >= FileIndex.
  162. unsigned i = 0, e = getNumValuesUsed();
  163. while (i != e && FileIndex > getValue(i).FileLoc)
  164. ++i;
  165. // If we found an a record for exactly this file index, just merge this
  166. // value into the pre-existing record and finish early.
  167. if (i != e && getValue(i).FileLoc == FileIndex) {
  168. // NOTE: Delta could drop to zero here. This means that the delta entry is
  169. // useless and could be removed. Supporting erases is more complex than
  170. // leaving an entry with Delta=0, so we just leave an entry with Delta=0 in
  171. // the tree.
  172. Values[i].Delta += Delta;
  173. return false;
  174. }
  175. // Otherwise, we found an insertion point, and we know that the value at the
  176. // specified index is > FileIndex. Handle the leaf case first.
  177. if (isLeaf()) {
  178. if (!isFull()) {
  179. // For an insertion into a non-full leaf node, just insert the value in
  180. // its sorted position. This requires moving later values over.
  181. if (i != e)
  182. memmove(&Values[i+1], &Values[i], sizeof(Values[0])*(e-i));
  183. Values[i] = SourceDelta::get(FileIndex, Delta);
  184. ++NumValuesUsed;
  185. return false;
  186. }
  187. // Otherwise, if this is leaf is full, split the node at its median, insert
  188. // the value into one of the children, and return the result.
  189. assert(InsertRes && "No result location specified");
  190. DoSplit(*InsertRes);
  191. if (InsertRes->Split.FileLoc > FileIndex)
  192. InsertRes->LHS->DoInsertion(FileIndex, Delta, 0 /*can't fail*/);
  193. else
  194. InsertRes->RHS->DoInsertion(FileIndex, Delta, 0 /*can't fail*/);
  195. return true;
  196. }
  197. // Otherwise, this is an interior node. Send the request down the tree.
  198. DeltaTreeInteriorNode *IN = cast<DeltaTreeInteriorNode>(this);
  199. if (!IN->Children[i]->DoInsertion(FileIndex, Delta, InsertRes))
  200. return false; // If there was space in the child, just return.
  201. // Okay, this split the subtree, producing a new value and two children to
  202. // insert here. If this node is non-full, we can just insert it directly.
  203. if (!isFull()) {
  204. // Now that we have two nodes and a new element, insert the perclated value
  205. // into ourself by moving all the later values/children down, then inserting
  206. // the new one.
  207. if (i != e)
  208. memmove(&IN->Children[i+2], &IN->Children[i+1],
  209. (e-i)*sizeof(IN->Children[0]));
  210. IN->Children[i] = InsertRes->LHS;
  211. IN->Children[i+1] = InsertRes->RHS;
  212. if (e != i)
  213. memmove(&Values[i+1], &Values[i], (e-i)*sizeof(Values[0]));
  214. Values[i] = InsertRes->Split;
  215. ++NumValuesUsed;
  216. return false;
  217. }
  218. // Finally, if this interior node was full and a node is percolated up, split
  219. // ourself and return that up the chain. Start by saving all our info to
  220. // avoid having the split clobber it.
  221. IN->Children[i] = InsertRes->LHS;
  222. DeltaTreeNode *SubRHS = InsertRes->RHS;
  223. SourceDelta SubSplit = InsertRes->Split;
  224. // Do the split.
  225. DoSplit(*InsertRes);
  226. // Figure out where to insert SubRHS/NewSplit.
  227. DeltaTreeInteriorNode *InsertSide;
  228. if (SubSplit.FileLoc < InsertRes->Split.FileLoc)
  229. InsertSide = cast<DeltaTreeInteriorNode>(InsertRes->LHS);
  230. else
  231. InsertSide = cast<DeltaTreeInteriorNode>(InsertRes->RHS);
  232. // We now have a non-empty interior node 'InsertSide' to insert
  233. // SubRHS/SubSplit into. Find out where to insert SubSplit.
  234. // Find the insertion point, the first delta whose index is >SubSplit.FileLoc.
  235. i = 0; e = InsertSide->getNumValuesUsed();
  236. while (i != e && SubSplit.FileLoc > InsertSide->getValue(i).FileLoc)
  237. ++i;
  238. // Now we know that i is the place to insert the split value into. Insert it
  239. // and the child right after it.
  240. if (i != e)
  241. memmove(&InsertSide->Children[i+2], &InsertSide->Children[i+1],
  242. (e-i)*sizeof(IN->Children[0]));
  243. InsertSide->Children[i+1] = SubRHS;
  244. if (e != i)
  245. memmove(&InsertSide->Values[i+1], &InsertSide->Values[i],
  246. (e-i)*sizeof(Values[0]));
  247. InsertSide->Values[i] = SubSplit;
  248. ++InsertSide->NumValuesUsed;
  249. InsertSide->FullDelta += SubSplit.Delta + SubRHS->getFullDelta();
  250. return true;
  251. }
  252. /// DoSplit - Split the currently full node (which has 2*WidthFactor-1 values)
  253. /// into two subtrees each with "WidthFactor-1" values and a pivot value.
  254. /// Return the pieces in InsertRes.
  255. void DeltaTreeNode::DoSplit(InsertResult &InsertRes) {
  256. assert(isFull() && "Why split a non-full node?");
  257. // Since this node is full, it contains 2*WidthFactor-1 values. We move
  258. // the first 'WidthFactor-1' values to the LHS child (which we leave in this
  259. // node), propagate one value up, and move the last 'WidthFactor-1' values
  260. // into the RHS child.
  261. // Create the new child node.
  262. DeltaTreeNode *NewNode;
  263. if (DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(this)) {
  264. // If this is an interior node, also move over 'WidthFactor' children
  265. // into the new node.
  266. DeltaTreeInteriorNode *New = new DeltaTreeInteriorNode();
  267. memcpy(&New->Children[0], &IN->Children[WidthFactor],
  268. WidthFactor*sizeof(IN->Children[0]));
  269. NewNode = New;
  270. } else {
  271. // Just create the new leaf node.
  272. NewNode = new DeltaTreeNode();
  273. }
  274. // Move over the last 'WidthFactor-1' values from here to NewNode.
  275. memcpy(&NewNode->Values[0], &Values[WidthFactor],
  276. (WidthFactor-1)*sizeof(Values[0]));
  277. // Decrease the number of values in the two nodes.
  278. NewNode->NumValuesUsed = NumValuesUsed = WidthFactor-1;
  279. // Recompute the two nodes' full delta.
  280. NewNode->RecomputeFullDeltaLocally();
  281. RecomputeFullDeltaLocally();
  282. InsertRes.LHS = this;
  283. InsertRes.RHS = NewNode;
  284. InsertRes.Split = Values[WidthFactor-1];
  285. }
  286. //===----------------------------------------------------------------------===//
  287. // DeltaTree Implementation
  288. //===----------------------------------------------------------------------===//
  289. //#define VERIFY_TREE
  290. #ifdef VERIFY_TREE
  291. /// VerifyTree - Walk the btree performing assertions on various properties to
  292. /// verify consistency. This is useful for debugging new changes to the tree.
  293. static void VerifyTree(const DeltaTreeNode *N) {
  294. const DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(N);
  295. if (IN == 0) {
  296. // Verify leaves, just ensure that FullDelta matches up and the elements
  297. // are in proper order.
  298. int FullDelta = 0;
  299. for (unsigned i = 0, e = N->getNumValuesUsed(); i != e; ++i) {
  300. if (i)
  301. assert(N->getValue(i-1).FileLoc < N->getValue(i).FileLoc);
  302. FullDelta += N->getValue(i).Delta;
  303. }
  304. assert(FullDelta == N->getFullDelta());
  305. return;
  306. }
  307. // Verify interior nodes: Ensure that FullDelta matches up and the
  308. // elements are in proper order and the children are in proper order.
  309. int FullDelta = 0;
  310. for (unsigned i = 0, e = IN->getNumValuesUsed(); i != e; ++i) {
  311. const SourceDelta &IVal = N->getValue(i);
  312. const DeltaTreeNode *IChild = IN->getChild(i);
  313. if (i)
  314. assert(IN->getValue(i-1).FileLoc < IVal.FileLoc);
  315. FullDelta += IVal.Delta;
  316. FullDelta += IChild->getFullDelta();
  317. // The largest value in child #i should be smaller than FileLoc.
  318. assert(IChild->getValue(IChild->getNumValuesUsed()-1).FileLoc <
  319. IVal.FileLoc);
  320. // The smallest value in child #i+1 should be larger than FileLoc.
  321. assert(IN->getChild(i+1)->getValue(0).FileLoc > IVal.FileLoc);
  322. VerifyTree(IChild);
  323. }
  324. FullDelta += IN->getChild(IN->getNumValuesUsed())->getFullDelta();
  325. assert(FullDelta == N->getFullDelta());
  326. }
  327. #endif // VERIFY_TREE
  328. static DeltaTreeNode *getRoot(void *Root) {
  329. return (DeltaTreeNode*)Root;
  330. }
  331. DeltaTree::DeltaTree() {
  332. Root = new DeltaTreeNode();
  333. }
  334. DeltaTree::DeltaTree(const DeltaTree &RHS) {
  335. // Currently we only support copying when the RHS is empty.
  336. assert(getRoot(RHS.Root)->getNumValuesUsed() == 0 &&
  337. "Can only copy empty tree");
  338. Root = new DeltaTreeNode();
  339. }
  340. DeltaTree::~DeltaTree() {
  341. getRoot(Root)->Destroy();
  342. }
  343. /// getDeltaAt - Return the accumulated delta at the specified file offset.
  344. /// This includes all insertions or delections that occurred *before* the
  345. /// specified file index.
  346. int DeltaTree::getDeltaAt(unsigned FileIndex) const {
  347. const DeltaTreeNode *Node = getRoot(Root);
  348. int Result = 0;
  349. // Walk down the tree.
  350. while (1) {
  351. // For all nodes, include any local deltas before the specified file
  352. // index by summing them up directly. Keep track of how many were
  353. // included.
  354. unsigned NumValsGreater = 0;
  355. for (unsigned e = Node->getNumValuesUsed(); NumValsGreater != e;
  356. ++NumValsGreater) {
  357. const SourceDelta &Val = Node->getValue(NumValsGreater);
  358. if (Val.FileLoc >= FileIndex)
  359. break;
  360. Result += Val.Delta;
  361. }
  362. // If we have an interior node, include information about children and
  363. // recurse. Otherwise, if we have a leaf, we're done.
  364. const DeltaTreeInteriorNode *IN = dyn_cast<DeltaTreeInteriorNode>(Node);
  365. if (!IN) return Result;
  366. // Include any children to the left of the values we skipped, all of
  367. // their deltas should be included as well.
  368. for (unsigned i = 0; i != NumValsGreater; ++i)
  369. Result += IN->getChild(i)->getFullDelta();
  370. // If we found exactly the value we were looking for, break off the
  371. // search early. There is no need to search the RHS of the value for
  372. // partial results.
  373. if (NumValsGreater != Node->getNumValuesUsed() &&
  374. Node->getValue(NumValsGreater).FileLoc == FileIndex)
  375. return Result+IN->getChild(NumValsGreater)->getFullDelta();
  376. // Otherwise, traverse down the tree. The selected subtree may be
  377. // partially included in the range.
  378. Node = IN->getChild(NumValsGreater);
  379. }
  380. // NOT REACHED.
  381. }
  382. /// AddDelta - When a change is made that shifts around the text buffer,
  383. /// this method is used to record that info. It inserts a delta of 'Delta'
  384. /// into the current DeltaTree at offset FileIndex.
  385. void DeltaTree::AddDelta(unsigned FileIndex, int Delta) {
  386. assert(Delta && "Adding a noop?");
  387. DeltaTreeNode *MyRoot = getRoot(Root);
  388. DeltaTreeNode::InsertResult InsertRes;
  389. if (MyRoot->DoInsertion(FileIndex, Delta, &InsertRes)) {
  390. Root = MyRoot = new DeltaTreeInteriorNode(InsertRes);
  391. }
  392. #ifdef VERIFY_TREE
  393. VerifyTree(MyRoot);
  394. #endif
  395. }