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 14 #include "clang/Rewrite/DeltaTree.h" 15 #include "llvm/Support/Casting.h" 16 #include <cstring> 17 #include <cstdio> 18 using namespace clang; 19 using llvm::cast; 20 using llvm::dyn_cast; 21 22 namespace { 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 43 namespace { 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 60 61 struct InsertResult { 62 DeltaTreeNode *LHS, *RHS; 63 SourceDelta Split; 64 }; 65 66 67 namespace { 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) 96 : NumValuesUsed(0), IsLeaf(isLeaf), FullDelta(0) {} 97 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 112 /// 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 118 void DoSplit(InsertResult &InsertRes); 119 120 121 /// 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 131 namespace { 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 150 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 159 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(); } 170 }; 171 } 172 173 174 /// Destroy - A 'virtual' destructor. 175 void 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. 184 void 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 194 /// 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. 198 bool DeltaTreeNode::DoInsertion(unsigned FileIndex, int Delta, 199 InsertResult *InsertRes) { 200 // 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 209 // value into the pre-existing record and finish early. 210 if (i != e && getValue(i).FileLoc == FileIndex) { 211 // 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. 215 Values[i].Delta += Delta; 216 return false; 217 } 218 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; 230 } 231 232 // 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; 242 } 243 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; 307 } 308 309 /// 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. 312 void 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 351 352 //===----------------------------------------------------------------------===// 353 // DeltaTree Implementation 354 //===----------------------------------------------------------------------===// 355 356 //#define VERIFY_TREE 357 358 #ifdef VERIFY_TREE 359 /// VerifyTree - Walk the btree performing assertions on various properties to 360 /// verify consistency. This is useful for debugging new changes to the tree. 361 static 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 } 400 #endif // VERIFY_TREE 401 402 static DeltaTreeNode *getRoot(void *Root) { 403 return (DeltaTreeNode*)Root; 404 } 405 406 DeltaTree::DeltaTree() { 407 Root = new DeltaTreeNode(); 408 } 409 DeltaTree::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 416 DeltaTree::~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. 423 int 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 467 /// 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. 470 void DeltaTree::AddDelta(unsigned FileIndex, int Delta) { 471 assert(Delta && "Adding a noop?"); 472 DeltaTreeNode *MyRoot = getRoot(Root); 473 474 InsertResult InsertRes; 475 if (MyRoot->DoInsertion(FileIndex, Delta, &InsertRes)) { 476 Root = MyRoot = new DeltaTreeInteriorNode(InsertRes); 477 } 478 479 #ifdef VERIFY_TREE 480 VerifyTree(MyRoot); 481 #endif 482 } 483 484