Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Rewrite/RewriteRope.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- RewriteRope.cpp - Rope specialized for rewriter --------------------===//
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 RewriteRope class, which is a powerful string.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Rewrite/Core/RewriteRope.h"
14
#include "clang/Basic/LLVM.h"
15
#include "llvm/Support/Casting.h"
16
#include <algorithm>
17
#include <cassert>
18
#include <cstring>
19
20
using namespace clang;
21
22
/// RewriteRope is a "strong" string class, designed to make insertions and
23
/// deletions in the middle of the string nearly constant time (really, they are
24
/// O(log N), but with a very low constant factor).
25
///
26
/// The implementation of this datastructure is a conceptual linear sequence of
27
/// RopePiece elements.  Each RopePiece represents a view on a separately
28
/// allocated and reference counted string.  This means that splitting a very
29
/// long string can be done in constant time by splitting a RopePiece that
30
/// references the whole string into two rope pieces that reference each half.
31
/// Once split, another string can be inserted in between the two halves by
32
/// inserting a RopePiece in between the two others.  All of this is very
33
/// inexpensive: it takes time proportional to the number of RopePieces, not the
34
/// length of the strings they represent.
35
///
36
/// While a linear sequences of RopePieces is the conceptual model, the actual
37
/// implementation captures them in an adapted B+ Tree.  Using a B+ tree (which
38
/// is a tree that keeps the values in the leaves and has where each node
39
/// contains a reasonable number of pointers to children/values) allows us to
40
/// maintain efficient operation when the RewriteRope contains a *huge* number
41
/// of RopePieces.  The basic idea of the B+ Tree is that it allows us to find
42
/// the RopePiece corresponding to some offset very efficiently, and it
43
/// automatically balances itself on insertions of RopePieces (which can happen
44
/// for both insertions and erases of string ranges).
45
///
46
/// The one wrinkle on the theory is that we don't attempt to keep the tree
47
/// properly balanced when erases happen.  Erases of string data can both insert
48
/// new RopePieces (e.g. when the middle of some other rope piece is deleted,
49
/// which results in two rope pieces, which is just like an insert) or it can
50
/// reduce the number of RopePieces maintained by the B+Tree.  In the case when
51
/// the number of RopePieces is reduced, we don't attempt to maintain the
52
/// standard 'invariant' that each node in the tree contains at least
53
/// 'WidthFactor' children/values.  For our use cases, this doesn't seem to
54
/// matter.
55
///
56
/// The implementation below is primarily implemented in terms of three classes:
57
///   RopePieceBTreeNode - Common base class for:
58
///
59
///     RopePieceBTreeLeaf - Directly manages up to '2*WidthFactor' RopePiece
60
///          nodes.  This directly represents a chunk of the string with those
61
///          RopePieces concatenated.
62
///     RopePieceBTreeInterior - An interior node in the B+ Tree, which manages
63
///          up to '2*WidthFactor' other nodes in the tree.
64
65
namespace {
66
67
//===----------------------------------------------------------------------===//
68
// RopePieceBTreeNode Class
69
//===----------------------------------------------------------------------===//
70
71
  /// RopePieceBTreeNode - Common base class of RopePieceBTreeLeaf and
72
  /// RopePieceBTreeInterior.  This provides some 'virtual' dispatching methods
73
  /// and a flag that determines which subclass the instance is.  Also
74
  /// important, this node knows the full extend of the node, including any
75
  /// children that it has.  This allows efficient skipping over entire subtrees
76
  /// when looking for an offset in the BTree.
77
  class RopePieceBTreeNode {
78
  protected:
79
    /// WidthFactor - This controls the number of K/V slots held in the BTree:
80
    /// how wide it is.  Each level of the BTree is guaranteed to have at least
81
    /// 'WidthFactor' elements in it (either ropepieces or children), (except
82
    /// the root, which may have less) and may have at most 2*WidthFactor
83
    /// elements.
84
    enum { WidthFactor = 8 };
85
86
    /// Size - This is the number of bytes of file this node (including any
87
    /// potential children) covers.
88
    unsigned Size = 0;
89
90
    /// IsLeaf - True if this is an instance of RopePieceBTreeLeaf, false if it
91
    /// is an instance of RopePieceBTreeInterior.
92
    bool IsLeaf;
93
94
57.7k
    RopePieceBTreeNode(bool isLeaf) : IsLeaf(isLeaf) {}
95
    ~RopePieceBTreeNode() = default;
96
97
  public:
98
829k
    bool isLeaf() const { return IsLeaf; }
99
5.45M
    unsigned size() const { return Size; }
100
101
    void Destroy();
102
103
    /// split - Split the range containing the specified offset so that we are
104
    /// guaranteed that there is a place to do an insertion at the specified
105
    /// offset.  The offset is relative, so "0" is the start of the node.
106
    ///
107
    /// If there is no space in this subtree for the extra piece, the extra tree
108
    /// node is returned and must be inserted into a parent.
109
    RopePieceBTreeNode *split(unsigned Offset);
110
111
    /// insert - Insert the specified ropepiece into this tree node at the
112
    /// specified offset.  The offset is relative, so "0" is the start of the
113
    /// node.
114
    ///
115
    /// If there is no space in this subtree for the extra piece, the extra tree
116
    /// node is returned and must be inserted into a parent.
117
    RopePieceBTreeNode *insert(unsigned Offset, const RopePiece &R);
118
119
    /// erase - Remove NumBytes from this node at the specified offset.  We are
120
    /// guaranteed that there is a split at Offset.
121
    void erase(unsigned Offset, unsigned NumBytes);
122
  };
123
124
//===----------------------------------------------------------------------===//
125
// RopePieceBTreeLeaf Class
126
//===----------------------------------------------------------------------===//
127
128
  /// RopePieceBTreeLeaf - Directly manages up to '2*WidthFactor' RopePiece
129
  /// nodes.  This directly represents a chunk of the string with those
130
  /// RopePieces concatenated.  Since this is a B+Tree, all values (in this case
131
  /// instances of RopePiece) are stored in leaves like this.  To make iteration
132
  /// over the leaves efficient, they maintain a singly linked list through the
133
  /// NextLeaf field.  This allows the B+Tree forward iterator to be constant
134
  /// time for all increments.
135
  class RopePieceBTreeLeaf : public RopePieceBTreeNode {
136
    /// NumPieces - This holds the number of rope pieces currently active in the
137
    /// Pieces array.
138
    unsigned char NumPieces = 0;
139
140
    /// Pieces - This tracks the file chunks currently in this leaf.
141
    RopePiece Pieces[2*WidthFactor];
142
143
    /// NextLeaf - This is a pointer to the next leaf in the tree, allowing
144
    /// efficient in-order forward iteration of the tree without traversal.
145
    RopePieceBTreeLeaf **PrevLeaf = nullptr;
146
    RopePieceBTreeLeaf *NextLeaf = nullptr;
147
148
  public:
149
55.3k
    RopePieceBTreeLeaf() : RopePieceBTreeNode(true) {}
150
151
55.3k
    ~RopePieceBTreeLeaf() {
152
55.3k
      if (PrevLeaf || 
NextLeaf55.3k
)
153
14.8k
        removeFromLeafInOrder();
154
55.3k
      clear();
155
55.3k
    }
156
157
254k
    bool isFull() const { return NumPieces == 2*WidthFactor; }
158
159
    /// clear - Remove all rope pieces from this leaf.
160
68.8k
    void clear() {
161
306k
      while (NumPieces)
162
237k
        Pieces[--NumPieces] = RopePiece();
163
68.8k
      Size = 0;
164
68.8k
    }
165
166
559k
    unsigned getNumPieces() const { return NumPieces; }
167
168
1.66M
    const RopePiece &getPiece(unsigned i) const {
169
1.66M
      assert(i < getNumPieces() && "Invalid piece ID");
170
1.66M
      return Pieces[i];
171
1.66M
    }
172
173
29.4k
    const RopePieceBTreeLeaf *getNextLeafInOrder() const { return NextLeaf; }
174
175
14.8k
    void insertAfterLeafInOrder(RopePieceBTreeLeaf *Node) {
176
14.8k
      assert(!PrevLeaf && !NextLeaf && "Already in ordering");
177
14.8k
178
14.8k
      NextLeaf = Node->NextLeaf;
179
14.8k
      if (NextLeaf)
180
11.8k
        NextLeaf->PrevLeaf = &NextLeaf;
181
14.8k
      PrevLeaf = &Node->NextLeaf;
182
14.8k
      Node->NextLeaf = this;
183
14.8k
    }
184
185
14.8k
    void removeFromLeafInOrder() {
186
14.8k
      if (PrevLeaf) {
187
1
        *PrevLeaf = NextLeaf;
188
1
        if (NextLeaf)
189
1
          NextLeaf->PrevLeaf = PrevLeaf;
190
14.8k
      } else if (NextLeaf) {
191
14.8k
        NextLeaf->PrevLeaf = nullptr;
192
14.8k
      }
193
14.8k
    }
194
195
    /// FullRecomputeSizeLocally - This method recomputes the 'Size' field by
196
    /// summing the size of all RopePieces.
197
29.7k
    void FullRecomputeSizeLocally() {
198
29.7k
      Size = 0;
199
267k
      for (unsigned i = 0, e = getNumPieces(); i != e; 
++i237k
)
200
237k
        Size += getPiece(i).size();
201
29.7k
    }
202
203
    /// split - Split the range containing the specified offset so that we are
204
    /// guaranteed that there is a place to do an insertion at the specified
205
    /// offset.  The offset is relative, so "0" is the start of the node.
206
    ///
207
    /// If there is no space in this subtree for the extra piece, the extra tree
208
    /// node is returned and must be inserted into a parent.
209
    RopePieceBTreeNode *split(unsigned Offset);
210
211
    /// insert - Insert the specified ropepiece into this tree node at the
212
    /// specified offset.  The offset is relative, so "0" is the start of the
213
    /// node.
214
    ///
215
    /// If there is no space in this subtree for the extra piece, the extra tree
216
    /// node is returned and must be inserted into a parent.
217
    RopePieceBTreeNode *insert(unsigned Offset, const RopePiece &R);
218
219
    /// erase - Remove NumBytes from this node at the specified offset.  We are
220
    /// guaranteed that there is a split at Offset.
221
    void erase(unsigned Offset, unsigned NumBytes);
222
223
813k
    static bool classof(const RopePieceBTreeNode *N) {
224
813k
      return N->isLeaf();
225
813k
    }
226
  };
227
228
} // namespace
229
230
/// split - Split the range containing the specified offset so that we are
231
/// guaranteed that there is a place to do an insertion at the specified
232
/// offset.  The offset is relative, so "0" is the start of the node.
233
///
234
/// If there is no space in this subtree for the extra piece, the extra tree
235
/// node is returned and must be inserted into a parent.
236
174k
RopePieceBTreeNode *RopePieceBTreeLeaf::split(unsigned Offset) {
237
174k
  // Find the insertion point.  We are guaranteed that there is a split at the
238
174k
  // specified offset so find it.
239
174k
  if (Offset == 0 || 
Offset == size()159k
) {
240
14.9k
    // Fastpath for a common case.  There is already a splitpoint at the end.
241
14.9k
    return nullptr;
242
14.9k
  }
243
159k
244
159k
  // Find the piece that this offset lands in.
245
159k
  unsigned PieceOffs = 0;
246
159k
  unsigned i = 0;
247
844k
  while (Offset >= PieceOffs+Pieces[i].size()) {
248
685k
    PieceOffs += Pieces[i].size();
249
685k
    ++i;
250
685k
  }
251
159k
252
159k
  // If there is already a split point at the specified offset, just return
253
159k
  // success.
254
159k
  if (PieceOffs == Offset)
255
53.1k
    return nullptr;
256
105k
257
105k
  // Otherwise, we need to split piece 'i' at Offset-PieceOffs.  Convert Offset
258
105k
  // to being Piece relative.
259
105k
  unsigned IntraPieceOffset = Offset-PieceOffs;
260
105k
261
105k
  // We do this by shrinking the RopePiece and then doing an insert of the tail.
262
105k
  RopePiece Tail(Pieces[i].StrData, Pieces[i].StartOffs+IntraPieceOffset,
263
105k
                 Pieces[i].EndOffs);
264
105k
  Size -= Pieces[i].size();
265
105k
  Pieces[i].EndOffs = Pieces[i].StartOffs+IntraPieceOffset;
266
105k
  Size += Pieces[i].size();
267
105k
268
105k
  return insert(Offset, Tail);
269
105k
}
270
271
/// insert - Insert the specified RopePiece into this tree node at the
272
/// specified offset.  The offset is relative, so "0" is the start of the node.
273
///
274
/// If there is no space in this subtree for the extra piece, the extra tree
275
/// node is returned and must be inserted into a parent.
276
RopePieceBTreeNode *RopePieceBTreeLeaf::insert(unsigned Offset,
277
254k
                                               const RopePiece &R) {
278
254k
  // If this node is not full, insert the piece.
279
254k
  if (!isFull()) {
280
239k
    // Find the insertion point.  We are guaranteed that there is a split at the
281
239k
    // specified offset so find it.
282
239k
    unsigned i = 0, e = getNumPieces();
283
239k
    if (Offset == size()) {
284
44.8k
      // Fastpath for a common case.
285
44.8k
      i = e;
286
194k
    } else {
287
194k
      unsigned SlotOffs = 0;
288
1.15M
      for (; Offset > SlotOffs; 
++i964k
)
289
964k
        SlotOffs += getPiece(i).size();
290
194k
      assert(SlotOffs == Offset && "Split didn't occur before insertion!");
291
194k
    }
292
239k
293
239k
    // For an insertion into a non-full leaf node, just insert the value in
294
239k
    // its sorted position.  This requires moving later values over.
295
1.11M
    for (; i != e; 
--e872k
)
296
872k
      Pieces[e] = Pieces[e-1];
297
239k
    Pieces[i] = R;
298
239k
    ++NumPieces;
299
239k
    Size += R.size();
300
239k
    return nullptr;
301
239k
  }
302
14.8k
303
14.8k
  // Otherwise, if this is leaf is full, split it in two halves.  Since this
304
14.8k
  // node is full, it contains 2*WidthFactor values.  We move the first
305
14.8k
  // 'WidthFactor' values to the LHS child (which we leave in this node) and
306
14.8k
  // move the last 'WidthFactor' values into the RHS child.
307
14.8k
308
14.8k
  // Create the new node.
309
14.8k
  RopePieceBTreeLeaf *NewNode = new RopePieceBTreeLeaf();
310
14.8k
311
14.8k
  // Move over the last 'WidthFactor' values from here to NewNode.
312
14.8k
  std::copy(&Pieces[WidthFactor], &Pieces[2*WidthFactor],
313
14.8k
            &NewNode->Pieces[0]);
314
14.8k
  // Replace old pieces with null RopePieces to drop refcounts.
315
14.8k
  std::fill(&Pieces[WidthFactor], &Pieces[2*WidthFactor], RopePiece());
316
14.8k
317
14.8k
  // Decrease the number of values in the two nodes.
318
14.8k
  NewNode->NumPieces = NumPieces = WidthFactor;
319
14.8k
320
14.8k
  // Recompute the two nodes' size.
321
14.8k
  NewNode->FullRecomputeSizeLocally();
322
14.8k
  FullRecomputeSizeLocally();
323
14.8k
324
14.8k
  // Update the list of leaves.
325
14.8k
  NewNode->insertAfterLeafInOrder(this);
326
14.8k
327
14.8k
  // These insertions can't fail.
328
14.8k
  if (this->size() >= Offset)
329
2.26k
    this->insert(Offset, R);
330
12.5k
  else
331
12.5k
    NewNode->insert(Offset - this->size(), R);
332
14.8k
  return NewNode;
333
14.8k
}
334
335
/// erase - Remove NumBytes from this node at the specified offset.  We are
336
/// guaranteed that there is a split at Offset.
337
43.0k
void RopePieceBTreeLeaf::erase(unsigned Offset, unsigned NumBytes) {
338
43.0k
  // Since we are guaranteed that there is a split at Offset, we start by
339
43.0k
  // finding the Piece that starts there.
340
43.0k
  unsigned PieceOffs = 0;
341
43.0k
  unsigned i = 0;
342
136k
  for (; Offset > PieceOffs; 
++i93.3k
)
343
93.3k
    PieceOffs += getPiece(i).size();
344
43.0k
  assert(PieceOffs == Offset && "Split didn't occur before erase!");
345
43.0k
346
43.0k
  unsigned StartPiece = i;
347
43.0k
348
43.0k
  // Figure out how many pieces completely cover 'NumBytes'.  We want to remove
349
43.0k
  // all of them.
350
43.6k
  for (; Offset+NumBytes > PieceOffs+getPiece(i).size(); 
++i564
)
351
564
    PieceOffs += getPiece(i).size();
352
43.0k
353
43.0k
  // If we exactly include the last one, include it in the region to delete.
354
43.0k
  if (Offset+NumBytes == PieceOffs+getPiece(i).size()) {
355
812
    PieceOffs += getPiece(i).size();
356
812
    ++i;
357
812
  }
358
43.0k
359
43.0k
  // If we completely cover some RopePieces, erase them now.
360
43.0k
  if (i != StartPiece) {
361
1.04k
    unsigned NumDeleted = i-StartPiece;
362
4.24k
    for (; i != getNumPieces(); 
++i3.19k
)
363
3.19k
      Pieces[i-NumDeleted] = Pieces[i];
364
1.04k
365
1.04k
    // Drop references to dead rope pieces.
366
1.04k
    std::fill(&Pieces[getNumPieces()-NumDeleted], &Pieces[getNumPieces()],
367
1.04k
              RopePiece());
368
1.04k
    NumPieces -= NumDeleted;
369
1.04k
370
1.04k
    unsigned CoverBytes = PieceOffs-Offset;
371
1.04k
    NumBytes -= CoverBytes;
372
1.04k
    Size -= CoverBytes;
373
1.04k
  }
374
43.0k
375
43.0k
  // If we completely removed some stuff, we could be done.
376
43.0k
  if (NumBytes == 0) 
return812
;
377
42.2k
378
42.2k
  // Okay, now might be erasing part of some Piece.  If this is the case, then
379
42.2k
  // move the start point of the piece.
380
42.2k
  assert(getPiece(StartPiece).size() > NumBytes);
381
42.2k
  Pieces[StartPiece].StartOffs += NumBytes;
382
42.2k
383
42.2k
  // The size of this node just shrunk by NumBytes.
384
42.2k
  Size -= NumBytes;
385
42.2k
}
386
387
//===----------------------------------------------------------------------===//
388
// RopePieceBTreeInterior Class
389
//===----------------------------------------------------------------------===//
390
391
namespace {
392
393
  /// RopePieceBTreeInterior - This represents an interior node in the B+Tree,
394
  /// which holds up to 2*WidthFactor pointers to child nodes.
395
  class RopePieceBTreeInterior : public RopePieceBTreeNode {
396
    /// NumChildren - This holds the number of children currently active in the
397
    /// Children array.
398
    unsigned char NumChildren = 0;
399
400
    RopePieceBTreeNode *Children[2*WidthFactor];
401
402
  public:
403
1.25k
    RopePieceBTreeInterior() : RopePieceBTreeNode(false) {}
404
405
    RopePieceBTreeInterior(RopePieceBTreeNode *LHS, RopePieceBTreeNode *RHS)
406
1.14k
        : RopePieceBTreeNode(false) {
407
1.14k
      Children[0] = LHS;
408
1.14k
      Children[1] = RHS;
409
1.14k
      NumChildren = 2;
410
1.14k
      Size = LHS->size() + RHS->size();
411
1.14k
    }
412
413
2.40k
    ~RopePieceBTreeInterior() {
414
19.6k
      for (unsigned i = 0, e = getNumChildren(); i != e; 
++i17.2k
)
415
17.2k
        Children[i]->Destroy();
416
2.40k
    }
417
418
16.2k
    bool isFull() const { return NumChildren == 2*WidthFactor; }
419
420
217k
    unsigned getNumChildren() const { return NumChildren; }
421
422
1.72k
    const RopePieceBTreeNode *getChild(unsigned i) const {
423
1.72k
      assert(i < NumChildren && "invalid child #");
424
1.72k
      return Children[i];
425
1.72k
    }
426
427
5.02M
    RopePieceBTreeNode *getChild(unsigned i) {
428
5.02M
      assert(i < NumChildren && "invalid child #");
429
5.02M
      return Children[i];
430
5.02M
    }
431
432
    /// FullRecomputeSizeLocally - Recompute the Size field of this node by
433
    /// summing up the sizes of the child nodes.
434
2.50k
    void FullRecomputeSizeLocally() {
435
2.50k
      Size = 0;
436
23.8k
      for (unsigned i = 0, e = getNumChildren(); i != e; 
++i21.3k
)
437
21.3k
        Size += getChild(i)->size();
438
2.50k
    }
439
440
    /// split - Split the range containing the specified offset so that we are
441
    /// guaranteed that there is a place to do an insertion at the specified
442
    /// offset.  The offset is relative, so "0" is the start of the node.
443
    ///
444
    /// If there is no space in this subtree for the extra piece, the extra tree
445
    /// node is returned and must be inserted into a parent.
446
    RopePieceBTreeNode *split(unsigned Offset);
447
448
    /// insert - Insert the specified ropepiece into this tree node at the
449
    /// specified offset.  The offset is relative, so "0" is the start of the
450
    /// node.
451
    ///
452
    /// If there is no space in this subtree for the extra piece, the extra tree
453
    /// node is returned and must be inserted into a parent.
454
    RopePieceBTreeNode *insert(unsigned Offset, const RopePiece &R);
455
456
    /// HandleChildPiece - A child propagated an insertion result up to us.
457
    /// Insert the new child, and/or propagate the result further up the tree.
458
    RopePieceBTreeNode *HandleChildPiece(unsigned i, RopePieceBTreeNode *RHS);
459
460
    /// erase - Remove NumBytes from this node at the specified offset.  We are
461
    /// guaranteed that there is a split at Offset.
462
    void erase(unsigned Offset, unsigned NumBytes);
463
464
15.9k
    static bool classof(const RopePieceBTreeNode *N) {
465
15.9k
      return !N->isLeaf();
466
15.9k
    }
467
  };
468
469
} // namespace
470
471
/// split - Split the range containing the specified offset so that we are
472
/// guaranteed that there is a place to do an insertion at the specified
473
/// offset.  The offset is relative, so "0" is the start of the node.
474
///
475
/// If there is no space in this subtree for the extra piece, the extra tree
476
/// node is returned and must be inserted into a parent.
477
195k
RopePieceBTreeNode *RopePieceBTreeInterior::split(unsigned Offset) {
478
195k
  // Figure out which child to split.
479
195k
  if (Offset == 0 || 
Offset == size()194k
)
480
990
    return nullptr; // If we have an exact offset, we're already split.
481
194k
482
194k
  unsigned ChildOffset = 0;
483
194k
  unsigned i = 0;
484
1.25M
  for (; Offset >= ChildOffset+getChild(i)->size(); 
++i1.05M
)
485
1.05M
    ChildOffset += getChild(i)->size();
486
194k
487
194k
  // If already split there, we're done.
488
194k
  if (ChildOffset == Offset)
489
1.34k
    return nullptr;
490
192k
491
192k
  // Otherwise, recursively split the child.
492
192k
  if (RopePieceBTreeNode *RHS = getChild(i)->split(Offset-ChildOffset))
493
10.1k
    return HandleChildPiece(i, RHS);
494
182k
  return nullptr; // Done!
495
182k
}
496
497
/// insert - Insert the specified ropepiece into this tree node at the
498
/// specified offset.  The offset is relative, so "0" is the start of the
499
/// node.
500
///
501
/// If there is no space in this subtree for the extra piece, the extra tree
502
/// node is returned and must be inserted into a parent.
503
RopePieceBTreeNode *RopePieceBTreeInterior::insert(unsigned Offset,
504
186k
                                                   const RopePiece &R) {
505
186k
  // Find the insertion point.  We are guaranteed that there is a split at the
506
186k
  // specified offset so find it.
507
186k
  unsigned i = 0, e = getNumChildren();
508
186k
509
186k
  unsigned ChildOffs = 0;
510
186k
  if (Offset == size()) {
511
466
    // Fastpath for a common case.  Insert at end of last child.
512
466
    i = e-1;
513
466
    ChildOffs = size()-getChild(i)->size();
514
186k
  } else {
515
1.20M
    for (; Offset > ChildOffs+getChild(i)->size(); 
++i1.02M
)
516
1.02M
      ChildOffs += getChild(i)->size();
517
186k
  }
518
186k
519
186k
  Size += R.size();
520
186k
521
186k
  // Insert at the end of this child.
522
186k
  if (RopePieceBTreeNode *RHS = getChild(i)->insert(Offset-ChildOffs, R))
523
4.83k
    return HandleChildPiece(i, RHS);
524
181k
525
181k
  return nullptr;
526
181k
}
527
528
/// HandleChildPiece - A child propagated an insertion result up to us.
529
/// Insert the new child, and/or propagate the result further up the tree.
530
RopePieceBTreeNode *
531
16.2k
RopePieceBTreeInterior::HandleChildPiece(unsigned i, RopePieceBTreeNode *RHS) {
532
16.2k
  // Otherwise the child propagated a subtree up to us as a new child.  See if
533
16.2k
  // we have space for it here.
534
16.2k
  if (!isFull()) {
535
14.9k
    // Insert RHS after child 'i'.
536
14.9k
    if (i + 1 != getNumChildren())
537
11.4k
      memmove(&Children[i+2], &Children[i+1],
538
11.4k
              (getNumChildren()-i-1)*sizeof(Children[0]));
539
14.9k
    Children[i+1] = RHS;
540
14.9k
    ++NumChildren;
541
14.9k
    return nullptr;
542
14.9k
  }
543
1.25k
544
1.25k
  // Okay, this node is full.  Split it in half, moving WidthFactor children to
545
1.25k
  // a newly allocated interior node.
546
1.25k
547
1.25k
  // Create the new node.
548
1.25k
  RopePieceBTreeInterior *NewNode = new RopePieceBTreeInterior();
549
1.25k
550
1.25k
  // Move over the last 'WidthFactor' values from here to NewNode.
551
1.25k
  memcpy(&NewNode->Children[0], &Children[WidthFactor],
552
1.25k
         WidthFactor*sizeof(Children[0]));
553
1.25k
554
1.25k
  // Decrease the number of values in the two nodes.
555
1.25k
  NewNode->NumChildren = NumChildren = WidthFactor;
556
1.25k
557
1.25k
  // Finally, insert the two new children in the side the can (now) hold them.
558
1.25k
  // These insertions can't fail.
559
1.25k
  if (i < WidthFactor)
560
31
    this->HandleChildPiece(i, RHS);
561
1.22k
  else
562
1.22k
    NewNode->HandleChildPiece(i-WidthFactor, RHS);
563
1.25k
564
1.25k
  // Recompute the two nodes' size.
565
1.25k
  NewNode->FullRecomputeSizeLocally();
566
1.25k
  FullRecomputeSizeLocally();
567
1.25k
  return NewNode;
568
1.25k
}
569
570
/// erase - Remove NumBytes from this node at the specified offset.  We are
571
/// guaranteed that there is a split at Offset.
572
9.95k
void RopePieceBTreeInterior::erase(unsigned Offset, unsigned NumBytes) {
573
9.95k
  // This will shrink this node by NumBytes.
574
9.95k
  Size -= NumBytes;
575
9.95k
576
9.95k
  // Find the first child that overlaps with Offset.
577
9.95k
  unsigned i = 0;
578
46.1k
  for (; Offset >= getChild(i)->size(); 
++i36.2k
)
579
36.2k
    Offset -= getChild(i)->size();
580
9.95k
581
9.95k
  // Propagate the delete request into overlapping children, or completely
582
9.95k
  // delete the children as appropriate.
583
9.96k
  while (NumBytes) {
584
9.96k
    RopePieceBTreeNode *CurChild = getChild(i);
585
9.96k
586
9.96k
    // If we are deleting something contained entirely in the child, pass on the
587
9.96k
    // request.
588
9.96k
    if (Offset+NumBytes < CurChild->size()) {
589
9.95k
      CurChild->erase(Offset, NumBytes);
590
9.95k
      return;
591
9.95k
    }
592
9
593
9
    // If this deletion request starts somewhere in the middle of the child, it
594
9
    // must be deleting to the end of the child.
595
9
    if (Offset) {
596
8
      unsigned BytesFromChild = CurChild->size()-Offset;
597
8
      CurChild->erase(Offset, BytesFromChild);
598
8
      NumBytes -= BytesFromChild;
599
8
      // Start at the beginning of the next child.
600
8
      Offset = 0;
601
8
      ++i;
602
8
      continue;
603
8
    }
604
1
605
1
    // If the deletion request completely covers the child, delete it and move
606
1
    // the rest down.
607
1
    NumBytes -= CurChild->size();
608
1
    CurChild->Destroy();
609
1
    --NumChildren;
610
1
    if (i != getNumChildren())
611
1
      memmove(&Children[i], &Children[i+1],
612
1
              (getNumChildren()-i)*sizeof(Children[0]));
613
1
  }
614
9.95k
}
615
616
//===----------------------------------------------------------------------===//
617
// RopePieceBTreeNode Implementation
618
//===----------------------------------------------------------------------===//
619
620
57.7k
void RopePieceBTreeNode::Destroy() {
621
57.7k
  if (auto *Leaf = dyn_cast<RopePieceBTreeLeaf>(this))
622
55.3k
    delete Leaf;
623
2.40k
  else
624
2.40k
    delete cast<RopePieceBTreeInterior>(this);
625
57.7k
}
626
627
/// split - Split the range containing the specified offset so that we are
628
/// guaranteed that there is a place to do an insertion at the specified
629
/// offset.  The offset is relative, so "0" is the start of the node.
630
///
631
/// If there is no space in this subtree for the extra piece, the extra tree
632
/// node is returned and must be inserted into a parent.
633
369k
RopePieceBTreeNode *RopePieceBTreeNode::split(unsigned Offset) {
634
369k
  assert(Offset <= size() && "Invalid offset to split!");
635
369k
  if (auto *Leaf = dyn_cast<RopePieceBTreeLeaf>(this))
636
174k
    return Leaf->split(Offset);
637
195k
  return cast<RopePieceBTreeInterior>(this)->split(Offset);
638
195k
}
639
640
/// insert - Insert the specified ropepiece into this tree node at the
641
/// specified offset.  The offset is relative, so "0" is the start of the
642
/// node.
643
///
644
/// If there is no space in this subtree for the extra piece, the extra tree
645
/// node is returned and must be inserted into a parent.
646
RopePieceBTreeNode *RopePieceBTreeNode::insert(unsigned Offset,
647
319k
                                               const RopePiece &R) {
648
319k
  assert(Offset <= size() && "Invalid offset to insert!");
649
319k
  if (auto *Leaf = dyn_cast<RopePieceBTreeLeaf>(this))
650
133k
    return Leaf->insert(Offset, R);
651
186k
  return cast<RopePieceBTreeInterior>(this)->insert(Offset, R);
652
186k
}
653
654
/// erase - Remove NumBytes from this node at the specified offset.  We are
655
/// guaranteed that there is a split at Offset.
656
53.0k
void RopePieceBTreeNode::erase(unsigned Offset, unsigned NumBytes) {
657
53.0k
  assert(Offset+NumBytes <= size() && "Invalid offset to erase!");
658
53.0k
  if (auto *Leaf = dyn_cast<RopePieceBTreeLeaf>(this))
659
43.0k
    return Leaf->erase(Offset, NumBytes);
660
9.95k
  return cast<RopePieceBTreeInterior>(this)->erase(Offset, NumBytes);
661
9.95k
}
662
663
//===----------------------------------------------------------------------===//
664
// RopePieceBTreeIterator Implementation
665
//===----------------------------------------------------------------------===//
666
667
598k
static const RopePieceBTreeLeaf *getCN(const void *P) {
668
598k
  return static_cast<const RopePieceBTreeLeaf*>(P);
669
598k
}
670
671
// begin iterator.
672
14.2k
RopePieceBTreeIterator::RopePieceBTreeIterator(const void *n) {
673
14.2k
  const auto *N = static_cast<const RopePieceBTreeNode *>(n);
674
14.2k
675
14.2k
  // Walk down the left side of the tree until we get to a leaf.
676
15.9k
  while (const auto *IN = dyn_cast<RopePieceBTreeInterior>(N))
677
1.72k
    N = IN->getChild(0);
678
14.2k
679
14.2k
  // We must have at least one leaf.
680
14.2k
  CurNode = cast<RopePieceBTreeLeaf>(N);
681
14.2k
682
14.2k
  // If we found a leaf that happens to be empty, skip over it until we get
683
14.2k
  // to something full.
684
14.2k
  while (CurNode && 
getCN(CurNode)->getNumPieces() == 014.2k
)
685
7
    CurNode = getCN(CurNode)->getNextLeafInOrder();
686
14.2k
687
14.2k
  if (CurNode)
688
14.2k
    CurPiece = &getCN(CurNode)->getPiece(0);
689
7
  else  // Empty tree, this is an end() iterator.
690
7
    CurPiece = nullptr;
691
14.2k
  CurChar = 0;
692
14.2k
}
693
694
254k
void RopePieceBTreeIterator::MoveToNextPiece() {
695
254k
  if (CurPiece != &getCN(CurNode)->getPiece(getCN(CurNode)->getNumPieces()-1)) {
696
224k
    CurChar = 0;
697
224k
    ++CurPiece;
698
224k
    return;
699
224k
  }
700
29.4k
701
29.4k
  // Find the next non-empty leaf node.
702
29.4k
  do
703
29.4k
    CurNode = getCN(CurNode)->getNextLeafInOrder();
704
29.4k
  while (CurNode && 
getCN(CurNode)->getNumPieces() == 016.0k
);
705
29.4k
706
29.4k
  if (CurNode)
707
16.0k
    CurPiece = &getCN(CurNode)->getPiece(0);
708
13.4k
  else // Hit end().
709
13.4k
    CurPiece = nullptr;
710
29.4k
  CurChar = 0;
711
29.4k
}
712
713
//===----------------------------------------------------------------------===//
714
// RopePieceBTree Implementation
715
//===----------------------------------------------------------------------===//
716
717
407k
static RopePieceBTreeNode *getRoot(void *P) {
718
407k
  return static_cast<RopePieceBTreeNode*>(P);
719
407k
}
720
721
13.5k
RopePieceBTree::RopePieceBTree() {
722
13.5k
  Root = new RopePieceBTreeLeaf();
723
13.5k
}
724
725
27.0k
RopePieceBTree::RopePieceBTree(const RopePieceBTree &RHS) {
726
27.0k
  assert(RHS.empty() && "Can't copy non-empty tree yet");
727
27.0k
  Root = new RopePieceBTreeLeaf();
728
27.0k
}
729
730
40.5k
RopePieceBTree::~RopePieceBTree() {
731
40.5k
  getRoot(Root)->Destroy();
732
40.5k
}
733
734
6
unsigned RopePieceBTree::size() const {
735
6
  return getRoot(Root)->size();
736
6
}
737
738
13.5k
void RopePieceBTree::clear() {
739
13.5k
  if (auto *Leaf = dyn_cast<RopePieceBTreeLeaf>(getRoot(Root)))
740
13.5k
    Leaf->clear();
741
0
  else {
742
0
    getRoot(Root)->Destroy();
743
0
    Root = new RopePieceBTreeLeaf();
744
0
  }
745
13.5k
}
746
747
133k
void RopePieceBTree::insert(unsigned Offset, const RopePiece &R) {
748
133k
  // #1. Split at Offset.
749
133k
  if (RopePieceBTreeNode *RHS = getRoot(Root)->split(Offset))
750
87
    Root = new RopePieceBTreeInterior(getRoot(Root), RHS);
751
133k
752
133k
  // #2. Do the insertion.
753
133k
  if (RopePieceBTreeNode *RHS = getRoot(Root)->insert(Offset, R))
754
894
    Root = new RopePieceBTreeInterior(getRoot(Root), RHS);
755
133k
}
756
757
43.0k
void RopePieceBTree::erase(unsigned Offset, unsigned NumBytes) {
758
43.0k
  // #1. Split at Offset.
759
43.0k
  if (RopePieceBTreeNode *RHS = getRoot(Root)->split(Offset))
760
166
    Root = new RopePieceBTreeInterior(getRoot(Root), RHS);
761
43.0k
762
43.0k
  // #2. Do the erasing.
763
43.0k
  getRoot(Root)->erase(Offset, NumBytes);
764
43.0k
}
765
766
//===----------------------------------------------------------------------===//
767
// RewriteRope Implementation
768
//===----------------------------------------------------------------------===//
769
770
/// MakeRopeString - This copies the specified byte range into some instance of
771
/// RopeRefCountString, and return a RopePiece that represents it.  This uses
772
/// the AllocBuffer object to aggregate requests for small strings into one
773
/// allocation instead of doing tons of tiny allocations.
774
133k
RopePiece RewriteRope::MakeRopeString(const char *Start, const char *End) {
775
133k
  unsigned Len = End-Start;
776
133k
  assert(Len && "Zero length RopePiece is invalid!");
777
133k
778
133k
  // If we have space for this string in the current alloc buffer, use it.
779
133k
  if (AllocOffs+Len <= AllocChunkSize) {
780
118k
    memcpy(AllocBuffer->Data+AllocOffs, Start, Len);
781
118k
    AllocOffs += Len;
782
118k
    return RopePiece(AllocBuffer, AllocOffs-Len, AllocOffs);
783
118k
  }
784
14.7k
785
14.7k
  // If we don't have enough room because this specific allocation is huge,
786
14.7k
  // just allocate a new rope piece for it alone.
787
14.7k
  if (Len > AllocChunkSize) {
788
323
    unsigned Size = End-Start+sizeof(RopeRefCountString)-1;
789
323
    auto *Res = reinterpret_cast<RopeRefCountString *>(new char[Size]);
790
323
    Res->RefCount = 0;
791
323
    memcpy(Res->Data, Start, End-Start);
792
323
    return RopePiece(Res, 0, End-Start);
793
323
  }
794
14.3k
795
14.3k
  // Otherwise, this was a small request but we just don't have space for it
796
14.3k
  // Make a new chunk and share it with later allocations.
797
14.3k
798
14.3k
  unsigned AllocSize = offsetof(RopeRefCountString, Data) + AllocChunkSize;
799
14.3k
  auto *Res = reinterpret_cast<RopeRefCountString *>(new char[AllocSize]);
800
14.3k
  Res->RefCount = 0;
801
14.3k
  memcpy(Res->Data, Start, Len);
802
14.3k
  AllocBuffer = Res;
803
14.3k
  AllocOffs = Len;
804
14.3k
805
14.3k
  return RopePiece(AllocBuffer, 0, Len);
806
14.3k
}