Coverage Report

Created: 2018-12-11 17:59

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