DeltaTree.cpp 16 KB

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