Coverage Report

Created: 2019-03-22 08:08

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