Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/Transforms/Scalar/SROA.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
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
/// \file
9
/// This transformation implements the well known scalar replacement of
10
/// aggregates transformation. It tries to identify promotable elements of an
11
/// aggregate alloca, and promote them to registers. It will also try to
12
/// convert uses of an element (or set of elements) of an alloca into a vector
13
/// or bitfield-style integer scalar if appropriate.
14
///
15
/// It works to do this with minimal slicing of the alloca so that regions
16
/// which are merely transferred in and out of external memory remain unchanged
17
/// and are not decomposed to scalar code.
18
///
19
/// Because this also performs alloca promotion, it can be thought of as also
20
/// serving the purpose of SSA formation. The algorithm iterates on the
21
/// function until all opportunities for promotion have been realized.
22
///
23
//===----------------------------------------------------------------------===//
24
25
#include "llvm/Transforms/Scalar/SROA.h"
26
#include "llvm/ADT/APInt.h"
27
#include "llvm/ADT/ArrayRef.h"
28
#include "llvm/ADT/DenseMap.h"
29
#include "llvm/ADT/PointerIntPair.h"
30
#include "llvm/ADT/STLExtras.h"
31
#include "llvm/ADT/SetVector.h"
32
#include "llvm/ADT/SmallBitVector.h"
33
#include "llvm/ADT/SmallPtrSet.h"
34
#include "llvm/ADT/SmallVector.h"
35
#include "llvm/ADT/Statistic.h"
36
#include "llvm/ADT/StringRef.h"
37
#include "llvm/ADT/Twine.h"
38
#include "llvm/ADT/iterator.h"
39
#include "llvm/ADT/iterator_range.h"
40
#include "llvm/Analysis/AssumptionCache.h"
41
#include "llvm/Analysis/GlobalsModRef.h"
42
#include "llvm/Analysis/Loads.h"
43
#include "llvm/Analysis/PtrUseVisitor.h"
44
#include "llvm/Transforms/Utils/Local.h"
45
#include "llvm/Config/llvm-config.h"
46
#include "llvm/IR/BasicBlock.h"
47
#include "llvm/IR/Constant.h"
48
#include "llvm/IR/ConstantFolder.h"
49
#include "llvm/IR/Constants.h"
50
#include "llvm/IR/DIBuilder.h"
51
#include "llvm/IR/DataLayout.h"
52
#include "llvm/IR/DebugInfoMetadata.h"
53
#include "llvm/IR/DerivedTypes.h"
54
#include "llvm/IR/Dominators.h"
55
#include "llvm/IR/Function.h"
56
#include "llvm/IR/GetElementPtrTypeIterator.h"
57
#include "llvm/IR/GlobalAlias.h"
58
#include "llvm/IR/IRBuilder.h"
59
#include "llvm/IR/InstVisitor.h"
60
#include "llvm/IR/InstrTypes.h"
61
#include "llvm/IR/Instruction.h"
62
#include "llvm/IR/Instructions.h"
63
#include "llvm/IR/IntrinsicInst.h"
64
#include "llvm/IR/Intrinsics.h"
65
#include "llvm/IR/LLVMContext.h"
66
#include "llvm/IR/Metadata.h"
67
#include "llvm/IR/Module.h"
68
#include "llvm/IR/Operator.h"
69
#include "llvm/IR/PassManager.h"
70
#include "llvm/IR/Type.h"
71
#include "llvm/IR/Use.h"
72
#include "llvm/IR/User.h"
73
#include "llvm/IR/Value.h"
74
#include "llvm/Pass.h"
75
#include "llvm/Support/Casting.h"
76
#include "llvm/Support/CommandLine.h"
77
#include "llvm/Support/Compiler.h"
78
#include "llvm/Support/Debug.h"
79
#include "llvm/Support/ErrorHandling.h"
80
#include "llvm/Support/MathExtras.h"
81
#include "llvm/Support/raw_ostream.h"
82
#include "llvm/Transforms/Scalar.h"
83
#include "llvm/Transforms/Utils/PromoteMemToReg.h"
84
#include <algorithm>
85
#include <cassert>
86
#include <chrono>
87
#include <cstddef>
88
#include <cstdint>
89
#include <cstring>
90
#include <iterator>
91
#include <string>
92
#include <tuple>
93
#include <utility>
94
#include <vector>
95
96
#ifndef NDEBUG
97
// We only use this for a debug check.
98
#include <random>
99
#endif
100
101
using namespace llvm;
102
using namespace llvm::sroa;
103
104
#define DEBUG_TYPE "sroa"
105
106
STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
107
STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
108
STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
109
STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
110
STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
111
STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
112
STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
113
STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
114
STATISTIC(NumDeleted, "Number of instructions deleted");
115
STATISTIC(NumVectorized, "Number of vectorized aggregates");
116
117
/// Hidden option to enable randomly shuffling the slices to help uncover
118
/// instability in their order.
119
static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
120
                                             cl::init(false), cl::Hidden);
121
122
/// Hidden option to experiment with completely strict handling of inbounds
123
/// GEPs.
124
static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
125
                                        cl::Hidden);
126
127
namespace {
128
129
/// A custom IRBuilder inserter which prefixes all names, but only in
130
/// Assert builds.
131
class IRBuilderPrefixedInserter : public IRBuilderDefaultInserter {
132
  std::string Prefix;
133
134
4.11M
  const Twine getNameWithPrefix(const Twine &Name) const {
135
4.11M
    return Name.isTriviallyEmpty() ? 
Name1.31M
:
Prefix + Name2.80M
;
136
4.11M
  }
137
138
public:
139
3.91M
  void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
140
141
protected:
142
  void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
143
4.11M
                    BasicBlock::iterator InsertPt) const {
144
4.11M
    IRBuilderDefaultInserter::InsertHelper(I, getNameWithPrefix(Name), BB,
145
4.11M
                                           InsertPt);
146
4.11M
  }
147
};
148
149
/// Provide a type for IRBuilder that drops names in release builds.
150
using IRBuilderTy = IRBuilder<ConstantFolder, IRBuilderPrefixedInserter>;
151
152
/// A used slice of an alloca.
153
///
154
/// This structure represents a slice of an alloca used by some instruction. It
155
/// stores both the begin and end offsets of this use, a pointer to the use
156
/// itself, and a flag indicating whether we can classify the use as splittable
157
/// or not when forming partitions of the alloca.
158
class Slice {
159
  /// The beginning offset of the range.
160
  uint64_t BeginOffset = 0;
161
162
  /// The ending offset, not included in the range.
163
  uint64_t EndOffset = 0;
164
165
  /// Storage for both the use of this slice and whether it can be
166
  /// split.
167
  PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
168
169
public:
170
  Slice() = default;
171
172
  Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
173
      : BeginOffset(BeginOffset), EndOffset(EndOffset),
174
4.27M
        UseAndIsSplittable(U, IsSplittable) {}
175
176
51.0M
  uint64_t beginOffset() const { return BeginOffset; }
177
61.2M
  uint64_t endOffset() const { return EndOffset; }
178
179
34.8M
  bool isSplittable() const { return UseAndIsSplittable.getInt(); }
180
74.6k
  void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
181
182
19.8M
  Use *getUse() const { return UseAndIsSplittable.getPointer(); }
183
184
3.79M
  bool isDead() const { return getUse() == nullptr; }
185
28
  void kill() { UseAndIsSplittable.setPointer(nullptr); }
186
187
  /// Support for ordering ranges.
188
  ///
189
  /// This provides an ordering over ranges such that start offsets are
190
  /// always increasing, and within equal start offsets, the end offsets are
191
  /// decreasing. Thus the spanning range comes first in a cluster with the
192
  /// same start position.
193
4.23M
  bool operator<(const Slice &RHS) const {
194
4.23M
    if (beginOffset() < RHS.beginOffset())
195
324k
      return true;
196
3.91M
    if (beginOffset() > RHS.beginOffset())
197
153k
      return false;
198
3.75M
    if (isSplittable() != RHS.isSplittable())
199
668k
      return !isSplittable();
200
3.08M
    if (endOffset() > RHS.endOffset())
201
13.5k
      return true;
202
3.07M
    return false;
203
3.07M
  }
204
205
  /// Support comparison with a single offset to allow binary searches.
206
  friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
207
0
                                              uint64_t RHSOffset) {
208
0
    return LHS.beginOffset() < RHSOffset;
209
0
  }
210
  friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
211
0
                                              const Slice &RHS) {
212
0
    return LHSOffset < RHS.beginOffset();
213
0
  }
214
215
0
  bool operator==(const Slice &RHS) const {
216
0
    return isSplittable() == RHS.isSplittable() &&
217
0
           beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
218
0
  }
219
0
  bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
220
};
221
222
} // end anonymous namespace
223
224
/// Representation of the alloca slices.
225
///
226
/// This class represents the slices of an alloca which are formed by its
227
/// various uses. If a pointer escapes, we can't fully build a representation
228
/// for the slices used and we reflect that in this structure. The uses are
229
/// stored, sorted by increasing beginning offset and with unsplittable slices
230
/// starting at a particular offset before splittable slices.
231
class llvm::sroa::AllocaSlices {
232
public:
233
  /// Construct the slices of a particular alloca.
234
  AllocaSlices(const DataLayout &DL, AllocaInst &AI);
235
236
  /// Test whether a pointer to the allocation escapes our analysis.
237
  ///
238
  /// If this is true, the slices are never fully built and should be
239
  /// ignored.
240
1.08M
  bool isEscaped() const { return PointerEscapingInstr; }
241
242
  /// Support for iterating over the slices.
243
  /// @{
244
  using iterator = SmallVectorImpl<Slice>::iterator;
245
  using range = iterator_range<iterator>;
246
247
5.40M
  iterator begin() { return Slices.begin(); }
248
8.80M
  iterator end() { return Slices.end(); }
249
250
  using const_iterator = SmallVectorImpl<Slice>::const_iterator;
251
  using const_range = iterator_range<const_iterator>;
252
253
0
  const_iterator begin() const { return Slices.begin(); }
254
0
  const_iterator end() const { return Slices.end(); }
255
  /// @}
256
257
  /// Erase a range of slices.
258
16
  void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
259
260
  /// Insert new slices for this alloca.
261
  ///
262
  /// This moves the slices into the alloca's slices collection, and re-sorts
263
  /// everything so that the usual ordering properties of the alloca's slices
264
  /// hold.
265
16
  void insert(ArrayRef<Slice> NewSlices) {
266
16
    int OldSize = Slices.size();
267
16
    Slices.append(NewSlices.begin(), NewSlices.end());
268
16
    auto SliceI = Slices.begin() + OldSize;
269
16
    llvm::sort(SliceI, Slices.end());
270
16
    std::inplace_merge(Slices.begin(), SliceI, Slices.end());
271
16
  }
272
273
  // Forward declare the iterator and range accessor for walking the
274
  // partitions.
275
  class partition_iterator;
276
  iterator_range<partition_iterator> partitions();
277
278
  /// Access the dead users for this alloca.
279
879k
  ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
280
281
  /// Access the dead operands referring to this alloca.
282
  ///
283
  /// These are operands which have cannot actually be used to refer to the
284
  /// alloca as they are outside its range and the user doesn't correct for
285
  /// that. These mostly consist of PHI node inputs and the like which we just
286
  /// need to replace with undef.
287
879k
  ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
288
289
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
290
  void print(raw_ostream &OS, const_iterator I, StringRef Indent = "  ") const;
291
  void printSlice(raw_ostream &OS, const_iterator I,
292
                  StringRef Indent = "  ") const;
293
  void printUse(raw_ostream &OS, const_iterator I,
294
                StringRef Indent = "  ") const;
295
  void print(raw_ostream &OS) const;
296
  void dump(const_iterator I) const;
297
  void dump() const;
298
#endif
299
300
private:
301
  template <typename DerivedT, typename RetT = void> class BuilderBase;
302
  class SliceBuilder;
303
304
  friend class AllocaSlices::SliceBuilder;
305
306
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
307
  /// Handle to alloca instruction to simplify method interfaces.
308
  AllocaInst &AI;
309
#endif
310
311
  /// The instruction responsible for this alloca not having a known set
312
  /// of slices.
313
  ///
314
  /// When an instruction (potentially) escapes the pointer to the alloca, we
315
  /// store a pointer to that here and abort trying to form slices of the
316
  /// alloca. This will be null if the alloca slices are analyzed successfully.
317
  Instruction *PointerEscapingInstr;
318
319
  /// The slices of the alloca.
320
  ///
321
  /// We store a vector of the slices formed by uses of the alloca here. This
322
  /// vector is sorted by increasing begin offset, and then the unsplittable
323
  /// slices before the splittable ones. See the Slice inner class for more
324
  /// details.
325
  SmallVector<Slice, 8> Slices;
326
327
  /// Instructions which will become dead if we rewrite the alloca.
328
  ///
329
  /// Note that these are not separated by slice. This is because we expect an
330
  /// alloca to be completely rewritten or not rewritten at all. If rewritten,
331
  /// all these instructions can simply be removed and replaced with undef as
332
  /// they come from outside of the allocated space.
333
  SmallVector<Instruction *, 8> DeadUsers;
334
335
  /// Operands which will become dead if we rewrite the alloca.
336
  ///
337
  /// These are operands that in their particular use can be replaced with
338
  /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
339
  /// to PHI nodes and the like. They aren't entirely dead (there might be
340
  /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
341
  /// want to swap this particular input for undef to simplify the use lists of
342
  /// the alloca.
343
  SmallVector<Use *, 8> DeadOperands;
344
};
345
346
/// A partition of the slices.
347
///
348
/// An ephemeral representation for a range of slices which can be viewed as
349
/// a partition of the alloca. This range represents a span of the alloca's
350
/// memory which cannot be split, and provides access to all of the slices
351
/// overlapping some part of the partition.
352
///
353
/// Objects of this type are produced by traversing the alloca's slices, but
354
/// are only ephemeral and not persistent.
355
class llvm::sroa::Partition {
356
private:
357
  friend class AllocaSlices;
358
  friend class AllocaSlices::partition_iterator;
359
360
  using iterator = AllocaSlices::iterator;
361
362
  /// The beginning and ending offsets of the alloca for this
363
  /// partition.
364
  uint64_t BeginOffset, EndOffset;
365
366
  /// The start and end iterators of this partition.
367
  iterator SI, SJ;
368
369
  /// A collection of split slice tails overlapping the partition.
370
  SmallVector<Slice *, 4> SplitTails;
371
372
  /// Raw constructor builds an empty partition starting and ending at
373
  /// the given iterator.
374
3.51M
  Partition(iterator SI) : SI(SI), SJ(SI) {}
375
376
public:
377
  /// The start offset of this partition.
378
  ///
379
  /// All of the contained slices start at or after this offset.
380
6.59M
  uint64_t beginOffset() const { return BeginOffset; }
381
382
  /// The end offset of this partition.
383
  ///
384
  /// All of the contained slices end at or before this offset.
385
4.57M
  uint64_t endOffset() const { return EndOffset; }
386
387
  /// The size of the partition.
388
  ///
389
  /// Note that this can never be zero.
390
1.06M
  uint64_t size() const {
391
1.06M
    assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
392
1.06M
    return EndOffset - BeginOffset;
393
1.06M
  }
394
395
  /// Test whether this partition contains no slices, and merely spans
396
  /// a region occupied by split slices.
397
0
  bool empty() const { return SI == SJ; }
398
399
  /// \name Iterate slices that start within the partition.
400
  /// These may be splittable or unsplittable. They have a begin offset >= the
401
  /// partition begin offset.
402
  /// @{
403
  // FIXME: We should probably define a "concat_iterator" helper and use that
404
  // to stitch together pointee_iterators over the split tails and the
405
  // contiguous iterators of the partition. That would give a much nicer
406
  // interface here. We could then additionally expose filtered iterators for
407
  // split, unsplit, and unsplittable splices based on the usage patterns.
408
6.75M
  iterator begin() const { return SI; }
409
6.63M
  iterator end() const { return SJ; }
410
  /// @}
411
412
  /// Get the sequence of split slice tails.
413
  ///
414
  /// These tails are of slices which start before this partition but are
415
  /// split and overlap into the partition. We accumulate these while forming
416
  /// partitions.
417
2.79M
  ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
418
};
419
420
/// An iterator over partitions of the alloca's slices.
421
///
422
/// This iterator implements the core algorithm for partitioning the alloca's
423
/// slices. It is a forward iterator as we don't support backtracking for
424
/// efficiency reasons, and re-use a single storage area to maintain the
425
/// current set of split slices.
426
///
427
/// It is templated on the slice iterator type to use so that it can operate
428
/// with either const or non-const slice iterators.
429
class AllocaSlices::partition_iterator
430
    : public iterator_facade_base<partition_iterator, std::forward_iterator_tag,
431
                                  Partition> {
432
  friend class AllocaSlices;
433
434
  /// Most of the state for walking the partitions is held in a class
435
  /// with a nice interface for examining them.
436
  Partition P;
437
438
  /// We need to keep the end of the slices to know when to stop.
439
  AllocaSlices::iterator SE;
440
441
  /// We also need to keep track of the maximum split end offset seen.
442
  /// FIXME: Do we really?
443
  uint64_t MaxSplitSliceEndOffset = 0;
444
445
  /// Sets the partition to be empty at given iterator, and sets the
446
  /// end iterator.
447
  partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
448
3.51M
      : P(SI), SE(SE) {
449
3.51M
    // If not already at the end, advance our state to form the initial
450
3.51M
    // partition.
451
3.51M
    if (SI != SE)
452
1.75M
      advance();
453
3.51M
  }
454
455
  /// Advance the iterator to the next partition.
456
  ///
457
  /// Requires that the iterator not be at the end of the slices.
458
3.61M
  void advance() {
459
3.61M
    assert((P.SI != SE || !P.SplitTails.empty()) &&
460
3.61M
           "Cannot advance past the end of the slices!");
461
3.61M
462
3.61M
    // Clear out any split uses which have ended.
463
3.61M
    if (!P.SplitTails.empty()) {
464
86.1k
      if (P.EndOffset >= MaxSplitSliceEndOffset) {
465
32.0k
        // If we've finished all splits, this is easy.
466
32.0k
        P.SplitTails.clear();
467
32.0k
        MaxSplitSliceEndOffset = 0;
468
54.0k
      } else {
469
54.0k
        // Remove the uses which have ended in the prior partition. This
470
54.0k
        // cannot change the max split slice end because we just checked that
471
54.0k
        // the prior partition ended prior to that max.
472
54.0k
        P.SplitTails.erase(llvm::remove_if(P.SplitTails,
473
134k
                                           [&](Slice *S) {
474
134k
                                             return S->endOffset() <=
475
134k
                                                    P.EndOffset;
476
134k
                                           }),
477
54.0k
                           P.SplitTails.end());
478
54.0k
        assert(llvm::any_of(P.SplitTails,
479
54.0k
                            [&](Slice *S) {
480
54.0k
                              return S->endOffset() == MaxSplitSliceEndOffset;
481
54.0k
                            }) &&
482
54.0k
               "Could not find the current max split slice offset!");
483
54.0k
        assert(llvm::all_of(P.SplitTails,
484
54.0k
                            [&](Slice *S) {
485
54.0k
                              return S->endOffset() <= MaxSplitSliceEndOffset;
486
54.0k
                            }) &&
487
54.0k
               "Max split slice end offset is not actually the max!");
488
54.0k
      }
489
86.1k
    }
490
3.61M
491
3.61M
    // If P.SI is already at the end, then we've cleared the split tail and
492
3.61M
    // now have an end iterator.
493
3.61M
    if (P.SI == SE) {
494
3.24k
      assert(P.SplitTails.empty() && "Failed to clear the split slices!");
495
3.24k
      return;
496
3.24k
    }
497
3.61M
498
3.61M
    // If we had a non-empty partition previously, set up the state for
499
3.61M
    // subsequent partitions.
500
3.61M
    if (P.SI != P.SJ) {
501
1.85M
      // Accumulate all the splittable slices which started in the old
502
1.85M
      // partition into the split list.
503
1.85M
      for (Slice &S : P)
504
7.58M
        if (S.isSplittable() && 
S.endOffset() > P.EndOffset4.25M
) {
505
74.0k
          P.SplitTails.push_back(&S);
506
74.0k
          MaxSplitSliceEndOffset =
507
74.0k
              std::max(S.endOffset(), MaxSplitSliceEndOffset);
508
74.0k
        }
509
1.85M
510
1.85M
      // Start from the end of the previous partition.
511
1.85M
      P.SI = P.SJ;
512
1.85M
513
1.85M
      // If P.SI is now at the end, we at most have a tail of split slices.
514
1.85M
      if (P.SI == SE) {
515
1.75M
        P.BeginOffset = P.EndOffset;
516
1.75M
        P.EndOffset = MaxSplitSliceEndOffset;
517
1.75M
        return;
518
1.75M
      }
519
94.9k
520
94.9k
      // If the we have split slices and the next slice is after a gap and is
521
94.9k
      // not splittable immediately form an empty partition for the split
522
94.9k
      // slices up until the next slice begins.
523
94.9k
      if (!P.SplitTails.empty() && 
P.SI->beginOffset() != P.EndOffset81.5k
&&
524
94.9k
          
!P.SI->isSplittable()1.54k
) {
525
1.38k
        P.BeginOffset = P.EndOffset;
526
1.38k
        P.EndOffset = P.SI->beginOffset();
527
1.38k
        return;
528
1.38k
      }
529
1.85M
    }
530
1.85M
531
1.85M
    // OK, we need to consume new slices. Set the end offset based on the
532
1.85M
    // current slice, and step SJ past it. The beginning offset of the
533
1.85M
    // partition is the beginning offset of the next slice unless we have
534
1.85M
    // pre-existing split slices that are continuing, in which case we begin
535
1.85M
    // at the prior end offset.
536
1.85M
    P.BeginOffset = P.SplitTails.empty() ? 
P.SI->beginOffset()1.77M
:
P.EndOffset81.5k
;
537
1.85M
    P.EndOffset = P.SI->endOffset();
538
1.85M
    ++P.SJ;
539
1.85M
540
1.85M
    // There are two strategies to form a partition based on whether the
541
1.85M
    // partition starts with an unsplittable slice or a splittable slice.
542
1.85M
    if (!P.SI->isSplittable()) {
543
1.10M
      // When we're forming an unsplittable region, it must always start at
544
1.10M
      // the first slice and will extend through its end.
545
1.10M
      assert(P.BeginOffset == P.SI->beginOffset());
546
1.10M
547
1.10M
      // Form a partition including all of the overlapping slices with this
548
1.10M
      // unsplittable slice.
549
3.90M
      while (P.SJ != SE && 
P.SJ->beginOffset() < P.EndOffset2.88M
) {
550
2.80M
        if (!P.SJ->isSplittable())
551
2.22M
          P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
552
2.80M
        ++P.SJ;
553
2.80M
      }
554
1.10M
555
1.10M
      // We have a partition across a set of overlapping unsplittable
556
1.10M
      // partitions.
557
1.10M
      return;
558
1.10M
    }
559
746k
560
746k
    // If we're starting with a splittable slice, then we need to form
561
746k
    // a synthetic partition spanning it and any other overlapping splittable
562
746k
    // splices.
563
746k
    assert(P.SI->isSplittable() && "Forming a splittable partition!");
564
746k
565
746k
    // Collect all of the overlapping splittable slices.
566
3.67M
    while (P.SJ != SE && 
P.SJ->beginOffset() < P.EndOffset2.94M
&&
567
3.67M
           
P.SJ->isSplittable()2.93M
) {
568
2.93M
      P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
569
2.93M
      ++P.SJ;
570
2.93M
    }
571
746k
572
746k
    // Back upiP.EndOffset if we ended the span early when encountering an
573
746k
    // unsplittable slice. This synthesizes the early end offset of
574
746k
    // a partition spanning only splittable slices.
575
746k
    if (P.SJ != SE && 
P.SJ->beginOffset() < P.EndOffset11.3k
) {
576
2.25k
      assert(!P.SJ->isSplittable());
577
2.25k
      P.EndOffset = P.SJ->beginOffset();
578
2.25k
    }
579
746k
  }
580
581
public:
582
3.61M
  bool operator==(const partition_iterator &RHS) const {
583
3.61M
    assert(SE == RHS.SE &&
584
3.61M
           "End iterators don't match between compared partition iterators!");
585
3.61M
586
3.61M
    // The observed positions of partitions is marked by the P.SI iterator and
587
3.61M
    // the emptiness of the split slices. The latter is only relevant when
588
3.61M
    // P.SI == SE, as the end iterator will additionally have an empty split
589
3.61M
    // slices list, but the prior may have the same P.SI and a tail of split
590
3.61M
    // slices.
591
3.61M
    if (P.SI == RHS.P.SI && 
P.SplitTails.empty() == RHS.P.SplitTails.empty()1.76M
) {
592
1.75M
      assert(P.SJ == RHS.P.SJ &&
593
1.75M
             "Same set of slices formed two different sized partitions!");
594
1.75M
      assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
595
1.75M
             "Same slice position with differently sized non-empty split "
596
1.75M
             "slice tails!");
597
1.75M
      return true;
598
1.75M
    }
599
1.85M
    return false;
600
1.85M
  }
601
602
1.85M
  partition_iterator &operator++() {
603
1.85M
    advance();
604
1.85M
    return *this;
605
1.85M
  }
606
607
1.85M
  Partition &operator*() { return P; }
608
};
609
610
/// A forward range over the partitions of the alloca's slices.
611
///
612
/// This accesses an iterator range over the partitions of the alloca's
613
/// slices. It computes these partitions on the fly based on the overlapping
614
/// offsets of the slices and the ability to split them. It will visit "empty"
615
/// partitions to cover regions of the alloca only accessed via split
616
/// slices.
617
1.75M
iterator_range<AllocaSlices::partition_iterator> AllocaSlices::partitions() {
618
1.75M
  return make_range(partition_iterator(begin(), end()),
619
1.75M
                    partition_iterator(end(), end()));
620
1.75M
}
621
622
1.82k
static Value *foldSelectInst(SelectInst &SI) {
623
1.82k
  // If the condition being selected on is a constant or the same value is
624
1.82k
  // being selected between, fold the select. Yes this does (rarely) happen
625
1.82k
  // early on.
626
1.82k
  if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
627
4
    return SI.getOperand(1 + CI->isZero());
628
1.82k
  if (SI.getOperand(1) == SI.getOperand(2))
629
26
    return SI.getOperand(1);
630
1.79k
631
1.79k
  return nullptr;
632
1.79k
}
633
634
/// A helper that folds a PHI node or a select.
635
10.1k
static Value *foldPHINodeOrSelectInst(Instruction &I) {
636
10.1k
  if (PHINode *PN = dyn_cast<PHINode>(&I)) {
637
8.35k
    // If PN merges together the same value, return that value.
638
8.35k
    return PN->hasConstantValue();
639
8.35k
  }
640
1.82k
  return foldSelectInst(cast<SelectInst>(I));
641
1.82k
}
642
643
/// Builder for the alloca slices.
644
///
645
/// This class builds a set of alloca slices by recursively visiting the uses
646
/// of an alloca and making a slice for each load and store at each offset.
647
class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
648
  friend class PtrUseVisitor<SliceBuilder>;
649
  friend class InstVisitor<SliceBuilder>;
650
651
  using Base = PtrUseVisitor<SliceBuilder>;
652
653
  const uint64_t AllocSize;
654
  AllocaSlices &AS;
655
656
  SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
657
  SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
658
659
  /// Set to de-duplicate dead instructions found in the use walk.
660
  SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
661
662
public:
663
  SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS)
664
      : PtrUseVisitor<SliceBuilder>(DL),
665
1.08M
        AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
666
667
private:
668
3.11k
  void markAsDead(Instruction &I) {
669
3.11k
    if (VisitedDeadInsts.insert(&I).second)
670
3.11k
      AS.DeadUsers.push_back(&I);
671
3.11k
  }
672
673
  void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
674
4.27M
                 bool IsSplittable = false) {
675
4.27M
    // Completely skip uses which have a zero size or start either before or
676
4.27M
    // past the end of the allocation.
677
4.27M
    if (Size == 0 || 
Offset.uge(AllocSize)4.27M
) {
678
5
      LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @"
679
5
                        << Offset
680
5
                        << " which has zero size or starts outside of the "
681
5
                        << AllocSize << " byte alloca:\n"
682
5
                        << "    alloca: " << AS.AI << "\n"
683
5
                        << "       use: " << I << "\n");
684
5
      return markAsDead(I);
685
5
    }
686
4.27M
687
4.27M
    uint64_t BeginOffset = Offset.getZExtValue();
688
4.27M
    uint64_t EndOffset = BeginOffset + Size;
689
4.27M
690
4.27M
    // Clamp the end offset to the end of the allocation. Note that this is
691
4.27M
    // formulated to handle even the case where "BeginOffset + Size" overflows.
692
4.27M
    // This may appear superficially to be something we could ignore entirely,
693
4.27M
    // but that is not so! There may be widened loads or PHI-node uses where
694
4.27M
    // some instructions are dead but not others. We can't completely ignore
695
4.27M
    // them, and so have to record at least the information here.
696
4.27M
    assert(AllocSize >= BeginOffset); // Established above.
697
4.27M
    if (Size > AllocSize - BeginOffset) {
698
30
      LLVM_DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @"
699
30
                        << Offset << " to remain within the " << AllocSize
700
30
                        << " byte alloca:\n"
701
30
                        << "    alloca: " << AS.AI << "\n"
702
30
                        << "       use: " << I << "\n");
703
30
      EndOffset = AllocSize;
704
30
    }
705
4.27M
706
4.27M
    AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
707
4.27M
  }
708
709
881k
  void visitBitCastInst(BitCastInst &BC) {
710
881k
    if (BC.use_empty())
711
2.79k
      return markAsDead(BC);
712
878k
713
878k
    return Base::visitBitCastInst(BC);
714
878k
  }
715
716
156
  void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
717
156
    if (ASC.use_empty())
718
11
      return markAsDead(ASC);
719
145
720
145
    return Base::visitAddrSpaceCastInst(ASC);
721
145
  }
722
723
368k
  void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
724
368k
    if (GEPI.use_empty())
725
266
      return markAsDead(GEPI);
726
367k
727
367k
    if (SROAStrictInbounds && 
GEPI.isInBounds()0
) {
728
0
      // FIXME: This is a manually un-factored variant of the basic code inside
729
0
      // of GEPs with checking of the inbounds invariant specified in the
730
0
      // langref in a very strict sense. If we ever want to enable
731
0
      // SROAStrictInbounds, this code should be factored cleanly into
732
0
      // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
733
0
      // by writing out the code here where we have the underlying allocation
734
0
      // size readily available.
735
0
      APInt GEPOffset = Offset;
736
0
      const DataLayout &DL = GEPI.getModule()->getDataLayout();
737
0
      for (gep_type_iterator GTI = gep_type_begin(GEPI),
738
0
                             GTE = gep_type_end(GEPI);
739
0
           GTI != GTE; ++GTI) {
740
0
        ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
741
0
        if (!OpC)
742
0
          break;
743
0
744
0
        // Handle a struct index, which adds its field offset to the pointer.
745
0
        if (StructType *STy = GTI.getStructTypeOrNull()) {
746
0
          unsigned ElementIdx = OpC->getZExtValue();
747
0
          const StructLayout *SL = DL.getStructLayout(STy);
748
0
          GEPOffset +=
749
0
              APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
750
0
        } else {
751
0
          // For array or vector indices, scale the index by the size of the
752
0
          // type.
753
0
          APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
754
0
          GEPOffset += Index * APInt(Offset.getBitWidth(),
755
0
                                     DL.getTypeAllocSize(GTI.getIndexedType()));
756
0
        }
757
0
758
0
        // If this index has computed an intermediate pointer which is not
759
0
        // inbounds, then the result of the GEP is a poison value and we can
760
0
        // delete it and all uses.
761
0
        if (GEPOffset.ugt(AllocSize))
762
0
          return markAsDead(GEPI);
763
0
      }
764
0
    }
765
367k
766
367k
    return Base::visitGetElementPtrInst(GEPI);
767
367k
  }
768
769
  void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
770
3.29M
                         uint64_t Size, bool IsVolatile) {
771
3.29M
    // We allow splitting of non-volatile loads and stores where the type is an
772
3.29M
    // integer type. These may be used to implement 'memcpy' or other "transfer
773
3.29M
    // of bits" patterns.
774
3.29M
    bool IsSplittable = Ty->isIntegerTy() && 
!IsVolatile1.59M
;
775
3.29M
776
3.29M
    insertUse(I, Offset, Size, IsSplittable);
777
3.29M
  }
778
779
1.92M
  void visitLoadInst(LoadInst &LI) {
780
1.92M
    assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
781
1.92M
           "All simple FCA loads should have been pre-split");
782
1.92M
783
1.92M
    if (!IsOffsetKnown)
784
2.29k
      return PI.setAborted(&LI);
785
1.92M
786
1.92M
    if (LI.isVolatile() &&
787
1.92M
        
LI.getPointerAddressSpace() != DL.getAllocaAddrSpace()592
)
788
2
      return PI.setAborted(&LI);
789
1.92M
790
1.92M
    uint64_t Size = DL.getTypeStoreSize(LI.getType());
791
1.92M
    return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
792
1.92M
  }
793
794
1.37M
  void visitStoreInst(StoreInst &SI) {
795
1.37M
    Value *ValOp = SI.getValueOperand();
796
1.37M
    if (ValOp == *U)
797
9.32k
      return PI.setEscapedAndAborted(&SI);
798
1.36M
    if (!IsOffsetKnown)
799
1.62k
      return PI.setAborted(&SI);
800
1.36M
801
1.36M
    if (SI.isVolatile() &&
802
1.36M
        
SI.getPointerAddressSpace() != DL.getAllocaAddrSpace()670
)
803
2
      return PI.setAborted(&SI);
804
1.36M
805
1.36M
    uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
806
1.36M
807
1.36M
    // If this memory access can be shown to *statically* extend outside the
808
1.36M
    // bounds of the allocation, it's behavior is undefined, so simply
809
1.36M
    // ignore it. Note that this is more strict than the generic clamping
810
1.36M
    // behavior of insertUse. We also try to handle cases which might run the
811
1.36M
    // risk of overflow.
812
1.36M
    // FIXME: We should instead consider the pointer to have escaped if this
813
1.36M
    // function is being instrumented for addressing bugs or race conditions.
814
1.36M
    if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
815
15
      LLVM_DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @"
816
15
                        << Offset << " which extends past the end of the "
817
15
                        << AllocSize << " byte alloca:\n"
818
15
                        << "    alloca: " << AS.AI << "\n"
819
15
                        << "       use: " << SI << "\n");
820
15
      return markAsDead(SI);
821
15
    }
822
1.36M
823
1.36M
    assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
824
1.36M
           "All simple FCA stores should have been pre-split");
825
1.36M
    handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
826
1.36M
  }
827
828
8.06k
  void visitMemSetInst(MemSetInst &II) {
829
8.06k
    assert(II.getRawDest() == *U && "Pointer use is not the destination?");
830
8.06k
    ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
831
8.06k
    if ((Length && 
Length->getValue() == 08.05k
) ||
832
8.06k
        (IsOffsetKnown && 
Offset.uge(AllocSize)8.06k
))
833
2
      // Zero-length mem transfer intrinsics can be ignored entirely.
834
2
      return markAsDead(II);
835
8.06k
836
8.06k
    if (!IsOffsetKnown)
837
2
      return PI.setAborted(&II);
838
8.06k
839
8.06k
    // Don't replace this with a store with a different address space.  TODO:
840
8.06k
    // Use a store with the casted new alloca?
841
8.06k
    if (II.isVolatile() && 
II.getDestAddressSpace() != DL.getAllocaAddrSpace()7
)
842
2
      return PI.setAborted(&II);
843
8.06k
844
8.06k
    insertUse(II, Offset, Length ? 
Length->getLimitedValue()8.05k
845
8.06k
                                 : 
AllocSize - Offset.getLimitedValue()11
,
846
8.06k
              (bool)Length);
847
8.06k
  }
848
849
33.6k
  void visitMemTransferInst(MemTransferInst &II) {
850
33.6k
    ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
851
33.6k
    if (Length && 
Length->getValue() == 033.6k
)
852
0
      // Zero-length mem transfer intrinsics can be ignored entirely.
853
0
      return markAsDead(II);
854
33.6k
855
33.6k
    // Because we can visit these intrinsics twice, also check to see if the
856
33.6k
    // first time marked this instruction as dead. If so, skip it.
857
33.6k
    if (VisitedDeadInsts.count(&II))
858
4
      return;
859
33.6k
860
33.6k
    if (!IsOffsetKnown)
861
4
      return PI.setAborted(&II);
862
33.6k
863
33.6k
    // Don't replace this with a load/store with a different address space.
864
33.6k
    // TODO: Use a store with the casted new alloca?
865
33.6k
    if (II.isVolatile() &&
866
33.6k
        
(52
II.getDestAddressSpace() != DL.getAllocaAddrSpace()52
||
867
52
         
II.getSourceAddressSpace() != DL.getAllocaAddrSpace()48
))
868
4
      return PI.setAborted(&II);
869
33.6k
870
33.6k
    // This side of the transfer is completely out-of-bounds, and so we can
871
33.6k
    // nuke the entire transfer. However, we also need to nuke the other side
872
33.6k
    // if already added to our partitions.
873
33.6k
    // FIXME: Yet another place we really should bypass this when
874
33.6k
    // instrumenting for ASan.
875
33.6k
    if (Offset.uge(AllocSize)) {
876
4
      SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
877
4
          MemTransferSliceMap.find(&II);
878
4
      if (MTPI != MemTransferSliceMap.end())
879
0
        AS.Slices[MTPI->second].kill();
880
4
      return markAsDead(II);
881
4
    }
882
33.6k
883
33.6k
    uint64_t RawOffset = Offset.getLimitedValue();
884
33.6k
    uint64_t Size = Length ? 
Length->getLimitedValue()33.6k
:
AllocSize - RawOffset21
;
885
33.6k
886
33.6k
    // Check for the special case where the same exact value is used for both
887
33.6k
    // source and dest.
888
33.6k
    if (*U == II.getRawDest() && 
*U == II.getRawSource()18.4k
) {
889
2
      // For non-volatile transfers this is a no-op.
890
2
      if (!II.isVolatile())
891
2
        return markAsDead(II);
892
0
893
0
      return insertUse(II, Offset, Size, /*IsSplittable=*/false);
894
0
    }
895
33.6k
896
33.6k
    // If we have seen both source and destination for a mem transfer, then
897
33.6k
    // they both point to the same alloca.
898
33.6k
    bool Inserted;
899
33.6k
    SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
900
33.6k
    std::tie(MTPI, Inserted) =
901
33.6k
        MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
902
33.6k
    unsigned PrevIdx = MTPI->second;
903
33.6k
    if (!Inserted) {
904
9
      Slice &PrevP = AS.Slices[PrevIdx];
905
9
906
9
      // Check if the begin offsets match and this is a non-volatile transfer.
907
9
      // In that case, we can completely elide the transfer.
908
9
      if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
909
4
        PrevP.kill();
910
4
        return markAsDead(II);
911
4
      }
912
5
913
5
      // Otherwise we have an offset transfer within the same alloca. We can't
914
5
      // split those.
915
5
      PrevP.makeUnsplittable();
916
5
    }
917
33.6k
918
33.6k
    // Insert the use now that we've fixed up the splittable nature.
919
33.6k
    
insertUse(II, Offset, Size, /*IsSplittable=*/33.6k
Inserted33.6k
&&
Length33.6k
);
920
33.6k
921
33.6k
    // Check that we ended up with a valid index in the map.
922
33.6k
    assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
923
33.6k
           "Map index doesn't point back to a slice with this user.");
924
33.6k
  }
925
926
  // Disable SRoA for any intrinsics except for lifetime invariants.
927
  // FIXME: What about debug intrinsics? This matches old behavior, but
928
  // doesn't make sense.
929
945k
  void visitIntrinsicInst(IntrinsicInst &II) {
930
945k
    if (!IsOffsetKnown)
931
134
      return PI.setAborted(&II);
932
945k
933
945k
    if (II.isLifetimeStartOrEnd()) {
934
943k
      ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
935
943k
      uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
936
943k
                               Length->getLimitedValue());
937
943k
      insertUse(II, Offset, Size, true);
938
943k
      return;
939
943k
    }
940
1.80k
941
1.80k
    Base::visitIntrinsicInst(II);
942
1.80k
  }
943
944
8.94k
  Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
945
8.94k
    // We consider any PHI or select that results in a direct load or store of
946
8.94k
    // the same offset to be a viable use for slicing purposes. These uses
947
8.94k
    // are considered unsplittable and the size is the maximum loaded or stored
948
8.94k
    // size.
949
8.94k
    SmallPtrSet<Instruction *, 4> Visited;
950
8.94k
    SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
951
8.94k
    Visited.insert(Root);
952
8.94k
    Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
953
8.94k
    const DataLayout &DL = Root->getModule()->getDataLayout();
954
8.94k
    // If there are no loads or stores, the access is dead. We mark that as
955
8.94k
    // a size zero access.
956
8.94k
    Size = 0;
957
18.8k
    do {
958
18.8k
      Instruction *I, *UsedI;
959
18.8k
      std::tie(UsedI, I) = Uses.pop_back_val();
960
18.8k
961
18.8k
      if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
962
2.17k
        Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
963
2.17k
        continue;
964
2.17k
      }
965
16.6k
      if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
966
493
        Value *Op = SI->getOperand(0);
967
493
        if (Op == UsedI)
968
12
          return SI;
969
481
        Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
970
481
        continue;
971
481
      }
972
16.1k
973
16.1k
      if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
974
5.83k
        if (!GEP->hasAllZeroIndices())
975
5.82k
          return GEP;
976
10.3k
      } else if (!isa<BitCastInst>(I) && 
!isa<PHINode>(I)10.1k
&&
977
10.3k
                 
!isa<SelectInst>(I)2.83k
&&
!isa<AddrSpaceCastInst>(I)1.01k
) {
978
1.01k
        return I;
979
1.01k
      }
980
9.32k
981
9.32k
      for (User *U : I->users())
982
18.3k
        if (Visited.insert(cast<Instruction>(U)).second)
983
18.2k
          Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
984
11.9k
    } while (!Uses.empty());
985
8.94k
986
8.94k
    
return nullptr2.08k
;
987
8.94k
  }
988
989
10.1k
  void visitPHINodeOrSelectInst(Instruction &I) {
990
10.1k
    assert(isa<PHINode>(I) || isa<SelectInst>(I));
991
10.1k
    if (I.use_empty())
992
11
      return markAsDead(I);
993
10.1k
994
10.1k
    // TODO: We could use SimplifyInstruction here to fold PHINodes and
995
10.1k
    // SelectInsts. However, doing so requires to change the current
996
10.1k
    // dead-operand-tracking mechanism. For instance, suppose neither loading
997
10.1k
    // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
998
10.1k
    // trap either.  However, if we simply replace %U with undef using the
999
10.1k
    // current dead-operand-tracking mechanism, "load (select undef, undef,
1000
10.1k
    // %other)" may trap because the select may return the first operand
1001
10.1k
    // "undef".
1002
10.1k
    if (Value *Result = foldPHINodeOrSelectInst(I)) {
1003
803
      if (Result == *U)
1004
801
        // If the result of the constant fold will be the pointer, recurse
1005
801
        // through the PHI/select as if we had RAUW'ed it.
1006
801
        enqueueUsers(I);
1007
2
      else
1008
2
        // Otherwise the operand to the PHI/select is dead, and we can replace
1009
2
        // it with undef.
1010
2
        AS.DeadOperands.push_back(U);
1011
803
1012
803
      return;
1013
803
    }
1014
9.38k
1015
9.38k
    if (!IsOffsetKnown)
1016
1
      return PI.setAborted(&I);
1017
9.37k
1018
9.37k
    // See if we already have computed info on this node.
1019
9.37k
    uint64_t &Size = PHIOrSelectSizes[&I];
1020
9.37k
    if (!Size) {
1021
8.94k
      // This is a new PHI/Select, check for an unsafe use of it.
1022
8.94k
      if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
1023
6.85k
        return PI.setAborted(UnsafeI);
1024
2.52k
    }
1025
2.52k
1026
2.52k
    // For PHI and select operands outside the alloca, we can't nuke the entire
1027
2.52k
    // phi or select -- the other side might still be relevant, so we special
1028
2.52k
    // case them here and use a separate structure to track the operands
1029
2.52k
    // themselves which should be replaced with undef.
1030
2.52k
    // FIXME: This should instead be escaped in the event we're instrumenting
1031
2.52k
    // for address sanitization.
1032
2.52k
    if (Offset.uge(AllocSize)) {
1033
1
      AS.DeadOperands.push_back(U);
1034
1
      return;
1035
1
    }
1036
2.52k
1037
2.52k
    insertUse(I, Offset, Size);
1038
2.52k
  }
1039
1040
8.35k
  void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
1041
1042
1.83k
  void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
1043
1044
  /// Disable SROA entirely if there are unhandled users of the alloca.
1045
173k
  void visitInstruction(Instruction &I) { PI.setAborted(&I); }
1046
};
1047
1048
AllocaSlices::AllocaSlices(const DataLayout &DL, AllocaInst &AI)
1049
    :
1050
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1051
      AI(AI),
1052
#endif
1053
1.08M
      PointerEscapingInstr(nullptr) {
1054
1.08M
  SliceBuilder PB(DL, AI, *this);
1055
1.08M
  SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
1056
1.08M
  if (PtrI.isEscaped() || 
PtrI.isAborted()891k
) {
1057
201k
    // FIXME: We should sink the escape vs. abort info into the caller nicely,
1058
201k
    // possibly by just storing the PtrInfo in the AllocaSlices.
1059
201k
    PointerEscapingInstr = PtrI.getEscapingInst() ? 
PtrI.getEscapingInst()188k
1060
201k
                                                  : 
PtrI.getAbortingInst()12.5k
;
1061
201k
    assert(PointerEscapingInstr && "Did not track a bad instruction");
1062
201k
    return;
1063
201k
  }
1064
879k
1065
879k
  Slices.erase(
1066
3.79M
      llvm::remove_if(Slices, [](const Slice &S) { return S.isDead(); }),
1067
879k
      Slices.end());
1068
879k
1069
#ifndef NDEBUG
1070
  if (SROARandomShuffleSlices) {
1071
    std::mt19937 MT(static_cast<unsigned>(
1072
        std::chrono::system_clock::now().time_since_epoch().count()));
1073
    std::shuffle(Slices.begin(), Slices.end(), MT);
1074
  }
1075
#endif
1076
1077
879k
  // Sort the uses. This arranges for the offsets to be in ascending order,
1078
879k
  // and the sizes to be in descending order.
1079
879k
  llvm::sort(Slices);
1080
879k
}
1081
1082
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1083
1084
void AllocaSlices::print(raw_ostream &OS, const_iterator I,
1085
                         StringRef Indent) const {
1086
  printSlice(OS, I, Indent);
1087
  OS << "\n";
1088
  printUse(OS, I, Indent);
1089
}
1090
1091
void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
1092
                              StringRef Indent) const {
1093
  OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
1094
     << " slice #" << (I - begin())
1095
     << (I->isSplittable() ? " (splittable)" : "");
1096
}
1097
1098
void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
1099
                            StringRef Indent) const {
1100
  OS << Indent << "  used by: " << *I->getUse()->getUser() << "\n";
1101
}
1102
1103
void AllocaSlices::print(raw_ostream &OS) const {
1104
  if (PointerEscapingInstr) {
1105
    OS << "Can't analyze slices for alloca: " << AI << "\n"
1106
       << "  A pointer to this alloca escaped by:\n"
1107
       << "  " << *PointerEscapingInstr << "\n";
1108
    return;
1109
  }
1110
1111
  OS << "Slices of alloca: " << AI << "\n";
1112
  for (const_iterator I = begin(), E = end(); I != E; ++I)
1113
    print(OS, I);
1114
}
1115
1116
LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
1117
  print(dbgs(), I);
1118
}
1119
LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
1120
1121
#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1122
1123
/// Walk the range of a partitioning looking for a common type to cover this
1124
/// sequence of slices.
1125
static Type *findCommonType(AllocaSlices::const_iterator B,
1126
                            AllocaSlices::const_iterator E,
1127
938k
                            uint64_t EndOffset) {
1128
938k
  Type *Ty = nullptr;
1129
938k
  bool TyIsCommon = true;
1130
938k
  IntegerType *ITy = nullptr;
1131
938k
1132
938k
  // Note that we need to look at *every* alloca slice's Use to ensure we
1133
938k
  // always get consistent results regardless of the order of slices.
1134
4.73M
  for (AllocaSlices::const_iterator I = B; I != E; 
++I3.79M
) {
1135
3.79M
    Use *U = I->getUse();
1136
3.79M
    if (isa<IntrinsicInst>(*U->getUser()))
1137
697k
      continue;
1138
3.09M
    if (I->beginOffset() != B->beginOffset() || 
I->endOffset() != EndOffset3.09M
)
1139
6.70k
      continue;
1140
3.08M
1141
3.08M
    Type *UserTy = nullptr;
1142
3.08M
    if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1143
1.86M
      UserTy = LI->getType();
1144
1.86M
    } else 
if (StoreInst *1.22M
SI1.22M
= dyn_cast<StoreInst>(U->getUser())) {
1145
1.21M
      UserTy = SI->getValueOperand()->getType();
1146
1.21M
    }
1147
3.08M
1148
3.08M
    if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
1149
1.46M
      // If the type is larger than the partition, skip it. We only encounter
1150
1.46M
      // this for split integer operations where we want to use the type of the
1151
1.46M
      // entity causing the split. Also skip if the type is not a byte width
1152
1.46M
      // multiple.
1153
1.46M
      if (UserITy->getBitWidth() % 8 != 0 ||
1154
1.46M
          
UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset())1.44M
)
1155
15.3k
        continue;
1156
1.44M
1157
1.44M
      // Track the largest bitwidth integer type used in this way in case there
1158
1.44M
      // is no common type.
1159
1.44M
      if (!ITy || 
ITy->getBitWidth() < UserITy->getBitWidth()1.04M
)
1160
405k
        ITy = UserITy;
1161
1.44M
    }
1162
3.08M
1163
3.08M
    // To avoid depending on the order of slices, Ty and TyIsCommon must not
1164
3.08M
    // depend on types skipped above.
1165
3.08M
    
if (3.07M
!UserTy3.07M
||
(3.07M
Ty3.07M
&&
Ty != UserTy2.15M
))
1166
30.5k
      TyIsCommon = false; // Give up on anything but an iN type.
1167
3.04M
    else
1168
3.04M
      Ty = UserTy;
1169
3.07M
  }
1170
938k
1171
938k
  return TyIsCommon ? 
Ty915k
:
ITy22.4k
;
1172
938k
}
1173
1174
/// PHI instructions that use an alloca and are subsequently loaded can be
1175
/// rewritten to load both input pointers in the pred blocks and then PHI the
1176
/// results, allowing the load of the alloca to be promoted.
1177
/// From this:
1178
///   %P2 = phi [i32* %Alloca, i32* %Other]
1179
///   %V = load i32* %P2
1180
/// to:
1181
///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1182
///   ...
1183
///   %V2 = load i32* %Other
1184
///   ...
1185
///   %V = phi [i32 %V1, i32 %V2]
1186
///
1187
/// We can do this to a select if its only uses are loads and if the operands
1188
/// to the select can be loaded unconditionally.
1189
///
1190
/// FIXME: This should be hoisted into a generic utility, likely in
1191
/// Transforms/Util/Local.h
1192
424
static bool isSafePHIToSpeculate(PHINode &PN) {
1193
424
  const DataLayout &DL = PN.getModule()->getDataLayout();
1194
424
1195
424
  // For now, we can only do this promotion if the load is in the same block
1196
424
  // as the PHI, and if there are no stores between the phi and load.
1197
424
  // TODO: Allow recursive phi users.
1198
424
  // TODO: Allow stores.
1199
424
  BasicBlock *BB = PN.getParent();
1200
424
  unsigned MaxAlign = 0;
1201
424
  uint64_t APWidth = DL.getIndexTypeSizeInBits(PN.getType());
1202
424
  APInt MaxSize(APWidth, 0);
1203
424
  bool HaveLoad = false;
1204
424
  for (User *U : PN.users()) {
1205
424
    LoadInst *LI = dyn_cast<LoadInst>(U);
1206
424
    if (!LI || 
!LI->isSimple()376
)
1207
48
      return false;
1208
376
1209
376
    // For now we only allow loads in the same block as the PHI.  This is
1210
376
    // a common case that happens when instcombine merges two loads through
1211
376
    // a PHI.
1212
376
    if (LI->getParent() != BB)
1213
1
      return false;
1214
375
1215
375
    // Ensure that there are no instructions between the PHI and the load that
1216
375
    // could store.
1217
1.82k
    
for (BasicBlock::iterator BBI(PN); 375
&*BBI != LI;
++BBI1.44k
)
1218
1.80k
      if (BBI->mayWriteToMemory())
1219
360
        return false;
1220
375
1221
375
    uint64_t Size = DL.getTypeStoreSizeInBits(LI->getType());
1222
15
    MaxAlign = std::max(MaxAlign, LI->getAlignment());
1223
15
    MaxSize = MaxSize.ult(Size) ? APInt(APWidth, Size) : 
MaxSize0
;
1224
15
    HaveLoad = true;
1225
15
  }
1226
424
1227
424
  
if (15
!HaveLoad15
)
1228
0
    return false;
1229
15
1230
15
  // We can only transform this if it is safe to push the loads into the
1231
15
  // predecessor blocks. The only thing to watch out for is that we can't put
1232
15
  // a possibly trapping load in the predecessor if it is a critical edge.
1233
56
  
for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); 15
Idx != Num;
++Idx41
) {
1234
43
    Instruction *TI = PN.getIncomingBlock(Idx)->getTerminator();
1235
43
    Value *InVal = PN.getIncomingValue(Idx);
1236
43
1237
43
    // If the value is produced by the terminator of the predecessor (an
1238
43
    // invoke) or it has side-effects, there is no valid place to put a load
1239
43
    // in the predecessor.
1240
43
    if (TI == InVal || TI->mayHaveSideEffects())
1241
0
      return false;
1242
43
1243
43
    // If the predecessor has a single successor, then the edge isn't
1244
43
    // critical.
1245
43
    if (TI->getNumSuccessors() == 1)
1246
35
      continue;
1247
8
1248
8
    // If this pointer is always safe to load, or if we can prove that there
1249
8
    // is already a load in the block, then we can move the load to the pred
1250
8
    // block.
1251
8
    if (isSafeToLoadUnconditionally(InVal, MaxAlign, MaxSize, DL, TI))
1252
6
      continue;
1253
2
1254
2
    return false;
1255
2
  }
1256
15
1257
15
  
return true13
;
1258
15
}
1259
1260
9
static void speculatePHINodeLoads(PHINode &PN) {
1261
9
  LLVM_DEBUG(dbgs() << "    original: " << PN << "\n");
1262
9
1263
9
  LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
1264
9
  Type *LoadTy = SomeLoad->getType();
1265
9
  IRBuilderTy PHIBuilder(&PN);
1266
9
  PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
1267
9
                                        PN.getName() + ".sroa.speculated");
1268
9
1269
9
  // Get the AA tags and alignment to use from one of the loads.  It doesn't
1270
9
  // matter which one we get and if any differ.
1271
9
  AAMDNodes AATags;
1272
9
  SomeLoad->getAAMetadata(AATags);
1273
9
  unsigned Align = SomeLoad->getAlignment();
1274
9
1275
9
  // Rewrite all loads of the PN to use the new PHI.
1276
18
  while (!PN.use_empty()) {
1277
9
    LoadInst *LI = cast<LoadInst>(PN.user_back());
1278
9
    LI->replaceAllUsesWith(NewPN);
1279
9
    LI->eraseFromParent();
1280
9
  }
1281
9
1282
9
  // Inject loads into all of the pred blocks.
1283
9
  DenseMap<BasicBlock*, Value*> InjectedLoads;
1284
34
  for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; 
++Idx25
) {
1285
25
    BasicBlock *Pred = PN.getIncomingBlock(Idx);
1286
25
    Value *InVal = PN.getIncomingValue(Idx);
1287
25
1288
25
    // A PHI node is allowed to have multiple (duplicated) entries for the same
1289
25
    // basic block, as long as the value is the same. So if we already injected
1290
25
    // a load in the predecessor, then we should reuse the same load for all
1291
25
    // duplicated entries.
1292
25
    if (Value* V = InjectedLoads.lookup(Pred)) {
1293
1
      NewPN->addIncoming(V, Pred);
1294
1
      continue;
1295
1
    }
1296
24
1297
24
    Instruction *TI = Pred->getTerminator();
1298
24
    IRBuilderTy PredBuilder(TI);
1299
24
1300
24
    LoadInst *Load = PredBuilder.CreateLoad(
1301
24
        LoadTy, InVal,
1302
24
        (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
1303
24
    ++NumLoadsSpeculated;
1304
24
    Load->setAlignment(Align);
1305
24
    if (AATags)
1306
0
      Load->setAAMetadata(AATags);
1307
24
    NewPN->addIncoming(Load, Pred);
1308
24
    InjectedLoads[Pred] = Load;
1309
24
  }
1310
9
1311
9
  LLVM_DEBUG(dbgs() << "          speculated to: " << *NewPN << "\n");
1312
9
  PN.eraseFromParent();
1313
9
}
1314
1315
/// Select instructions that use an alloca and are subsequently loaded can be
1316
/// rewritten to load both input pointers and then select between the result,
1317
/// allowing the load of the alloca to be promoted.
1318
/// From this:
1319
///   %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1320
///   %V = load i32* %P2
1321
/// to:
1322
///   %V1 = load i32* %Alloca      -> will be mem2reg'd
1323
///   %V2 = load i32* %Other
1324
///   %V = select i1 %cond, i32 %V1, i32 %V2
1325
///
1326
/// We can do this to a select if its only uses are loads and if the operand
1327
/// to the select can be loaded unconditionally.
1328
1.61k
static bool isSafeSelectToSpeculate(SelectInst &SI) {
1329
1.61k
  Value *TValue = SI.getTrueValue();
1330
1.61k
  Value *FValue = SI.getFalseValue();
1331
1.61k
  const DataLayout &DL = SI.getModule()->getDataLayout();
1332
1.61k
1333
1.62k
  for (User *U : SI.users()) {
1334
1.62k
    LoadInst *LI = dyn_cast<LoadInst>(U);
1335
1.62k
    if (!LI || 
!LI->isSimple()1.46k
)
1336
156
      return false;
1337
1.46k
1338
1.46k
    // Both operands to the select need to be dereferenceable, either
1339
1.46k
    // absolutely (e.g. allocas) or at this point because we can see other
1340
1.46k
    // accesses to it.
1341
1.46k
    if (!isSafeToLoadUnconditionally(TValue, LI->getType(), LI->getAlignment(),
1342
1.46k
                                     DL, LI))
1343
11
      return false;
1344
1.45k
    if (!isSafeToLoadUnconditionally(FValue, LI->getType(), LI->getAlignment(),
1345
1.45k
                                     DL, LI))
1346
3
      return false;
1347
1.45k
  }
1348
1.61k
1349
1.61k
  
return true1.44k
;
1350
1.61k
}
1351
1352
1.43k
static void speculateSelectInstLoads(SelectInst &SI) {
1353
1.43k
  LLVM_DEBUG(dbgs() << "    original: " << SI << "\n");
1354
1.43k
1355
1.43k
  IRBuilderTy IRB(&SI);
1356
1.43k
  Value *TV = SI.getTrueValue();
1357
1.43k
  Value *FV = SI.getFalseValue();
1358
1.43k
  // Replace the loads of the select with a select of two loads.
1359
2.87k
  while (!SI.use_empty()) {
1360
1.43k
    LoadInst *LI = cast<LoadInst>(SI.user_back());
1361
1.43k
    assert(LI->isSimple() && "We only speculate simple loads");
1362
1.43k
1363
1.43k
    IRB.SetInsertPoint(LI);
1364
1.43k
    LoadInst *TL = IRB.CreateLoad(LI->getType(), TV,
1365
1.43k
                                  LI->getName() + ".sroa.speculate.load.true");
1366
1.43k
    LoadInst *FL = IRB.CreateLoad(LI->getType(), FV,
1367
1.43k
                                  LI->getName() + ".sroa.speculate.load.false");
1368
1.43k
    NumLoadsSpeculated += 2;
1369
1.43k
1370
1.43k
    // Transfer alignment and AA info if present.
1371
1.43k
    TL->setAlignment(LI->getAlignment());
1372
1.43k
    FL->setAlignment(LI->getAlignment());
1373
1.43k
1374
1.43k
    AAMDNodes Tags;
1375
1.43k
    LI->getAAMetadata(Tags);
1376
1.43k
    if (Tags) {
1377
1.41k
      TL->setAAMetadata(Tags);
1378
1.41k
      FL->setAAMetadata(Tags);
1379
1.41k
    }
1380
1.43k
1381
1.43k
    Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
1382
1.43k
                                LI->getName() + ".sroa.speculated");
1383
1.43k
1384
1.43k
    LLVM_DEBUG(dbgs() << "          speculated to: " << *V << "\n");
1385
1.43k
    LI->replaceAllUsesWith(V);
1386
1.43k
    LI->eraseFromParent();
1387
1.43k
  }
1388
1.43k
  SI.eraseFromParent();
1389
1.43k
}
1390
1391
/// Build a GEP out of a base pointer and indices.
1392
///
1393
/// This will return the BasePtr if that is valid, or build a new GEP
1394
/// instruction using the IRBuilder if GEP-ing is needed.
1395
static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
1396
805k
                       SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
1397
805k
  if (Indices.empty())
1398
0
    return BasePtr;
1399
805k
1400
805k
  // A single zero index is a no-op, so check for this and avoid building a GEP
1401
805k
  // in that case.
1402
805k
  if (Indices.size() == 1 && 
cast<ConstantInt>(Indices.back())->isZero()760k
)
1403
743k
    return BasePtr;
1404
61.7k
1405
61.7k
  return IRB.CreateInBoundsGEP(BasePtr->getType()->getPointerElementType(),
1406
61.7k
                               BasePtr, Indices, NamePrefix + "sroa_idx");
1407
61.7k
}
1408
1409
/// Get a natural GEP off of the BasePtr walking through Ty toward
1410
/// TargetTy without changing the offset of the pointer.
1411
///
1412
/// This routine assumes we've already established a properly offset GEP with
1413
/// Indices, and arrived at the Ty type. The goal is to continue to GEP with
1414
/// zero-indices down through type layers until we find one the same as
1415
/// TargetTy. If we can't find one with the same type, we at least try to use
1416
/// one with the same size. If none of that works, we just produce the GEP as
1417
/// indicated by Indices to have the correct offset.
1418
static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
1419
                                    Value *BasePtr, Type *Ty, Type *TargetTy,
1420
                                    SmallVectorImpl<Value *> &Indices,
1421
805k
                                    Twine NamePrefix) {
1422
805k
  if (Ty == TargetTy)
1423
14.2k
    return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1424
791k
1425
791k
  // Offset size to use for the indices.
1426
791k
  unsigned OffsetSize = DL.getIndexTypeSizeInBits(BasePtr->getType());
1427
791k
1428
791k
  // See if we can descend into a struct and locate a field with the correct
1429
791k
  // type.
1430
791k
  unsigned NumLayers = 0;
1431
791k
  Type *ElementTy = Ty;
1432
848k
  do {
1433
848k
    if (ElementTy->isPointerTy())
1434
166k
      break;
1435
681k
1436
681k
    if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
1437
14.5k
      ElementTy = ArrayTy->getElementType();
1438
14.5k
      Indices.push_back(IRB.getIntN(OffsetSize, 0));
1439
666k
    } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
1440
39.4k
      ElementTy = VectorTy->getElementType();
1441
39.4k
      Indices.push_back(IRB.getInt32(0));
1442
627k
    } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
1443
31.4k
      if (STy->element_begin() == STy->element_end())
1444
2
        break; // Nothing left to descend into.
1445
31.4k
      ElementTy = *STy->element_begin();
1446
31.4k
      Indices.push_back(IRB.getInt32(0));
1447
595k
    } else {
1448
595k
      break;
1449
595k
    }
1450
85.5k
    ++NumLayers;
1451
85.5k
  } while (ElementTy != TargetTy);
1452
791k
  if (ElementTy != TargetTy)
1453
762k
    Indices.erase(Indices.end() - NumLayers, Indices.end());
1454
791k
1455
791k
  return buildGEP(IRB, BasePtr, Indices, NamePrefix);
1456
791k
}
1457
1458
/// Recursively compute indices for a natural GEP.
1459
///
1460
/// This is the recursive step for getNaturalGEPWithOffset that walks down the
1461
/// element types adding appropriate indices for the GEP.
1462
static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
1463
                                       Value *Ptr, Type *Ty, APInt &Offset,
1464
                                       Type *TargetTy,
1465
                                       SmallVectorImpl<Value *> &Indices,
1466
855k
                                       Twine NamePrefix) {
1467
855k
  if (Offset == 0)
1468
805k
    return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
1469
805k
                                 NamePrefix);
1470
50.4k
1471
50.4k
  // We can't recurse through pointer types.
1472
50.4k
  if (Ty->isPointerTy())
1473
0
    return nullptr;
1474
50.4k
1475
50.4k
  // We try to analyze GEPs over vectors here, but note that these GEPs are
1476
50.4k
  // extremely poorly defined currently. The long-term goal is to remove GEPing
1477
50.4k
  // over a vector from the IR completely.
1478
50.4k
  if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
1479
9
    unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
1480
9
    if (ElementSizeInBits % 8 != 0) {
1481
0
      // GEPs over non-multiple of 8 size vector elements are invalid.
1482
0
      return nullptr;
1483
0
    }
1484
9
    APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
1485
9
    APInt NumSkippedElements = Offset.sdiv(ElementSize);
1486
9
    if (NumSkippedElements.ugt(VecTy->getNumElements()))
1487
0
      return nullptr;
1488
9
    Offset -= NumSkippedElements * ElementSize;
1489
9
    Indices.push_back(IRB.getInt(NumSkippedElements));
1490
9
    return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
1491
9
                                    Offset, TargetTy, Indices, NamePrefix);
1492
9
  }
1493
50.4k
1494
50.4k
  if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
1495
8.01k
    Type *ElementTy = ArrTy->getElementType();
1496
8.01k
    APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1497
8.01k
    APInt NumSkippedElements = Offset.sdiv(ElementSize);
1498
8.01k
    if (NumSkippedElements.ugt(ArrTy->getNumElements()))
1499
0
      return nullptr;
1500
8.01k
1501
8.01k
    Offset -= NumSkippedElements * ElementSize;
1502
8.01k
    Indices.push_back(IRB.getInt(NumSkippedElements));
1503
8.01k
    return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1504
8.01k
                                    Indices, NamePrefix);
1505
8.01k
  }
1506
42.4k
1507
42.4k
  StructType *STy = dyn_cast<StructType>(Ty);
1508
42.4k
  if (!STy)
1509
336
    return nullptr;
1510
42.1k
1511
42.1k
  const StructLayout *SL = DL.getStructLayout(STy);
1512
42.1k
  uint64_t StructOffset = Offset.getZExtValue();
1513
42.1k
  if (StructOffset >= SL->getSizeInBytes())
1514
11
    return nullptr;
1515
42.1k
  unsigned Index = SL->getElementContainingOffset(StructOffset);
1516
42.1k
  Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
1517
42.1k
  Type *ElementTy = STy->getElementType(Index);
1518
42.1k
  if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
1519
1.28k
    return nullptr; // The offset points into alignment padding.
1520
40.8k
1521
40.8k
  Indices.push_back(IRB.getInt32(Index));
1522
40.8k
  return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1523
40.8k
                                  Indices, NamePrefix);
1524
40.8k
}
1525
1526
/// Get a natural GEP from a base pointer to a particular offset and
1527
/// resulting in a particular type.
1528
///
1529
/// The goal is to produce a "natural" looking GEP that works with the existing
1530
/// composite types to arrive at the appropriate offset and element type for
1531
/// a pointer. TargetTy is the element type the returned GEP should point-to if
1532
/// possible. We recurse by decreasing Offset, adding the appropriate index to
1533
/// Indices, and setting Ty to the result subtype.
1534
///
1535
/// If no natural GEP can be constructed, this function returns null.
1536
static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
1537
                                      Value *Ptr, APInt Offset, Type *TargetTy,
1538
                                      SmallVectorImpl<Value *> &Indices,
1539
846k
                                      Twine NamePrefix) {
1540
846k
  PointerType *Ty = cast<PointerType>(Ptr->getType());
1541
846k
1542
846k
  // Don't consider any GEPs through an i8* as natural unless the TargetTy is
1543
846k
  // an i8.
1544
846k
  if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && 
TargetTy->isIntegerTy(8)68.1k
)
1545
39.7k
    return nullptr;
1546
807k
1547
807k
  Type *ElementTy = Ty->getElementType();
1548
807k
  if (!ElementTy->isSized())
1549
4
    return nullptr; // We can't GEP through an unsized element.
1550
807k
  APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
1551
807k
  if (ElementSize == 0)
1552
0
    return nullptr; // Zero-length arrays can't help us build a natural GEP.
1553
807k
  APInt NumSkippedElements = Offset.sdiv(ElementSize);
1554
807k
1555
807k
  Offset -= NumSkippedElements * ElementSize;
1556
807k
  Indices.push_back(IRB.getInt(NumSkippedElements));
1557
807k
  return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
1558
807k
                                  Indices, NamePrefix);
1559
807k
}
1560
1561
/// Compute an adjusted pointer from Ptr by Offset bytes where the
1562
/// resulting pointer has PointerTy.
1563
///
1564
/// This tries very hard to compute a "natural" GEP which arrives at the offset
1565
/// and produces the pointer type desired. Where it cannot, it will try to use
1566
/// the natural GEP to arrive at the offset and bitcast to the type. Where that
1567
/// fails, it will try to use an existing i8* and GEP to the byte offset and
1568
/// bitcast to the type.
1569
///
1570
/// The strategy for finding the more natural GEPs is to peel off layers of the
1571
/// pointer, walking back through bit casts and GEPs, searching for a base
1572
/// pointer from which we can compute a natural GEP with the desired
1573
/// properties. The algorithm tries to fold as many constant indices into
1574
/// a single GEP as possible, thus making each GEP more independent of the
1575
/// surrounding code.
1576
static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
1577
815k
                             APInt Offset, Type *PointerTy, Twine NamePrefix) {
1578
815k
  // Even though we don't look through PHI nodes, we could be called on an
1579
815k
  // instruction in an unreachable block, which may be on a cycle.
1580
815k
  SmallPtrSet<Value *, 4> Visited;
1581
815k
  Visited.insert(Ptr);
1582
815k
  SmallVector<Value *, 4> Indices;
1583
815k
1584
815k
  // We may end up computing an offset pointer that has the wrong type. If we
1585
815k
  // never are able to compute one directly that has the correct type, we'll
1586
815k
  // fall back to it, so keep it and the base it was computed from around here.
1587
815k
  Value *OffsetPtr = nullptr;
1588
815k
  Value *OffsetBasePtr;
1589
815k
1590
815k
  // Remember any i8 pointer we come across to re-use if we need to do a raw
1591
815k
  // byte offset.
1592
815k
  Value *Int8Ptr = nullptr;
1593
815k
  APInt Int8PtrOffset(Offset.getBitWidth(), 0);
1594
815k
1595
815k
  PointerType *TargetPtrTy = cast<PointerType>(PointerTy);
1596
815k
  Type *TargetTy = TargetPtrTy->getElementType();
1597
815k
1598
815k
  // As `addrspacecast` is , `Ptr` (the storage pointer) may have different
1599
815k
  // address space from the expected `PointerTy` (the pointer to be used).
1600
815k
  // Adjust the pointer type based the original storage pointer.
1601
815k
  auto AS = cast<PointerType>(Ptr->getType())->getAddressSpace();
1602
815k
  PointerTy = TargetTy->getPointerTo(AS);
1603
815k
1604
846k
  do {
1605
846k
    // First fold any existing GEPs into the offset.
1606
856k
    while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
1607
11.9k
      APInt GEPOffset(Offset.getBitWidth(), 0);
1608
11.9k
      if (!GEP->accumulateConstantOffset(DL, GEPOffset))
1609
2.18k
        break;
1610
9.72k
      Offset += GEPOffset;
1611
9.72k
      Ptr = GEP->getPointerOperand();
1612
9.72k
      if (!Visited.insert(Ptr).second)
1613
0
        break;
1614
9.72k
    }
1615
846k
1616
846k
    // See if we can perform a natural GEP here.
1617
846k
    Indices.clear();
1618
846k
    if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
1619
805k
                                           Indices, NamePrefix)) {
1620
805k
      // If we have a new natural pointer at the offset, clear out any old
1621
805k
      // offset pointer we computed. Unless it is the base pointer or
1622
805k
      // a non-instruction, we built a GEP we don't need. Zap it.
1623
805k
      if (OffsetPtr && 
OffsetPtr != OffsetBasePtr27.1k
)
1624
15.1k
        if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
1625
14.9k
          assert(I->use_empty() && "Built a GEP with uses some how!");
1626
14.9k
          I->eraseFromParent();
1627
14.9k
        }
1628
805k
      OffsetPtr = P;
1629
805k
      OffsetBasePtr = Ptr;
1630
805k
      // If we also found a pointer of the right type, we're done.
1631
805k
      if (P->getType() == PointerTy)
1632
42.8k
        break;
1633
803k
    }
1634
803k
1635
803k
    // Stash this pointer if we've found an i8*.
1636
803k
    if (Ptr->getType()->isIntegerTy(8)) {
1637
0
      Int8Ptr = Ptr;
1638
0
      Int8PtrOffset = Offset;
1639
0
    }
1640
803k
1641
803k
    // Peel off a layer of the pointer and update the offset appropriately.
1642
803k
    if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
1643
30.9k
      Ptr = cast<Operator>(Ptr)->getOperand(0);
1644
773k
    } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
1645
0
      if (GA->isInterposable())
1646
0
        break;
1647
0
      Ptr = GA->getAliasee();
1648
773k
    } else {
1649
773k
      break;
1650
773k
    }
1651
30.9k
    assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
1652
30.9k
  } while (Visited.insert(Ptr).second);
1653
815k
1654
815k
  if (!OffsetPtr) {
1655
37.6k
    if (!Int8Ptr) {
1656
37.6k
      Int8Ptr = IRB.CreateBitCast(
1657
37.6k
          Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
1658
37.6k
          NamePrefix + "sroa_raw_cast");
1659
37.6k
      Int8PtrOffset = Offset;
1660
37.6k
    }
1661
37.6k
1662
37.6k
    OffsetPtr = Int8PtrOffset == 0
1663
37.6k
                    ? 
Int8Ptr36.4k
1664
37.6k
                    : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
1665
1.17k
                                            IRB.getInt(Int8PtrOffset),
1666
1.17k
                                            NamePrefix + "sroa_raw_idx");
1667
37.6k
  }
1668
815k
  Ptr = OffsetPtr;
1669
815k
1670
815k
  // On the off chance we were targeting i8*, guard the bitcast here.
1671
815k
  if (cast<PointerType>(Ptr->getType()) != TargetPtrTy) {
1672
735k
    Ptr = IRB.CreatePointerBitCastOrAddrSpaceCast(Ptr,
1673
735k
                                                  TargetPtrTy,
1674
735k
                                                  NamePrefix + "sroa_cast");
1675
735k
  }
1676
815k
1677
815k
  return Ptr;
1678
815k
}
1679
1680
/// Compute the adjusted alignment for a load or store from an offset.
1681
static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
1682
10.4k
                                     const DataLayout &DL) {
1683
10.4k
  unsigned Alignment;
1684
10.4k
  Type *Ty;
1685
10.4k
  if (auto *LI = dyn_cast<LoadInst>(I)) {
1686
4.44k
    Alignment = LI->getAlignment();
1687
4.44k
    Ty = LI->getType();
1688
5.97k
  } else if (auto *SI = dyn_cast<StoreInst>(I)) {
1689
5.97k
    Alignment = SI->getAlignment();
1690
5.97k
    Ty = SI->getValueOperand()->getType();
1691
5.97k
  } else {
1692
0
    llvm_unreachable("Only loads and stores are allowed!");
1693
0
  }
1694
10.4k
1695
10.4k
  if (!Alignment)
1696
311
    Alignment = DL.getABITypeAlignment(Ty);
1697
10.4k
1698
10.4k
  return MinAlign(Alignment, Offset);
1699
10.4k
}
1700
1701
/// Test whether we can convert a value from the old to the new type.
1702
///
1703
/// This predicate should be used to guard calls to convertValue in order to
1704
/// ensure that we only try to convert viable values. The strategy is that we
1705
/// will peel off single element struct and array wrappings to get to an
1706
/// underlying value, and convert that value.
1707
5.19M
static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
1708
5.19M
  if (OldTy == NewTy)
1709
4.06M
    return true;
1710
1.12M
1711
1.12M
  // For integer types, we can't handle any bit-width differences. This would
1712
1.12M
  // break both vector conversions with extension and introduce endianness
1713
1.12M
  // issues when in conjunction with loads and stores.
1714
1.12M
  if (isa<IntegerType>(OldTy) && 
isa<IntegerType>(NewTy)556k
) {
1715
25
    assert(cast<IntegerType>(OldTy)->getBitWidth() !=
1716
25
               cast<IntegerType>(NewTy)->getBitWidth() &&
1717
25
           "We can't have the same bitwidth for different int types");
1718
25
    return false;
1719
25
  }
1720
1.12M
1721
1.12M
  if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
1722
1.44k
    return false;
1723
1.12M
  if (!NewTy->isSingleValueType() || 
!OldTy->isSingleValueType()1.12M
)
1724
8.44k
    return false;
1725
1.11M
1726
1.11M
  // We can convert pointers to integers and vice-versa. Same for vectors
1727
1.11M
  // of pointers and integers.
1728
1.11M
  OldTy = OldTy->getScalarType();
1729
1.11M
  NewTy = NewTy->getScalarType();
1730
1.11M
  if (NewTy->isPointerTy() || 
OldTy->isPointerTy()644k
) {
1731
938k
    if (NewTy->isPointerTy() && 
OldTy->isPointerTy()472k
) {
1732
2.84k
      return cast<PointerType>(NewTy)->getPointerAddressSpace() ==
1733
2.84k
        cast<PointerType>(OldTy)->getPointerAddressSpace();
1734
2.84k
    }
1735
935k
1736
935k
    // We can convert integers to integral pointers, but not to non-integral
1737
935k
    // pointers.
1738
935k
    if (OldTy->isIntegerTy())
1739
469k
      return !DL.isNonIntegralPointerType(NewTy);
1740
466k
1741
466k
    // We can convert integral pointers to integers, but non-integral pointers
1742
466k
    // need to remain pointers.
1743
466k
    if (!DL.isNonIntegralPointerType(OldTy))
1744
466k
      return NewTy->isIntegerTy();
1745
6
1746
6
    return false;
1747
6
  }
1748
178k
1749
178k
  return true;
1750
178k
}
1751
1752
/// Generic routine to convert an SSA value to a value of a different
1753
/// type.
1754
///
1755
/// This will try various different casting techniques, such as bitcasts,
1756
/// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
1757
/// two types for viability with this routine.
1758
static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
1759
3.88M
                           Type *NewTy) {
1760
3.88M
  Type *OldTy = V->getType();
1761
3.88M
  assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
1762
3.88M
1763
3.88M
  if (OldTy == NewTy)
1764
3.83M
    return V;
1765
43.0k
1766
43.0k
  assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
1767
43.0k
         "Integer types must be the exact same to convert.");
1768
43.0k
1769
43.0k
  // See if we need inttoptr for this type pair. A cast involving both scalars
1770
43.0k
  // and vectors requires and additional bitcast.
1771
43.0k
  if (OldTy->isIntOrIntVectorTy() && 
NewTy->isPtrOrPtrVectorTy()20.5k
) {
1772
14.6k
    // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
1773
14.6k
    if (OldTy->isVectorTy() && 
!NewTy->isVectorTy()2
)
1774
0
      return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1775
0
                                NewTy);
1776
14.6k
1777
14.6k
    // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
1778
14.6k
    if (!OldTy->isVectorTy() && 
NewTy->isVectorTy()14.6k
)
1779
0
      return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
1780
0
                                NewTy);
1781
14.6k
1782
14.6k
    return IRB.CreateIntToPtr(V, NewTy);
1783
14.6k
  }
1784
28.3k
1785
28.3k
  // See if we need ptrtoint for this type pair. A cast involving both scalars
1786
28.3k
  // and vectors requires and additional bitcast.
1787
28.3k
  if (OldTy->isPtrOrPtrVectorTy() && 
NewTy->isIntOrIntVectorTy()14.7k
) {
1788
13.3k
    // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
1789
13.3k
    if (OldTy->isVectorTy() && 
!NewTy->isVectorTy()4
)
1790
2
      return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1791
2
                               NewTy);
1792
13.3k
1793
13.3k
    // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
1794
13.3k
    if (!OldTy->isVectorTy() && 
NewTy->isVectorTy()13.3k
)
1795
0
      return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
1796
0
                               NewTy);
1797
13.3k
1798
13.3k
    return IRB.CreatePtrToInt(V, NewTy);
1799
13.3k
  }
1800
14.9k
1801
14.9k
  return IRB.CreateBitCast(V, NewTy);
1802
14.9k
}
1803
1804
/// Test whether the given slice use can be promoted to a vector.
1805
///
1806
/// This function is called to test each entry in a partition which is slated
1807
/// for a single slice.
1808
static bool isVectorPromotionViableForSlice(Partition &P, const Slice &S,
1809
                                            VectorType *Ty,
1810
                                            uint64_t ElementSize,
1811
123k
                                            const DataLayout &DL) {
1812
123k
  // First validate the slice offsets.
1813
123k
  uint64_t BeginOffset =
1814
123k
      std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
1815
123k
  uint64_t BeginIndex = BeginOffset / ElementSize;
1816
123k
  if (BeginIndex * ElementSize != BeginOffset ||
1817
123k
      BeginIndex >= Ty->getNumElements())
1818
0
    return false;
1819
123k
  uint64_t EndOffset =
1820
123k
      std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
1821
123k
  uint64_t EndIndex = EndOffset / ElementSize;
1822
123k
  if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
1823
0
    return false;
1824
123k
1825
123k
  assert(EndIndex > BeginIndex && "Empty vector!");
1826
123k
  uint64_t NumElements = EndIndex - BeginIndex;
1827
123k
  Type *SliceTy = (NumElements == 1)
1828
123k
                      ? 
Ty->getElementType()12.1k
1829
123k
                      : 
VectorType::get(Ty->getElementType(), NumElements)110k
;
1830
123k
1831
123k
  Type *SplitIntTy =
1832
123k
      Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
1833
123k
1834
123k
  Use *U = S.getUse();
1835
123k
1836
123k
  if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
1837
1.55k
    if (MI->isVolatile())
1838
0
      return false;
1839
1.55k
    if (!S.isSplittable())
1840
2
      return false; // Skip any unsplittable intrinsics.
1841
121k
  } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
1842
39.4k
    if (!II->isLifetimeStartOrEnd())
1843
0
      return false;
1844
82.0k
  } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
1845
0
    // Disable vector promotion when there are loads or stores of an FCA.
1846
0
    return false;
1847
82.0k
  } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
1848
44.7k
    if (LI->isVolatile())
1849
0
      return false;
1850
44.7k
    Type *LTy = LI->getType();
1851
44.7k
    if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1852
4
      assert(LTy->isIntegerTy());
1853
4
      LTy = SplitIntTy;
1854
4
    }
1855
44.7k
    if (!canConvertValue(DL, SliceTy, LTy))
1856
1
      return false;
1857
37.3k
  } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
1858
37.2k
    if (SI->isVolatile())
1859
0
      return false;
1860
37.2k
    Type *STy = SI->getValueOperand()->getType();
1861
37.2k
    if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
1862
3
      assert(STy->isIntegerTy());
1863
3
      STy = SplitIntTy;
1864
3
    }
1865
37.2k
    if (!canConvertValue(DL, STy, SliceTy))
1866
0
      return false;
1867
4
  } else {
1868
4
    return false;
1869
4
  }
1870
123k
1871
123k
  return true;
1872
123k
}
1873
1874
/// Test whether the given alloca partitioning and range of slices can be
1875
/// promoted to a vector.
1876
///
1877
/// This is a quick test to check whether we can rewrite a particular alloca
1878
/// partition (and its newly formed alloca) into a vector alloca with only
1879
/// whole-vector loads and stores such that it could be promoted to a vector
1880
/// SSA value. We only can ensure this for a limited set of operations, and we
1881
/// don't want to do the rewrites unless we are confident that the result will
1882
/// be promotable, so we have an early test here.
1883
103k
static VectorType *isVectorPromotionViable(Partition &P, const DataLayout &DL) {
1884
103k
  // Collect the candidate types for vector-based promotion. Also track whether
1885
103k
  // we have different element types.
1886
103k
  SmallVector<VectorType *, 4> CandidateTys;
1887
103k
  Type *CommonEltTy = nullptr;
1888
103k
  bool HaveCommonEltTy = true;
1889
216k
  auto CheckCandidateType = [&](Type *Ty) {
1890
216k
    if (auto *VTy = dyn_cast<VectorType>(Ty)) {
1891
81.3k
      CandidateTys.push_back(VTy);
1892
81.3k
      if (!CommonEltTy)
1893
32.2k
        CommonEltTy = VTy->getElementType();
1894
49.0k
      else if (CommonEltTy != VTy->getElementType())
1895
15
        HaveCommonEltTy = false;
1896
81.3k
    }
1897
216k
  };
1898
103k
  // Consider any loads or stores that are the exact size of the slice.
1899
103k
  for (const Slice &S : P)
1900
331k
    if (S.beginOffset() == P.beginOffset() &&
1901
331k
        
S.endOffset() == P.endOffset()330k
) {
1902
284k
      if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
1903
109k
        CheckCandidateType(LI->getType());
1904
175k
      else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
1905
107k
        CheckCandidateType(SI->getValueOperand()->getType());
1906
284k
    }
1907
103k
1908
103k
  // If we didn't find a vector type, nothing to do here.
1909
103k
  if (CandidateTys.empty())
1910
71.5k
    return nullptr;
1911
32.2k
1912
32.2k
  // Remove non-integer vector types if we had multiple common element types.
1913
32.2k
  // FIXME: It'd be nice to replace them with integer vector types, but we can't
1914
32.2k
  // do that until all the backends are known to produce good code for all
1915
32.2k
  // integer vector types.
1916
32.2k
  if (!HaveCommonEltTy) {
1917
15
    CandidateTys.erase(
1918
15
        llvm::remove_if(CandidateTys,
1919
30
                        [](VectorType *VTy) {
1920
30
                          return !VTy->getElementType()->isIntegerTy();
1921
30
                        }),
1922
15
        CandidateTys.end());
1923
15
1924
15
    // If there were no integer vector types, give up.
1925
15
    if (CandidateTys.empty())
1926
0
      return nullptr;
1927
15
1928
15
    // Rank the remaining candidate vector types. This is easy because we know
1929
15
    // they're all integer vectors. We sort by ascending number of elements.
1930
15
    auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
1931
10
      (void)DL;
1932
10
      assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
1933
10
             "Cannot have vector types of different sizes!");
1934
10
      assert(RHSTy->getElementType()->isIntegerTy() &&
1935
10
             "All non-integer types eliminated!");
1936
10
      assert(LHSTy->getElementType()->isIntegerTy() &&
1937
10
             "All non-integer types eliminated!");
1938
10
      return RHSTy->getNumElements() < LHSTy->getNumElements();
1939
10
    };
1940
15
    llvm::sort(CandidateTys, RankVectorTypes);
1941
15
    CandidateTys.erase(
1942
15
        std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
1943
15
        CandidateTys.end());
1944
32.2k
  } else {
1945
32.2k
// The only way to have the same element type in every vector type is to
1946
32.2k
// have the same vector type. Check that and remove all but one.
1947
#ifndef NDEBUG
1948
    for (VectorType *VTy : CandidateTys) {
1949
      assert(VTy->getElementType() == CommonEltTy &&
1950
             "Unaccounted for element type!");
1951
      assert(VTy == CandidateTys[0] &&
1952
             "Different vector types with the same element type!");
1953
    }
1954
#endif
1955
    CandidateTys.resize(1);
1956
32.2k
  }
1957
32.2k
1958
32.2k
  // Try each vector type, and return the one which works.
1959
32.2k
  auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
1960
32.2k
    uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
1961
32.2k
1962
32.2k
    // While the definition of LLVM vectors is bitpacked, we don't support sizes
1963
32.2k
    // that aren't byte sized.
1964
32.2k
    if (ElementSize % 8)
1965
0
      return false;
1966
32.2k
    assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
1967
32.2k
           "vector size not a multiple of element size?");
1968
32.2k
    ElementSize /= 8;
1969
32.2k
1970
32.2k
    for (const Slice &S : P)
1971
117k
      if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
1972
7
        return false;
1973
32.2k
1974
32.2k
    
for (const Slice *S : P.splitSliceTails())32.2k
1975
5.19k
      if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
1976
0
        return false;
1977
32.2k
1978
32.2k
    return true;
1979
32.2k
  };
1980
32.2k
  for (VectorType *VTy : CandidateTys)
1981
32.2k
    if (CheckVectorTypeForPromotion(VTy))
1982
32.2k
      return VTy;
1983
32.2k
1984
32.2k
  
return nullptr7
;
1985
32.2k
}
1986
1987
/// Test whether a slice of an alloca is valid for integer widening.
1988
///
1989
/// This implements the necessary checking for the \c isIntegerWideningViable
1990
/// test below on a single slice of the alloca.
1991
static bool isIntegerWideningViableForSlice(const Slice &S,
1992
                                            uint64_t AllocBeginOffset,
1993
                                            Type *AllocaTy,
1994
                                            const DataLayout &DL,
1995
3.79M
                                            bool &WholeAllocaOp) {
1996
3.79M
  uint64_t Size = DL.getTypeStoreSize(AllocaTy);
1997
3.79M
1998
3.79M
  uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
1999
3.79M
  uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
2000
3.79M
2001
3.79M
  // We can't reasonably handle cases where the load or store extends past
2002
3.79M
  // the end of the alloca's type and into its padding.
2003
3.79M
  if (RelEnd > Size)
2004
50.8k
    return false;
2005
3.74M
2006
3.74M
  Use *U = S.getUse();
2007
3.74M
2008
3.74M
  if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
2009
1.86M
    if (LI->isVolatile())
2010
4
      return false;
2011
1.86M
    // We can't handle loads that extend past the allocated memory.
2012
1.86M
    if (DL.getTypeStoreSize(LI->getType()) > Size)
2013
1.37k
      return false;
2014
1.86M
    // So far, AllocaSliceRewriter does not support widening split slice tails
2015
1.86M
    // in rewriteIntegerLoad.
2016
1.86M
    if (S.beginOffset() < AllocBeginOffset)
2017
1
      return false;
2018
1.86M
    // Note that we don't count vector loads or stores as whole-alloca
2019
1.86M
    // operations which enable integer widening because we would prefer to use
2020
1.86M
    // vector widening instead.
2021
1.86M
    if (!isa<VectorType>(LI->getType()) && 
RelBegin == 01.81M
&&
RelEnd == Size1.81M
)
2022
1.81M
      WholeAllocaOp = true;
2023
1.86M
    if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
2024
843k
      if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
2025
10
        return false;
2026
1.01M
    } else if (RelBegin != 0 || 
RelEnd != Size1.01M
||
2027
1.01M
               
!canConvertValue(DL, AllocaTy, LI->getType())1.01M
) {
2028
84
      // Non-integer loads need to be convertible from the alloca type so that
2029
84
      // they are promotable.
2030
84
      return false;
2031
84
    }
2032
1.88M
  } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
2033
1.20M
    Type *ValueTy = SI->getValueOperand()->getType();
2034
1.20M
    if (SI->isVolatile())
2035
363
      return false;
2036
1.20M
    // We can't handle stores that extend past the allocated memory.
2037
1.20M
    if (DL.getTypeStoreSize(ValueTy) > Size)
2038
1.49k
      return false;
2039
1.20M
    // So far, AllocaSliceRewriter does not support widening split slice tails
2040
1.20M
    // in rewriteIntegerStore.
2041
1.20M
    if (S.beginOffset() < AllocBeginOffset)
2042
1
      return false;
2043
1.20M
    // Note that we don't count vector loads or stores as whole-alloca
2044
1.20M
    // operations which enable integer widening because we would prefer to use
2045
1.20M
    // vector widening instead.
2046
1.20M
    if (!isa<VectorType>(ValueTy) && 
RelBegin == 01.16M
&&
RelEnd == Size1.16M
)
2047
1.16M
      WholeAllocaOp = true;
2048
1.20M
    if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
2049
601k
      if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
2050
4
        return false;
2051
604k
    } else if (RelBegin != 0 || 
RelEnd != Size604k
||
2052
604k
               
!canConvertValue(DL, ValueTy, AllocaTy)603k
) {
2053
70
      // Non-integer stores need to be convertible to the alloca type so that
2054
70
      // they are promotable.
2055
70
      return false;
2056
70
    }
2057
673k
  } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
2058
13.5k
    if (MI->isVolatile() || 
!isa<Constant>(MI->getLength())13.5k
)
2059
16
      return false;
2060
13.5k
    if (!S.isSplittable())
2061
2
      return false; // Skip any unsplittable intrinsics.
2062
659k
  } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
2063
657k
    if (!II->isLifetimeStartOrEnd())
2064
0
      return false;
2065
2.03k
  } else {
2066
2.03k
    return false;
2067
2.03k
  }
2068
3.73M
2069
3.73M
  return true;
2070
3.73M
}
2071
2072
/// Test whether the given alloca partition's integer operations can be
2073
/// widened to promotable ones.
2074
///
2075
/// This is a quick test to check whether we can rewrite the integer loads and
2076
/// stores to a particular alloca into wider loads and stores and be able to
2077
/// promote the resulting alloca.
2078
static bool isIntegerWideningViable(Partition &P, Type *AllocaTy,
2079
938k
                                    const DataLayout &DL) {
2080
938k
  uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
2081
938k
  // Don't create integer types larger than the maximum bitwidth.
2082
938k
  if (SizeInBits > IntegerType::MAX_INT_BITS)
2083
3
    return false;
2084
938k
2085
938k
  // Don't try to handle allocas with bit-padding.
2086
938k
  if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
2087
4.30k
    return false;
2088
934k
2089
934k
  // We need to ensure that an integer type with the appropriate bitwidth can
2090
934k
  // be converted to the alloca type, whatever that is. We don't want to force
2091
934k
  // the alloca itself to have an integer type if there is a more suitable one.
2092
934k
  Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
2093
934k
  if (!canConvertValue(DL, AllocaTy, IntTy) ||
2094
934k
      
!canConvertValue(DL, IntTy, AllocaTy)926k
)
2095
7.71k
    return false;
2096
926k
2097
926k
  // While examining uses, we ensure that the alloca has a covering load or
2098
926k
  // store. We don't want to widen the integer operations only to fail to
2099
926k
  // promote due to some other unsplittable entry (which we may make splittable
2100
926k
  // later). However, if there are only splittable uses, go ahead and assume
2101
926k
  // that we cover the alloca.
2102
926k
  // FIXME: We shouldn't consider split slices that happen to start in the
2103
926k
  // partition here...
2104
926k
  bool WholeAllocaOp =
2105
926k
      P.begin() != P.end() ? 
false924k
:
DL.isLegalInteger(SizeInBits)1.38k
;
2106
926k
2107
926k
  for (const Slice &S : P)
2108
3.72M
    if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
2109
3.72M
                                         WholeAllocaOp))
2110
22.5k
      return false;
2111
926k
2112
926k
  
for (const Slice *S : P.splitSliceTails())903k
2113
69.0k
    if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
2114
69.0k
                                         WholeAllocaOp))
2115
33.6k
      return false;
2116
903k
2117
903k
  
return WholeAllocaOp870k
;
2118
903k
}
2119
2120
static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
2121
                             IntegerType *Ty, uint64_t Offset,
2122
4.81k
                             const Twine &Name) {
2123
4.81k
  LLVM_DEBUG(dbgs() << "       start: " << *V << "\n");
2124
4.81k
  IntegerType *IntTy = cast<IntegerType>(V->getType());
2125
4.81k
  assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2126
4.81k
         "Element extends past full value");
2127
4.81k
  uint64_t ShAmt = 8 * Offset;
2128
4.81k
  if (DL.isBigEndian())
2129
16
    ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2130
4.81k
  if (ShAmt) {
2131
2.47k
    V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
2132
2.47k
    LLVM_DEBUG(dbgs() << "     shifted: " << *V << "\n");
2133
2.47k
  }
2134
4.81k
  assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2135
4.81k
         "Cannot extract to a larger integer!");
2136
4.81k
  if (Ty != IntTy) {
2137
4.81k
    V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
2138
4.81k
    LLVM_DEBUG(dbgs() << "     trunced: " << *V << "\n");
2139
4.81k
  }
2140
4.81k
  return V;
2141
4.81k
}
2142
2143
static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
2144
6.31k
                            Value *V, uint64_t Offset, const Twine &Name) {
2145
6.31k
  IntegerType *IntTy = cast<IntegerType>(Old->getType());
2146
6.31k
  IntegerType *Ty = cast<IntegerType>(V->getType());
2147
6.31k
  assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
2148
6.31k
         "Cannot insert a larger integer!");
2149
6.31k
  LLVM_DEBUG(dbgs() << "       start: " << *V << "\n");
2150
6.31k
  if (Ty != IntTy) {
2151
4.51k
    V = IRB.CreateZExt(V, IntTy, Name + ".ext");
2152
4.51k
    LLVM_DEBUG(dbgs() << "    extended: " << *V << "\n");
2153
4.51k
  }
2154
6.31k
  assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
2155
6.31k
         "Element store outside of alloca store");
2156
6.31k
  uint64_t ShAmt = 8 * Offset;
2157
6.31k
  if (DL.isBigEndian())
2158
14
    ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
2159
6.31k
  if (ShAmt) {
2160
2.23k
    V = IRB.CreateShl(V, ShAmt, Name + ".shift");
2161
2.23k
    LLVM_DEBUG(dbgs() << "     shifted: " << *V << "\n");
2162
2.23k
  }
2163
6.31k
2164
6.31k
  if (ShAmt || 
Ty->getBitWidth() < IntTy->getBitWidth()4.07k
) {
2165
4.51k
    APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
2166
4.51k
    Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
2167
4.51k
    LLVM_DEBUG(dbgs() << "      masked: " << *Old << "\n");
2168
4.51k
    V = IRB.CreateOr(Old, V, Name + ".insert");
2169
4.51k
    LLVM_DEBUG(dbgs() << "    inserted: " << *V << "\n");
2170
4.51k
  }
2171
6.31k
  return V;
2172
6.31k
}
2173
2174
static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
2175
44.7k
                            unsigned EndIndex, const Twine &Name) {
2176
44.7k
  VectorType *VecTy = cast<VectorType>(V->getType());
2177
44.7k
  unsigned NumElements = EndIndex - BeginIndex;
2178
44.7k
  assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2179
44.7k
2180
44.7k
  if (NumElements == VecTy->getNumElements())
2181
44.3k
    return V;
2182
428
2183
428
  if (NumElements == 1) {
2184
409
    V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
2185
409
                                 Name + ".extract");
2186
409
    LLVM_DEBUG(dbgs() << "     extract: " << *V << "\n");
2187
409
    return V;
2188
409
  }
2189
19
2190
19
  SmallVector<Constant *, 8> Mask;
2191
19
  Mask.reserve(NumElements);
2192
59
  for (unsigned i = BeginIndex; i != EndIndex; 
++i40
)
2193
40
    Mask.push_back(IRB.getInt32(i));
2194
19
  V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2195
19
                              ConstantVector::get(Mask), Name + ".extract");
2196
19
  LLVM_DEBUG(dbgs() << "     shuffle: " << *V << "\n");
2197
19
  return V;
2198
19
}
2199
2200
static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
2201
342
                           unsigned BeginIndex, const Twine &Name) {
2202
342
  VectorType *VecTy = cast<VectorType>(Old->getType());
2203
342
  assert(VecTy && "Can only insert a vector into a vector");
2204
342
2205
342
  VectorType *Ty = dyn_cast<VectorType>(V->getType());
2206
342
  if (!Ty) {
2207
306
    // Single element to insert.
2208
306
    V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
2209
306
                                Name + ".insert");
2210
306
    LLVM_DEBUG(dbgs() << "     insert: " << *V << "\n");
2211
306
    return V;
2212
306
  }
2213
36
2214
36
  assert(Ty->getNumElements() <= VecTy->getNumElements() &&
2215
36
         "Too many elements!");
2216
36
  if (Ty->getNumElements() == VecTy->getNumElements()) {
2217
13
    assert(V->getType() == VecTy && "Vector type mismatch");
2218
13
    return V;
2219
13
  }
2220
23
  unsigned EndIndex = BeginIndex + Ty->getNumElements();
2221
23
2222
23
  // When inserting a smaller vector into the larger to store, we first
2223
23
  // use a shuffle vector to widen it with undef elements, and then
2224
23
  // a second shuffle vector to select between the loaded vector and the
2225
23
  // incoming vector.
2226
23
  SmallVector<Constant *, 8> Mask;
2227
23
  Mask.reserve(VecTy->getNumElements());
2228
115
  for (unsigned i = 0; i != VecTy->getNumElements(); 
++i92
)
2229
92
    if (i >= BeginIndex && 
i < EndIndex69
)
2230
47
      Mask.push_back(IRB.getInt32(i - BeginIndex));
2231
45
    else
2232
45
      Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
2233
23
  V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
2234
23
                              ConstantVector::get(Mask), Name + ".expand");
2235
23
  LLVM_DEBUG(dbgs() << "    shuffle: " << *V << "\n");
2236
23
2237
23
  Mask.clear();
2238
115
  for (unsigned i = 0; i != VecTy->getNumElements(); 
++i92
)
2239
92
    Mask.push_back(IRB.getInt1(i >= BeginIndex && 
i < EndIndex69
));
2240
23
2241
23
  V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
2242
23
2243
23
  LLVM_DEBUG(dbgs() << "    blend: " << *V << "\n");
2244
23
  return V;
2245
23
}
2246
2247
/// Visitor to rewrite instructions using p particular slice of an alloca
2248
/// to use a new alloca.
2249
///
2250
/// Also implements the rewriting to vector-based accesses when the partition
2251
/// passes the isVectorPromotionViable predicate. Most of the rewriting logic
2252
/// lives here.
2253
class llvm::sroa::AllocaSliceRewriter
2254
    : public InstVisitor<AllocaSliceRewriter, bool> {
2255
  // Befriend the base class so it can delegate to private visit methods.
2256
  friend class InstVisitor<AllocaSliceRewriter, bool>;
2257
2258
  using Base = InstVisitor<AllocaSliceRewriter, bool>;
2259
2260
  const DataLayout &DL;
2261
  AllocaSlices &AS;
2262
  SROA &Pass;
2263
  AllocaInst &OldAI, &NewAI;
2264
  const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
2265
  Type *NewAllocaTy;
2266
2267
  // This is a convenience and flag variable that will be null unless the new
2268
  // alloca's integer operations should be widened to this integer type due to
2269
  // passing isIntegerWideningViable above. If it is non-null, the desired
2270
  // integer type will be stored here for easy access during rewriting.
2271
  IntegerType *IntTy;
2272
2273
  // If we are rewriting an alloca partition which can be written as pure
2274
  // vector operations, we stash extra information here. When VecTy is
2275
  // non-null, we have some strict guarantees about the rewritten alloca:
2276
  //   - The new alloca is exactly the size of the vector type here.
2277
  //   - The accesses all either map to the entire vector or to a single
2278
  //     element.
2279
  //   - The set of accessing instructions is only one of those handled above
2280
  //     in isVectorPromotionViable. Generally these are the same access kinds
2281
  //     which are promotable via mem2reg.
2282
  VectorType *VecTy;
2283
  Type *ElementTy;
2284
  uint64_t ElementSize;
2285
2286
  // The original offset of the slice currently being rewritten relative to
2287
  // the original alloca.
2288
  uint64_t BeginOffset = 0;
2289
  uint64_t EndOffset = 0;
2290
2291
  // The new offsets of the slice currently being rewritten relative to the
2292
  // original alloca.
2293
  uint64_t NewBeginOffset, NewEndOffset;
2294
2295
  uint64_t SliceSize;
2296
  bool IsSplittable = false;
2297
  bool IsSplit = false;
2298
  Use *OldUse = nullptr;
2299
  Instruction *OldPtr = nullptr;
2300
2301
  // Track post-rewrite users which are PHI nodes and Selects.
2302
  SmallSetVector<PHINode *, 8> &PHIUsers;
2303
  SmallSetVector<SelectInst *, 8> &SelectUsers;
2304
2305
  // Utility IR builder, whose name prefix is setup for each visited use, and
2306
  // the insertion point is set to point to the user.
2307
  IRBuilderTy IRB;
2308
2309
public:
2310
  AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
2311
                      AllocaInst &OldAI, AllocaInst &NewAI,
2312
                      uint64_t NewAllocaBeginOffset,
2313
                      uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
2314
                      VectorType *PromotableVecTy,
2315
                      SmallSetVector<PHINode *, 8> &PHIUsers,
2316
                      SmallSetVector<SelectInst *, 8> &SelectUsers)
2317
      : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
2318
        NewAllocaBeginOffset(NewAllocaBeginOffset),
2319
        NewAllocaEndOffset(NewAllocaEndOffset),
2320
        NewAllocaTy(NewAI.getAllocatedType()),
2321
        IntTy(IsIntegerPromotable
2322
                  ? Type::getIntNTy(
2323
                        NewAI.getContext(),
2324
                        DL.getTypeSizeInBits(NewAI.getAllocatedType()))
2325
                  : nullptr),
2326
        VecTy(PromotableVecTy),
2327
        ElementTy(VecTy ? VecTy->getElementType() : nullptr),
2328
        ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
2329
        PHIUsers(PHIUsers), SelectUsers(SelectUsers),
2330
938k
        IRB(NewAI.getContext(), ConstantFolder()) {
2331
938k
    if (VecTy) {
2332
32.2k
      assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
2333
32.2k
             "Only multiple-of-8 sized vector elements are viable");
2334
32.2k
      ++NumVectorized;
2335
32.2k
    }
2336
938k
    assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
2337
938k
  }
2338
2339
3.91M
  bool visit(AllocaSlices::const_iterator I) {
2340
3.91M
    bool CanSROA = true;
2341
3.91M
    BeginOffset = I->beginOffset();
2342
3.91M
    EndOffset = I->endOffset();
2343
3.91M
    IsSplittable = I->isSplittable();
2344
3.91M
    IsSplit =
2345
3.91M
        BeginOffset < NewAllocaBeginOffset || 
EndOffset > NewAllocaEndOffset3.79M
;
2346
3.91M
    LLVM_DEBUG(dbgs() << "  rewriting " << (IsSplit ? "split " : ""));
2347
3.91M
    LLVM_DEBUG(AS.printSlice(dbgs(), I, ""));
2348
3.91M
    LLVM_DEBUG(dbgs() << "\n");
2349
3.91M
2350
3.91M
    // Compute the intersecting offset range.
2351
3.91M
    assert(BeginOffset < NewAllocaEndOffset);
2352
3.91M
    assert(EndOffset > NewAllocaBeginOffset);
2353
3.91M
    NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
2354
3.91M
    NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
2355
3.91M
2356
3.91M
    SliceSize = NewEndOffset - NewBeginOffset;
2357
3.91M
2358
3.91M
    OldUse = I->getUse();
2359
3.91M
    OldPtr = cast<Instruction>(OldUse->get());
2360
3.91M
2361
3.91M
    Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
2362
3.91M
    IRB.SetInsertPoint(OldUserI);
2363
3.91M
    IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
2364
3.91M
    IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
2365
3.91M
2366
3.91M
    CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
2367
3.91M
    if (VecTy || 
IntTy3.79M
)
2368
3.91M
      assert(CanSROA);
2369
3.91M
    return CanSROA;
2370
3.91M
  }
2371
2372
private:
2373
  // Make sure the other visit overloads are visible.
2374
  using Base::visit;
2375
2376
  // Every instruction which can end up as a user must have a rewrite rule.
2377
0
  bool visitInstruction(Instruction &I) {
2378
0
    LLVM_DEBUG(dbgs() << "    !!!! Cannot rewrite: " << I << "\n");
2379
0
    llvm_unreachable("No rewrite rule for this instruction!");
2380
0
  }
2381
2382
782k
  Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
2383
782k
    // Note that the offset computation can use BeginOffset or NewBeginOffset
2384
782k
    // interchangeably for unsplit slices.
2385
782k
    assert(IsSplit || BeginOffset == NewBeginOffset);
2386
782k
    uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2387
782k
2388
#ifndef NDEBUG
2389
    StringRef OldName = OldPtr->getName();
2390
    // Skip through the last '.sroa.' component of the name.
2391
    size_t LastSROAPrefix = OldName.rfind(".sroa.");
2392
    if (LastSROAPrefix != StringRef::npos) {
2393
      OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
2394
      // Look for an SROA slice index.
2395
      size_t IndexEnd = OldName.find_first_not_of("0123456789");
2396
      if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
2397
        // Strip the index and look for the offset.
2398
        OldName = OldName.substr(IndexEnd + 1);
2399
        size_t OffsetEnd = OldName.find_first_not_of("0123456789");
2400
        if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
2401
          // Strip the offset.
2402
          OldName = OldName.substr(OffsetEnd + 1);
2403
      }
2404
    }
2405
    // Strip any SROA suffixes as well.
2406
    OldName = OldName.substr(0, OldName.find(".sroa_"));
2407
#endif
2408
2409
782k
    return getAdjustedPtr(IRB, DL, &NewAI,
2410
782k
                          APInt(DL.getIndexTypeSizeInBits(PointerTy), Offset),
2411
782k
                          PointerTy,
2412
#ifndef NDEBUG
2413
                          Twine(OldName) + "."
2414
#else
2415
                          Twine()
2416
782k
#endif
2417
782k
                          );
2418
782k
  }
2419
2420
  /// Compute suitable alignment to access this slice of the *new*
2421
  /// alloca.
2422
  ///
2423
  /// You can optionally pass a type to this routine and if that type's ABI
2424
  /// alignment is itself suitable, this will return zero.
2425
47.9k
  unsigned getSliceAlign(Type *Ty = nullptr) {
2426
47.9k
    unsigned NewAIAlign = NewAI.getAlignment();
2427
47.9k
    if (!NewAIAlign)
2428
36.8k
      NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
2429
47.9k
    unsigned Align =
2430
47.9k
        MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
2431
47.9k
    return (Ty && 
Align == DL.getABITypeAlignment(Ty)1.63k
) ?
0350
:
Align47.5k
;
2432
47.9k
  }
2433
2434
93.3k
  unsigned getIndex(uint64_t Offset) {
2435
93.3k
    assert(VecTy && "Can only call getIndex when rewriting a vector");
2436
93.3k
    uint64_t RelOffset = Offset - NewAllocaBeginOffset;
2437
93.3k
    assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
2438
93.3k
    uint32_t Index = RelOffset / ElementSize;
2439
93.3k
    assert(Index * ElementSize == RelOffset);
2440
93.3k
    return Index;
2441
93.3k
  }
2442
2443
2.49M
  void deleteIfTriviallyDead(Value *V) {
2444
2.49M
    Instruction *I = cast<Instruction>(V);
2445
2.49M
    if (isInstructionTriviallyDead(I))
2446
482
      Pass.DeadInsts.insert(I);
2447
2.49M
  }
2448
2449
44.7k
  Value *rewriteVectorizedLoadInst() {
2450
44.7k
    unsigned BeginIndex = getIndex(NewBeginOffset);
2451
44.7k
    unsigned EndIndex = getIndex(NewEndOffset);
2452
44.7k
    assert(EndIndex > BeginIndex && "Empty vector!");
2453
44.7k
2454
44.7k
    Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2455
44.7k
                                     NewAI.getAlignment(), "load");
2456
44.7k
    return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
2457
44.7k
  }
2458
2459
817k
  Value *rewriteIntegerLoad(LoadInst &LI) {
2460
817k
    assert(IntTy && "We cannot insert an integer to the alloca");
2461
817k
    assert(!LI.isVolatile());
2462
817k
    Value *V = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2463
817k
                                     NewAI.getAlignment(), "load");
2464
817k
    V = convertValue(DL, IRB, V, IntTy);
2465
817k
    assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2466
817k
    uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2467
817k
    if (Offset > 0 || 
NewEndOffset < NewAllocaEndOffset817k
) {
2468
505
      IntegerType *ExtractTy = Type::getIntNTy(LI.getContext(), SliceSize * 8);
2469
505
      V = extractInteger(DL, IRB, V, ExtractTy, Offset, "extract");
2470
505
    }
2471
817k
    // It is possible that the extracted type is not the load type. This
2472
817k
    // happens if there is a load past the end of the alloca, and as
2473
817k
    // a consequence the slice is narrower but still a candidate for integer
2474
817k
    // lowering. To handle this case, we just zero extend the extracted
2475
817k
    // integer.
2476
817k
    assert(cast<IntegerType>(LI.getType())->getBitWidth() >= SliceSize * 8 &&
2477
817k
           "Can only handle an extract for an overly wide load");
2478
817k
    if (cast<IntegerType>(LI.getType())->getBitWidth() > SliceSize * 8)
2479
0
      V = IRB.CreateZExt(V, LI.getType());
2480
817k
    return V;
2481
817k
  }
2482
2483
1.87M
  bool visitLoadInst(LoadInst &LI) {
2484
1.87M
    LLVM_DEBUG(dbgs() << "    original: " << LI << "\n");
2485
1.87M
    Value *OldOp = LI.getOperand(0);
2486
1.87M
    assert(OldOp == OldPtr);
2487
1.87M
2488
1.87M
    AAMDNodes AATags;
2489
1.87M
    LI.getAAMetadata(AATags);
2490
1.87M
2491
1.87M
    unsigned AS = LI.getPointerAddressSpace();
2492
1.87M
2493
1.87M
    Type *TargetTy = IsSplit ? 
Type::getIntNTy(LI.getContext(), SliceSize * 8)4.37k
2494
1.87M
                             : 
LI.getType()1.87M
;
2495
1.87M
    const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
2496
1.87M
    bool IsPtrAdjusted = false;
2497
1.87M
    Value *V;
2498
1.87M
    if (VecTy) {
2499
44.7k
      V = rewriteVectorizedLoadInst();
2500
1.82M
    } else if (IntTy && 
LI.getType()->isIntegerTy()1.76M
) {
2501
817k
      V = rewriteIntegerLoad(LI);
2502
1.01M
    } else if (NewBeginOffset == NewAllocaBeginOffset &&
2503
1.01M
               
NewEndOffset == NewAllocaEndOffset1.01M
&&
2504
1.01M
               
(1.01M
canConvertValue(DL, NewAllocaTy, TargetTy)1.01M
||
2505
1.01M
                
(342
IsLoadPastEnd342
&&
NewAllocaTy->isIntegerTy()16
&&
2506
1.01M
                 
TargetTy->isIntegerTy()12
))) {
2507
1.01M
      LoadInst *NewLI = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2508
1.01M
                                              NewAI.getAlignment(),
2509
1.01M
                                              LI.isVolatile(), LI.getName());
2510
1.01M
      if (AATags)
2511
775k
        NewLI->setAAMetadata(AATags);
2512
1.01M
      if (LI.isVolatile())
2513
453
        NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
2514
1.01M
2515
1.01M
      // Any !nonnull metadata or !range metadata on the old load is also valid
2516
1.01M
      // on the new load. This is even true in some cases even when the loads
2517
1.01M
      // are different types, for example by mapping !nonnull metadata to
2518
1.01M
      // !range metadata by modeling the null pointer constant converted to the
2519
1.01M
      // integer type.
2520
1.01M
      // FIXME: Add support for range metadata here. Currently the utilities
2521
1.01M
      // for this don't propagate range metadata in trivial cases from one
2522
1.01M
      // integer load to another, don't handle non-addrspace-0 null pointers
2523
1.01M
      // correctly, and don't have any support for mapping ranges as the
2524
1.01M
      // integer type becomes winder or narrower.
2525
1.01M
      if (MDNode *N = LI.getMetadata(LLVMContext::MD_nonnull))
2526
5
        copyNonnullMetadata(LI, N, *NewLI);
2527
1.01M
2528
1.01M
      // Try to preserve nonnull metadata
2529
1.01M
      V = NewLI;
2530
1.01M
2531
1.01M
      // If this is an integer load past the end of the slice (which means the
2532
1.01M
      // bytes outside the slice are undef or this load is dead) just forcibly
2533
1.01M
      // fix the integer size with correct handling of endianness.
2534
1.01M
      if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2535
56.4k
        if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
2536
36.7k
          if (AITy->getBitWidth() < TITy->getBitWidth()) {
2537
10
            V = IRB.CreateZExt(V, TITy, "load.ext");
2538
10
            if (DL.isBigEndian())
2539
1
              V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
2540
1
                                "endian_shift");
2541
10
          }
2542
1.01M
    } else {
2543
858
      Type *LTy = TargetTy->getPointerTo(AS);
2544
858
      LoadInst *NewLI = IRB.CreateAlignedLoad(
2545
858
          TargetTy, getNewAllocaSlicePtr(IRB, LTy), getSliceAlign(TargetTy),
2546
858
          LI.isVolatile(), LI.getName());
2547
858
      if (AATags)
2548
477
        NewLI->setAAMetadata(AATags);
2549
858
      if (LI.isVolatile())
2550
8
        NewLI->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
2551
858
2552
858
      V = NewLI;
2553
858
      IsPtrAdjusted = true;
2554
858
    }
2555
1.87M
    V = convertValue(DL, IRB, V, TargetTy);
2556
1.87M
2557
1.87M
    if (IsSplit) {
2558
4.37k
      assert(!LI.isVolatile());
2559
4.37k
      assert(LI.getType()->isIntegerTy() &&
2560
4.37k
             "Only integer type loads and stores are split");
2561
4.37k
      assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
2562
4.37k
             "Split load isn't smaller than original load");
2563
4.37k
      assert(DL.typeSizeEqualsStoreSize(LI.getType()) &&
2564
4.37k
             "Non-byte-multiple bit width");
2565
4.37k
      // Move the insertion point just past the load so that we can refer to it.
2566
4.37k
      IRB.SetInsertPoint(&*std::next(BasicBlock::iterator(&LI)));
2567
4.37k
      // Create a placeholder value with the same type as LI to use as the
2568
4.37k
      // basis for the new value. This allows us to replace the uses of LI with
2569
4.37k
      // the computed value, and then replace the placeholder with LI, leaving
2570
4.37k
      // LI only used for this computation.
2571
4.37k
      Value *Placeholder = new LoadInst(
2572
4.37k
          LI.getType(), UndefValue::get(LI.getType()->getPointerTo(AS)));
2573
4.37k
      V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
2574
4.37k
                        "insert");
2575
4.37k
      LI.replaceAllUsesWith(V);
2576
4.37k
      Placeholder->replaceAllUsesWith(&LI);
2577
4.37k
      Placeholder->deleteValue();
2578
1.87M
    } else {
2579
1.87M
      LI.replaceAllUsesWith(V);
2580
1.87M
    }
2581
1.87M
2582
1.87M
    Pass.DeadInsts.insert(&LI);
2583
1.87M
    deleteIfTriviallyDead(OldOp);
2584
1.87M
    LLVM_DEBUG(dbgs() << "          to: " << *V << "\n");
2585
1.87M
    return !LI.isVolatile() && 
!IsPtrAdjusted1.87M
;
2586
1.87M
  }
2587
2588
  bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp,
2589
37.2k
                                  AAMDNodes AATags) {
2590
37.2k
    if (V->getType() != VecTy) {
2591
329
      unsigned BeginIndex = getIndex(NewBeginOffset);
2592
329
      unsigned EndIndex = getIndex(NewEndOffset);
2593
329
      assert(EndIndex > BeginIndex && "Empty vector!");
2594
329
      unsigned NumElements = EndIndex - BeginIndex;
2595
329
      assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2596
329
      Type *SliceTy = (NumElements == 1)
2597
329
                          ? 
ElementTy301
2598
329
                          : 
VectorType::get(ElementTy, NumElements)28
;
2599
329
      if (V->getType() != SliceTy)
2600
39
        V = convertValue(DL, IRB, V, SliceTy);
2601
329
2602
329
      // Mix in the existing elements.
2603
329
      Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2604
329
                                         NewAI.getAlignment(), "load");
2605
329
      V = insertVector(IRB, Old, V, BeginIndex, "vec");
2606
329
    }
2607
37.2k
    StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2608
37.2k
    if (AATags)
2609
30.7k
      Store->setAAMetadata(AATags);
2610
37.2k
    Pass.DeadInsts.insert(&SI);
2611
37.2k
2612
37.2k
    LLVM_DEBUG(dbgs() << "          to: " << *Store << "\n");
2613
37.2k
    return true;
2614
37.2k
  }
2615
2616
569k
  bool rewriteIntegerStore(Value *V, StoreInst &SI, AAMDNodes AATags) {
2617
569k
    assert(IntTy && "We cannot extract an integer from the alloca");
2618
569k
    assert(!SI.isVolatile());
2619
569k
    if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
2620
57
      Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2621
57
                                         NewAI.getAlignment(), "oldload");
2622
57
      Old = convertValue(DL, IRB, Old, IntTy);
2623
57
      assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
2624
57
      uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
2625
57
      V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
2626
57
    }
2627
569k
    V = convertValue(DL, IRB, V, NewAllocaTy);
2628
569k
    StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
2629
569k
    Store->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2630
569k
                             LLVMContext::MD_access_group});
2631
569k
    if (AATags)
2632
425k
      Store->setAAMetadata(AATags);
2633
569k
    Pass.DeadInsts.insert(&SI);
2634
569k
    LLVM_DEBUG(dbgs() << "          to: " << *Store << "\n");
2635
569k
    return true;
2636
569k
  }
2637
2638
1.22M
  bool visitStoreInst(StoreInst &SI) {
2639
1.22M
    LLVM_DEBUG(dbgs() << "    original: " << SI << "\n");
2640
1.22M
    Value *OldOp = SI.getOperand(1);
2641
1.22M
    assert(OldOp == OldPtr);
2642
1.22M
2643
1.22M
    AAMDNodes AATags;
2644
1.22M
    SI.getAAMetadata(AATags);
2645
1.22M
2646
1.22M
    Value *V = SI.getValueOperand();
2647
1.22M
2648
1.22M
    // Strip all inbounds GEPs and pointer casts to try to dig out any root
2649
1.22M
    // alloca that should be re-examined after promoting this alloca.
2650
1.22M
    if (V->getType()->isPointerTy())
2651
508k
      if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
2652
6.03k
        Pass.PostPromotionWorklist.insert(AI);
2653
1.22M
2654
1.22M
    if (SliceSize < DL.getTypeStoreSize(V->getType())) {
2655
4.21k
      assert(!SI.isVolatile());
2656
4.21k
      assert(V->getType()->isIntegerTy() &&
2657
4.21k
             "Only integer type loads and stores are split");
2658
4.21k
      assert(DL.typeSizeEqualsStoreSize(V->getType()) &&
2659
4.21k
             "Non-byte-multiple bit width");
2660
4.21k
      IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
2661
4.21k
      V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
2662
4.21k
                         "extract");
2663
4.21k
    }
2664
1.22M
2665
1.22M
    if (VecTy)
2666
37.2k
      return rewriteVectorizedStoreInst(V, SI, OldOp, AATags);
2667
1.18M
    if (IntTy && 
V->getType()->isIntegerTy()1.11M
)
2668
569k
      return rewriteIntegerStore(V, SI, AATags);
2669
616k
2670
616k
    const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
2671
616k
    StoreInst *NewSI;
2672
616k
    if (NewBeginOffset == NewAllocaBeginOffset &&
2673
616k
        
NewEndOffset == NewAllocaEndOffset616k
&&
2674
616k
        
(615k
canConvertValue(DL, V->getType(), NewAllocaTy)615k
||
2675
615k
         
(120
IsStorePastEnd120
&&
NewAllocaTy->isIntegerTy()0
&&
2676
615k
          
V->getType()->isIntegerTy()0
))) {
2677
615k
      // If this is an integer store past the end of slice (and thus the bytes
2678
615k
      // past that point are irrelevant or this is unreachable), truncate the
2679
615k
      // value prior to storing.
2680
615k
      if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
2681
48.5k
        if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
2682
48.4k
          if (VITy->getBitWidth() > AITy->getBitWidth()) {
2683
0
            if (DL.isBigEndian())
2684
0
              V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
2685
0
                                 "endian_shift");
2686
0
            V = IRB.CreateTrunc(V, AITy, "load.trunc");
2687
0
          }
2688
615k
2689
615k
      V = convertValue(DL, IRB, V, NewAllocaTy);
2690
615k
      NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2691
615k
                                     SI.isVolatile());
2692
615k
    } else {
2693
776
      unsigned AS = SI.getPointerAddressSpace();
2694
776
      Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo(AS));
2695
776
      NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
2696
776
                                     SI.isVolatile());
2697
776
    }
2698
616k
    NewSI->copyMetadata(SI, {LLVMContext::MD_mem_parallel_loop_access,
2699
616k
                             LLVMContext::MD_access_group});
2700
616k
    if (AATags)
2701
516k
      NewSI->setAAMetadata(AATags);
2702
616k
    if (SI.isVolatile())
2703
441
      NewSI->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
2704
616k
    Pass.DeadInsts.insert(&SI);
2705
616k
    deleteIfTriviallyDead(OldOp);
2706
616k
2707
616k
    LLVM_DEBUG(dbgs() << "          to: " << *NewSI << "\n");
2708
616k
    return NewSI->getPointerOperand() == &NewAI && 
!SI.isVolatile()615k
;
2709
616k
  }
2710
2711
  /// Compute an integer value from splatting an i8 across the given
2712
  /// number of bytes.
2713
  ///
2714
  /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
2715
  /// call this routine.
2716
  /// FIXME: Heed the advice above.
2717
  ///
2718
  /// \param V The i8 value to splat.
2719
  /// \param Size The number of bytes in the output (assuming i8 is one byte)
2720
1.84k
  Value *getIntegerSplat(Value *V, unsigned Size) {
2721
1.84k
    assert(Size > 0 && "Expected a positive number of bytes.");
2722
1.84k
    IntegerType *VTy = cast<IntegerType>(V->getType());
2723
1.84k
    assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
2724
1.84k
    if (Size == 1)
2725
119
      return V;
2726
1.72k
2727
1.72k
    Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
2728
1.72k
    V = IRB.CreateMul(
2729
1.72k
        IRB.CreateZExt(V, SplatIntTy, "zext"),
2730
1.72k
        ConstantExpr::getUDiv(
2731
1.72k
            Constant::getAllOnesValue(SplatIntTy),
2732
1.72k
            ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
2733
1.72k
                                  SplatIntTy)),
2734
1.72k
        "isplat");
2735
1.72k
    return V;
2736
1.72k
  }
2737
2738
  /// Compute a vector splat for a given element value.
2739
4
  Value *getVectorSplat(Value *V, unsigned NumElements) {
2740
4
    V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
2741
4
    LLVM_DEBUG(dbgs() << "       splat: " << *V << "\n");
2742
4
    return V;
2743
4
  }
2744
2745
3.62k
  bool visitMemSetInst(MemSetInst &II) {
2746
3.62k
    LLVM_DEBUG(dbgs() << "    original: " << II << "\n");
2747
3.62k
    assert(II.getRawDest() == OldPtr);
2748
3.62k
2749
3.62k
    AAMDNodes AATags;
2750
3.62k
    II.getAAMetadata(AATags);
2751
3.62k
2752
3.62k
    // If the memset has a variable size, it cannot be split, just adjust the
2753
3.62k
    // pointer to the new alloca.
2754
3.62k
    if (!isa<Constant>(II.getLength())) {
2755
6
      assert(!IsSplit);
2756
6
      assert(NewBeginOffset == BeginOffset);
2757
6
      II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
2758
6
      II.setDestAlignment(getSliceAlign());
2759
6
2760
6
      deleteIfTriviallyDead(OldPtr);
2761
6
      return false;
2762
6
    }
2763
3.62k
2764
3.62k
    // Record this instruction for deletion.
2765
3.62k
    Pass.DeadInsts.insert(&II);
2766
3.62k
2767
3.62k
    Type *AllocaTy = NewAI.getAllocatedType();
2768
3.62k
    Type *ScalarTy = AllocaTy->getScalarType();
2769
3.62k
    
2770
3.62k
    const bool CanContinue = [&]() {
2771
3.62k
      if (VecTy || 
IntTy3.61k
)
2772
1.80k
        return true;
2773
1.81k
      if (BeginOffset > NewAllocaBeginOffset ||
2774
1.81k
          
EndOffset < NewAllocaEndOffset1.80k
)
2775
24
        return false;
2776
1.79k
      auto *C = cast<ConstantInt>(II.getLength());
2777
1.79k
      if (C->getBitWidth() > 64)
2778
0
        return false;
2779
1.79k
      const auto Len = C->getZExtValue();
2780
1.79k
      auto *Int8Ty = IntegerType::getInt8Ty(NewAI.getContext());
2781
1.79k
      auto *SrcTy = VectorType::get(Int8Ty, Len);
2782
1.79k
      return canConvertValue(DL, SrcTy, AllocaTy) &&
2783
1.79k
        
DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy))41
;
2784
1.79k
    }();
2785
3.62k
2786
3.62k
    // If this doesn't map cleanly onto the alloca type, and that type isn't
2787
3.62k
    // a single value type, just emit a memset.
2788
3.62k
    if (!CanContinue) {
2789
1.77k
      Type *SizeTy = II.getLength()->getType();
2790
1.77k
      Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2791
1.77k
      CallInst *New = IRB.CreateMemSet(
2792
1.77k
          getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
2793
1.77k
          getSliceAlign(), II.isVolatile());
2794
1.77k
      if (AATags)
2795
159
        New->setAAMetadata(AATags);
2796
1.77k
      LLVM_DEBUG(dbgs() << "          to: " << *New << "\n");
2797
1.77k
      return false;
2798
1.77k
    }
2799
1.84k
2800
1.84k
    // If we can represent this as a simple value, we have to build the actual
2801
1.84k
    // value to store, which requires expanding the byte present in memset to
2802
1.84k
    // a sensible representation for the alloca type. This is essentially
2803
1.84k
    // splatting the byte to a sufficiently wide integer, splatting it across
2804
1.84k
    // any desired vector width, and bitcasting to the final type.
2805
1.84k
    Value *V;
2806
1.84k
2807
1.84k
    if (VecTy) {
2808
6
      // If this is a memset of a vectorized alloca, insert it.
2809
6
      assert(ElementTy == ScalarTy);
2810
6
2811
6
      unsigned BeginIndex = getIndex(NewBeginOffset);
2812
6
      unsigned EndIndex = getIndex(NewEndOffset);
2813
6
      assert(EndIndex > BeginIndex && "Empty vector!");
2814
6
      unsigned NumElements = EndIndex - BeginIndex;
2815
6
      assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
2816
6
2817
6
      Value *Splat =
2818
6
          getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
2819
6
      Splat = convertValue(DL, IRB, Splat, ElementTy);
2820
6
      if (NumElements > 1)
2821
4
        Splat = getVectorSplat(Splat, NumElements);
2822
6
2823
6
      Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2824
6
                                         NewAI.getAlignment(), "oldload");
2825
6
      V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
2826
1.83k
    } else if (IntTy) {
2827
1.79k
      // If this is a memset on an alloca where we can widen stores, insert the
2828
1.79k
      // set integer.
2829
1.79k
      assert(!II.isVolatile());
2830
1.79k
2831
1.79k
      uint64_t Size = NewEndOffset - NewBeginOffset;
2832
1.79k
      V = getIntegerSplat(II.getValue(), Size);
2833
1.79k
2834
1.79k
      if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
2835
1.79k
                    
EndOffset != NewAllocaBeginOffset1.34k
)) {
2836
1.79k
        Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
2837
1.79k
                                           NewAI.getAlignment(), "oldload");
2838
1.79k
        Old = convertValue(DL, IRB, Old, IntTy);
2839
1.79k
        uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
2840
1.79k
        V = insertInteger(DL, IRB, Old, V, Offset, "insert");
2841
1.79k
      } else {
2842
0
        assert(V->getType() == IntTy &&
2843
0
               "Wrong type for an alloca wide integer!");
2844
0
      }
2845
1.79k
      V = convertValue(DL, IRB, V, AllocaTy);
2846
1.79k
    } else {
2847
39
      // Established these invariants above.
2848
39
      assert(NewBeginOffset == NewAllocaBeginOffset);
2849
39
      assert(NewEndOffset == NewAllocaEndOffset);
2850
39
2851
39
      V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
2852
39
      if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
2853
0
        V = getVectorSplat(V, AllocaVecTy->getNumElements());
2854
39
2855
39
      V = convertValue(DL, IRB, V, AllocaTy);
2856
39
    }
2857
1.84k
2858
1.84k
    StoreInst *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
2859
1.84k
                                            II.isVolatile());
2860
1.84k
    if (AATags)
2861
200
      New->setAAMetadata(AATags);
2862
1.84k
    LLVM_DEBUG(dbgs() << "          to: " << *New << "\n");
2863
1.84k
    return !II.isVolatile();
2864
1.84k
  }
2865
2866
41.1k
  bool visitMemTransferInst(MemTransferInst &II) {
2867
41.1k
    // Rewriting of memory transfer instructions can be a bit tricky. We break
2868
41.1k
    // them into two categories: split intrinsics and unsplit intrinsics.
2869
41.1k
2870
41.1k
    LLVM_DEBUG(dbgs() << "    original: " << II << "\n");
2871
41.1k
2872
41.1k
    AAMDNodes AATags;
2873
41.1k
    II.getAAMetadata(AATags);
2874
41.1k
2875
41.1k
    bool IsDest = &II.getRawDestUse() == OldUse;
2876
41.1k
    assert((IsDest && II.getRawDest() == OldPtr) ||
2877
41.1k
           (!IsDest && II.getRawSource() == OldPtr));
2878
41.1k
2879
41.1k
    unsigned SliceAlign = getSliceAlign();
2880
41.1k
2881
41.1k
    // For unsplit intrinsics, we simply modify the source and destination
2882
41.1k
    // pointers in place. This isn't just an optimization, it is a matter of
2883
41.1k
    // correctness. With unsplit intrinsics we may be dealing with transfers
2884
41.1k
    // within a single alloca before SROA ran, or with transfers that have
2885
41.1k
    // a variable length. We may also be dealing with memmove instead of
2886
41.1k
    // memcpy, and so simply updating the pointers is the necessary for us to
2887
41.1k
    // update both source and dest of a single call.
2888
41.1k
    if (!IsSplittable) {
2889
24
      Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2890
24
      if (IsDest) {
2891
11
        II.setDest(AdjustedPtr);
2892
11
        II.setDestAlignment(SliceAlign);
2893
11
      }
2894
13
      else {
2895
13
        II.setSource(AdjustedPtr);
2896
13
        II.setSourceAlignment(SliceAlign);
2897
13
      }
2898
24
2899
24
      LLVM_DEBUG(dbgs() << "          to: " << II << "\n");
2900
24
      deleteIfTriviallyDead(OldPtr);
2901
24
      return false;
2902
24
    }
2903
41.1k
    // For split transfer intrinsics we have an incredibly useful assurance:
2904
41.1k
    // the source and destination do not reside within the same alloca, and at
2905
41.1k
    // least one of them does not escape. This means that we can replace
2906
41.1k
    // memmove with memcpy, and we don't need to worry about all manner of
2907
41.1k
    // downsides to splitting and transforming the operations.
2908
41.1k
2909
41.1k
    // If this doesn't map cleanly onto the alloca type, and that type isn't
2910
41.1k
    // a single value type, just emit a memcpy.
2911
41.1k
    bool EmitMemCpy =
2912
41.1k
        !VecTy && 
!IntTy39.6k
&&
2913
41.1k
        
(28.7k
BeginOffset > NewAllocaBeginOffset28.7k
||
EndOffset < NewAllocaEndOffset28.4k
||
2914
28.7k
         
SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType())28.2k
||
2915
28.7k
         
!NewAI.getAllocatedType()->isSingleValueType()28.2k
);
2916
41.1k
2917
41.1k
    // If we're just going to emit a memcpy, the alloca hasn't changed, and the
2918
41.1k
    // size hasn't been shrunk based on analysis of the viable range, this is
2919
41.1k
    // a no-op.
2920
41.1k
    if (EmitMemCpy && 
&OldAI == &NewAI10.9k
) {
2921
7.81k
      // Ensure the start lines up.
2922
7.81k
      assert(NewBeginOffset == BeginOffset);
2923
7.81k
2924
7.81k
      // Rewrite the size as needed.
2925
7.81k
      if (NewEndOffset != EndOffset)
2926
0
        II.setLength(ConstantInt::get(II.getLength()->getType(),
2927
0
                                      NewEndOffset - NewBeginOffset));
2928
7.81k
      return false;
2929
7.81k
    }
2930
33.3k
    // Record this instruction for deletion.
2931
33.3k
    Pass.DeadInsts.insert(&II);
2932
33.3k
2933
33.3k
    // Strip all inbounds GEPs and pointer casts to try to dig out any root
2934
33.3k
    // alloca that should be re-examined after rewriting this instruction.
2935
33.3k
    Value *OtherPtr = IsDest ? 
II.getRawSource()14.0k
:
II.getRawDest()19.3k
;
2936
33.3k
    if (AllocaInst *AI =
2937
21.2k
            dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
2938
21.2k
      assert(AI != &OldAI && AI != &NewAI &&
2939
21.2k
             "Splittable transfers cannot reach the same alloca on both ends.");
2940
21.2k
      Pass.Worklist.insert(AI);
2941
21.2k
    }
2942
33.3k
2943
33.3k
    Type *OtherPtrTy = OtherPtr->getType();
2944
33.3k
    unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
2945
33.3k
2946
33.3k
    // Compute the relative offset for the other pointer within the transfer.
2947
33.3k
    unsigned OffsetWidth = DL.getIndexSizeInBits(OtherAS);
2948
33.3k
    APInt OtherOffset(OffsetWidth, NewBeginOffset - BeginOffset);
2949
33.3k
    unsigned OtherAlign =
2950
33.3k
      IsDest ? 
II.getSourceAlignment()14.0k
:
II.getDestAlignment()19.3k
;
2951
33.3k
    OtherAlign =  MinAlign(OtherAlign ? 
OtherAlign33.2k
:
1113
,
2952
33.3k
                           OtherOffset.zextOrTrunc(64).getZExtValue());
2953
33.3k
2954
33.3k
    if (EmitMemCpy) {
2955
3.14k
      // Compute the other pointer, folding as much as possible to produce
2956
3.14k
      // a single, simple GEP in most cases.
2957
3.14k
      OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
2958
3.14k
                                OtherPtr->getName() + ".");
2959
3.14k
2960
3.14k
      Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
2961
3.14k
      Type *SizeTy = II.getLength()->getType();
2962
3.14k
      Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
2963
3.14k
2964
3.14k
      Value *DestPtr, *SrcPtr;
2965
3.14k
      unsigned DestAlign, SrcAlign;
2966
3.14k
      // Note: IsDest is true iff we're copying into the new alloca slice
2967
3.14k
      if (IsDest) {
2968
1.40k
        DestPtr = OurPtr;
2969
1.40k
        DestAlign = SliceAlign;
2970
1.40k
        SrcPtr = OtherPtr;
2971
1.40k
        SrcAlign = OtherAlign;
2972
1.74k
      } else {
2973
1.74k
        DestPtr = OtherPtr;
2974
1.74k
        DestAlign = OtherAlign;
2975
1.74k
        SrcPtr = OurPtr;
2976
1.74k
        SrcAlign = SliceAlign;
2977
1.74k
      }
2978
3.14k
      CallInst *New = IRB.CreateMemCpy(DestPtr, DestAlign, SrcPtr, SrcAlign,
2979
3.14k
                                       Size, II.isVolatile());
2980
3.14k
      if (AATags)
2981
82
        New->setAAMetadata(AATags);
2982
3.14k
      LLVM_DEBUG(dbgs() << "          to: " << *New << "\n");
2983
3.14k
      return false;
2984
3.14k
    }
2985
30.1k
2986
30.1k
    bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
2987
30.1k
                         
NewEndOffset == NewAllocaEndOffset30.1k
;
2988
30.1k
    uint64_t Size = NewEndOffset - NewBeginOffset;
2989
30.1k
    unsigned BeginIndex = VecTy ? 
getIndex(NewBeginOffset)1.54k
:
028.6k
;
2990
30.1k
    unsigned EndIndex = VecTy ? 
getIndex(NewEndOffset)1.54k
:
028.6k
;
2991
30.1k
    unsigned NumElements = EndIndex - BeginIndex;
2992
30.1k
    IntegerType *SubIntTy =
2993
30.1k
        IntTy ? 
Type::getIntNTy(IntTy->getContext(), Size * 8)10.8k
:
nullptr19.3k
;
2994
30.1k
2995
30.1k
    // Reset the other pointer type to match the register type we're going to
2996
30.1k
    // use, but using the address space of the original other pointer.
2997
30.1k
    Type *OtherTy;
2998
30.1k
    if (VecTy && 
!IsWholeAlloca1.54k
) {
2999
10
      if (NumElements == 1)
3000
4
        OtherTy = VecTy->getElementType();
3001
6
      else
3002
6
        OtherTy = VectorType::get(VecTy->getElementType(), NumElements);
3003
30.1k
    } else if (IntTy && 
!IsWholeAlloca10.8k
) {
3004
175
      OtherTy = SubIntTy;
3005
30.0k
    } else {
3006
30.0k
      OtherTy = NewAllocaTy;
3007
30.0k
    }
3008
30.1k
    OtherPtrTy = OtherTy->getPointerTo(OtherAS);
3009
30.1k
3010
30.1k
    Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
3011
30.1k
                                   OtherPtr->getName() + ".");
3012
30.1k
    unsigned SrcAlign = OtherAlign;
3013
30.1k
    Value *DstPtr = &NewAI;
3014
30.1k
    unsigned DstAlign = SliceAlign;
3015
30.1k
    if (!IsDest) {
3016
17.5k
      std::swap(SrcPtr, DstPtr);
3017
17.5k
      std::swap(SrcAlign, DstAlign);
3018
17.5k
    }
3019
30.1k
3020
30.1k
    Value *Src;
3021
30.1k
    if (VecTy && 
!IsWholeAlloca1.54k
&&
!IsDest10
) {
3022
3
      Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3023
3
                                  NewAI.getAlignment(), "load");
3024
3
      Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
3025
30.1k
    } else if (IntTy && 
!IsWholeAlloca10.8k
&&
!IsDest175
) {
3026
95
      Src = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3027
95
                                  NewAI.getAlignment(), "load");
3028
95
      Src = convertValue(DL, IRB, Src, IntTy);
3029
95
      uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3030
95
      Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
3031
30.0k
    } else {
3032
30.0k
      LoadInst *Load = IRB.CreateAlignedLoad(OtherTy, SrcPtr, SrcAlign,
3033
30.0k
                                             II.isVolatile(), "copyload");
3034
30.0k
      if (AATags)
3035
77
        Load->setAAMetadata(AATags);
3036
30.0k
      Src = Load;
3037
30.0k
    }
3038
30.1k
3039
30.1k
    if (VecTy && 
!IsWholeAlloca1.54k
&&
IsDest10
) {
3040
7
      Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3041
7
                                         NewAI.getAlignment(), "oldload");
3042
7
      Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
3043
30.1k
    } else if (IntTy && 
!IsWholeAlloca10.8k
&&
IsDest175
) {
3044
80
      Value *Old = IRB.CreateAlignedLoad(NewAI.getAllocatedType(), &NewAI,
3045
80
                                         NewAI.getAlignment(), "oldload");
3046
80
      Old = convertValue(DL, IRB, Old, IntTy);
3047
80
      uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
3048
80
      Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
3049
80
      Src = convertValue(DL, IRB, Src, NewAllocaTy);
3050
80
    }
3051
30.1k
3052
30.1k
    StoreInst *Store = cast<StoreInst>(
3053
30.1k
        IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
3054
30.1k
    if (AATags)
3055
77
      Store->setAAMetadata(AATags);
3056
30.1k
    LLVM_DEBUG(dbgs() << "          to: " << *Store << "\n");
3057
30.1k
    return !II.isVolatile();
3058
30.1k
  }
3059
3060
773k
  bool visitIntrinsicInst(IntrinsicInst &II) {
3061
773k
    assert(II.isLifetimeStartOrEnd());
3062
773k
    LLVM_DEBUG(dbgs() << "    original: " << II << "\n");
3063
773k
    assert(II.getArgOperand(1) == OldPtr);
3064
773k
3065
773k
    // Record this instruction for deletion.
3066
773k
    Pass.DeadInsts.insert(&II);
3067
773k
3068
773k
    // Lifetime intrinsics are only promotable if they cover the whole alloca.
3069
773k
    // Therefore, we drop lifetime intrinsics which don't cover the whole
3070
773k
    // alloca.
3071
773k
    // (In theory, intrinsics which partially cover an alloca could be
3072
773k
    // promoted, but PromoteMemToReg doesn't handle that case.)
3073
773k
    // FIXME: Check whether the alloca is promotable before dropping the
3074
773k
    // lifetime intrinsics?
3075
773k
    if (NewBeginOffset != NewAllocaBeginOffset ||
3076
773k
        
NewEndOffset != NewAllocaEndOffset773k
)
3077
4
      return true;
3078
773k
3079
773k
    ConstantInt *Size =
3080
773k
        ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
3081
773k
                         NewEndOffset - NewBeginOffset);
3082
773k
    // Lifetime intrinsics always expect an i8* so directly get such a pointer
3083
773k
    // for the new alloca slice.
3084
773k
    Type *PointerTy = IRB.getInt8PtrTy(OldPtr->getType()->getPointerAddressSpace());
3085
773k
    Value *Ptr = getNewAllocaSlicePtr(IRB, PointerTy);
3086
773k
    Value *New;
3087
773k
    if (II.getIntrinsicID() == Intrinsic::lifetime_start)
3088
375k
      New = IRB.CreateLifetimeStart(Ptr, Size);
3089
397k
    else
3090
397k
      New = IRB.CreateLifetimeEnd(Ptr, Size);
3091
773k
3092
773k
    (void)New;
3093
773k
    LLVM_DEBUG(dbgs() << "          to: " << *New << "\n");
3094
773k
3095
773k
    return true;
3096
773k
  }
3097
3098
2.48k
  void fixLoadStoreAlign(Instruction &Root) {
3099
2.48k
    // This algorithm implements the same visitor loop as
3100
2.48k
    // hasUnsafePHIOrSelectUse, and fixes the alignment of each load
3101
2.48k
    // or store found.
3102
2.48k
    SmallPtrSet<Instruction *, 4> Visited;
3103
2.48k
    SmallVector<Instruction *, 4> Uses;
3104
2.48k
    Visited.insert(&Root);
3105
2.48k
    Uses.push_back(&Root);
3106
6.09k
    do {
3107
6.09k
      Instruction *I = Uses.pop_back_val();
3108
6.09k
3109
6.09k
      if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3110
2.48k
        unsigned LoadAlign = LI->getAlignment();
3111
2.48k
        if (!LoadAlign)
3112
22
          LoadAlign = DL.getABITypeAlignment(LI->getType());
3113
2.48k
        LI->setAlignment(std::min(LoadAlign, getSliceAlign()));
3114
2.48k
        continue;
3115
2.48k
      }
3116
3.61k
      if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3117
850
        unsigned StoreAlign = SI->getAlignment();
3118
850
        if (!StoreAlign) {
3119
0
          Value *Op = SI->getOperand(0);
3120
0
          StoreAlign = DL.getABITypeAlignment(Op->getType());
3121
0
        }
3122
850
        SI->setAlignment(std::min(StoreAlign, getSliceAlign()));
3123
850
        continue;
3124
850
      }
3125
2.76k
3126
2.76k
      assert(isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I) ||
3127
2.76k
             isa<PHINode>(I) || isa<SelectInst>(I) ||
3128
2.76k
             isa<GetElementPtrInst>(I));
3129
2.76k
      for (User *U : I->users())
3130
3.61k
        if (Visited.insert(cast<Instruction>(U)).second)
3131
3.60k
          Uses.push_back(cast<Instruction>(U));
3132
6.09k
    } while (!Uses.empty());
3133
2.48k
  }
3134
3135
843
  bool visitPHINode(PHINode &PN) {
3136
843
    LLVM_DEBUG(dbgs() << "    original: " << PN << "\n");
3137
843
    assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
3138
843
    assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
3139
843
3140
843
    // We would like to compute a new pointer in only one place, but have it be
3141
843
    // as local as possible to the PHI. To do that, we re-use the location of
3142
843
    // the old pointer, which necessarily must be in the right position to
3143
843
    // dominate the PHI.
3144
843
    IRBuilderTy PtrBuilder(IRB);
3145
843
    if (isa<PHINode>(OldPtr))
3146
27
      PtrBuilder.SetInsertPoint(&*OldPtr->getParent()->getFirstInsertionPt());
3147
816
    else
3148
816
      PtrBuilder.SetInsertPoint(OldPtr);
3149
843
    PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
3150
843
3151
843
    Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
3152
843
    // Replace the operands which were using the old pointer.
3153
843
    std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
3154
843
3155
843
    LLVM_DEBUG(dbgs() << "          to: " << PN << "\n");
3156
843
    deleteIfTriviallyDead(OldPtr);
3157
843
3158
843
    // Fix the alignment of any loads or stores using this PHI node.
3159
843
    fixLoadStoreAlign(PN);
3160
843
3161
843
    // PHIs can't be promoted on their own, but often can be speculated. We
3162
843
    // check the speculation outside of the rewriter so that we see the
3163
843
    // fully-rewritten alloca.
3164
843
    PHIUsers.insert(&PN);
3165
843
    return true;
3166
843
  }
3167
3168
1.64k
  bool visitSelectInst(SelectInst &SI) {
3169
1.64k
    LLVM_DEBUG(dbgs() << "    original: " << SI << "\n");
3170
1.64k
    assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
3171
1.64k
           "Pointer isn't an operand!");
3172
1.64k
    assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
3173
1.64k
    assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
3174
1.64k
3175
1.64k
    Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
3176
1.64k
    // Replace the operands which were using the old pointer.
3177
1.64k
    if (SI.getOperand(1) == OldPtr)
3178
1.12k
      SI.setOperand(1, NewPtr);
3179
1.64k
    if (SI.getOperand(2) == OldPtr)
3180
517
      SI.setOperand(2, NewPtr);
3181
1.64k
3182
1.64k
    LLVM_DEBUG(dbgs() << "          to: " << SI << "\n");
3183
1.64k
    deleteIfTriviallyDead(OldPtr);
3184
1.64k
3185
1.64k
    // Fix the alignment of any loads or stores using this select.
3186
1.64k
    fixLoadStoreAlign(SI);
3187
1.64k
3188
1.64k
    // Selects can't be promoted on their own, but often can be speculated. We
3189
1.64k
    // check the speculation outside of the rewriter so that we see the
3190
1.64k
    // fully-rewritten alloca.
3191
1.64k
    SelectUsers.insert(&SI);
3192
1.64k
    return true;
3193
1.64k
  }
3194
};
3195
3196
namespace {
3197
3198
/// Visitor to rewrite aggregate loads and stores as scalar.
3199
///
3200
/// This pass aggressively rewrites all aggregate loads and stores on
3201
/// a particular pointer (or any pointer derived from it which we can identify)
3202
/// with scalar loads and stores.
3203
class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
3204
  // Befriend the base class so it can delegate to private visit methods.
3205
  friend class InstVisitor<AggLoadStoreRewriter, bool>;
3206
3207
  /// Queue of pointer uses to analyze and potentially rewrite.
3208
  SmallVector<Use *, 8> Queue;
3209
3210
  /// Set to prevent us from cycling with phi nodes and loops.
3211
  SmallPtrSet<User *, 8> Visited;
3212
3213
  /// The current pointer use being rewritten. This is used to dig up the used
3214
  /// value (as opposed to the user).
3215
  Use *U;
3216
3217
  /// Used to calculate offsets, and hence alignment, of subobjects.
3218
  const DataLayout &DL;
3219
3220
public:
3221
1.08M
  AggLoadStoreRewriter(const DataLayout &DL) : DL(DL) {}
3222
3223
  /// Rewrite loads and stores through a pointer and all pointers derived from
3224
  /// it.
3225
1.08M
  bool rewrite(Instruction &I) {
3226
1.08M
    LLVM_DEBUG(dbgs() << "  Rewriting FCA loads and stores...\n");
3227
1.08M
    enqueueUsers(I);
3228
1.08M
    bool Changed = false;
3229
8.56M
    while (!Queue.empty()) {
3230
7.48M
      U = Queue.pop_back_val();
3231
7.48M
      Changed |= visit(cast<Instruction>(U->getUser()));
3232
7.48M
    }
3233
1.08M
    return Changed;
3234
1.08M
  }
3235
3236
private:
3237
  /// Enqueue all the users of the given instruction for further processing.
3238
  /// This uses a set to de-duplicate users.
3239
3.04M
  void enqueueUsers(Instruction &I) {
3240
3.04M
    for (Use &U : I.uses())
3241
7.53M
      if (Visited.insert(U.getUser()).second)
3242
7.48M
        Queue.push_back(&U);
3243
3.04M
  }
3244
3245
  // Conservative default is to not rewrite anything.
3246
1.63M
  bool visitInstruction(Instruction &I) { return false; }
3247
3248
  /// Generic recursive split emission class.
3249
  template <typename Derived> class OpSplitter {
3250
  protected:
3251
    /// The builder used to form new instructions.
3252
    IRBuilderTy IRB;
3253
3254
    /// The indices which to be used with insert- or extractvalue to select the
3255
    /// appropriate value within the aggregate.
3256
    SmallVector<unsigned, 4> Indices;
3257
3258
    /// The indices to a GEP instruction which will move Ptr to the correct slot
3259
    /// within the aggregate.
3260
    SmallVector<Value *, 4> GEPIndices;
3261
3262
    /// The base pointer of the original op, used as a base for GEPing the
3263
    /// split operations.
3264
    Value *Ptr;
3265
3266
    /// The base pointee type being GEPed into.
3267
    Type *BaseTy;
3268
3269
    /// Known alignment of the base pointer.
3270
    unsigned BaseAlign;
3271
3272
    /// To calculate offset of each component so we can correctly deduce
3273
    /// alignments.
3274
    const DataLayout &DL;
3275
3276
    /// Initialize the splitter with an insertion point, Ptr and start with a
3277
    /// single zero GEP index.
3278
    OpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3279
               unsigned BaseAlign, const DataLayout &DL)
3280
        : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr),
3281
10.3k
          BaseTy(BaseTy), BaseAlign(BaseAlign), DL(DL) {}
SROA.cpp:(anonymous namespace)::AggLoadStoreRewriter::OpSplitter<(anonymous namespace)::AggLoadStoreRewriter::LoadOpSplitter>::OpSplitter(llvm::Instruction*, llvm::Value*, llvm::Type*, unsigned int, llvm::DataLayout const&)
Line
Count
Source
3281
4.39k
          BaseTy(BaseTy), BaseAlign(BaseAlign), DL(DL) {}
SROA.cpp:(anonymous namespace)::AggLoadStoreRewriter::OpSplitter<(anonymous namespace)::AggLoadStoreRewriter::StoreOpSplitter>::OpSplitter(llvm::Instruction*, llvm::Value*, llvm::Type*, unsigned int, llvm::DataLayout const&)
Line
Count
Source
3281
5.93k
          BaseTy(BaseTy), BaseAlign(BaseAlign), DL(DL) {}
3282
3283
  public:
3284
    /// Generic recursive split emission routine.
3285
    ///
3286
    /// This method recursively splits an aggregate op (load or store) into
3287
    /// scalar or vector ops. It splits recursively until it hits a single value
3288
    /// and emits that single value operation via the template argument.
3289
    ///
3290
    /// The logic of this routine relies on GEPs and insertvalue and
3291
    /// extractvalue all operating with the same fundamental index list, merely
3292
    /// formatted differently (GEPs need actual values).
3293
    ///
3294
    /// \param Ty  The type being split recursively into smaller ops.
3295
    /// \param Agg The aggregate value being built up or stored, depending on
3296
    /// whether this is splitting a load or a store respectively.
3297
40.4k
    void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3298
40.4k
      if (Ty->isSingleValueType()) {
3299
29.1k
        unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices);
3300
29.1k
        return static_cast<Derived *>(this)->emitFunc(
3301
29.1k
            Ty, Agg, MinAlign(BaseAlign, Offset), Name);
3302
29.1k
      }
3303
11.3k
3304
11.3k
      if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3305
8.77k
        unsigned OldSize = Indices.size();
3306
8.77k
        (void)OldSize;
3307
34.5k
        for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3308
25.7k
             ++Idx) {
3309
25.7k
          assert(Indices.size() == OldSize && "Did not return to the old size");
3310
25.7k
          Indices.push_back(Idx);
3311
25.7k
          GEPIndices.push_back(IRB.getInt32(Idx));
3312
25.7k
          emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3313
25.7k
          GEPIndices.pop_back();
3314
25.7k
          Indices.pop_back();
3315
25.7k
        }
3316
8.77k
        return;
3317
8.77k
      }
3318
2.55k
3319
2.55k
      if (StructType *STy = dyn_cast<StructType>(Ty)) {
3320
2.55k
        unsigned OldSize = Indices.size();
3321
2.55k
        (void)OldSize;
3322
6.96k
        for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3323
4.40k
             ++Idx) {
3324
4.40k
          assert(Indices.size() == OldSize && "Did not return to the old size");
3325
4.40k
          Indices.push_back(Idx);
3326
4.40k
          GEPIndices.push_back(IRB.getInt32(Idx));
3327
4.40k
          emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3328
4.40k
          GEPIndices.pop_back();
3329
4.40k
          Indices.pop_back();
3330
4.40k
        }
3331
2.55k
        return;
3332
2.55k
      }
3333
0
3334
0
      llvm_unreachable("Only arrays and structs are aggregate loadable types");
3335
0
    }
SROA.cpp:(anonymous namespace)::AggLoadStoreRewriter::OpSplitter<(anonymous namespace)::AggLoadStoreRewriter::LoadOpSplitter>::emitSplitOps(llvm::Type*, llvm::Value*&, llvm::Twine const&)
Line
Count
Source
3297
16.6k
    void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3298
16.6k
      if (Ty->isSingleValueType()) {
3299
11.4k
        unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices);
3300
11.4k
        return static_cast<Derived *>(this)->emitFunc(
3301
11.4k
            Ty, Agg, MinAlign(BaseAlign, Offset), Name);
3302
11.4k
      }
3303
5.22k
3304
5.22k
      if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3305
3.26k
        unsigned OldSize = Indices.size();
3306
3.26k
        (void)OldSize;
3307
12.4k
        for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3308
9.14k
             ++Idx) {
3309
9.14k
          assert(Indices.size() == OldSize && "Did not return to the old size");
3310
9.14k
          Indices.push_back(Idx);
3311
9.14k
          GEPIndices.push_back(IRB.getInt32(Idx));
3312
9.14k
          emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3313
9.14k
          GEPIndices.pop_back();
3314
9.14k
          Indices.pop_back();
3315
9.14k
        }
3316
3.26k
        return;
3317
3.26k
      }
3318
1.95k
3319
1.95k
      if (StructType *STy = dyn_cast<StructType>(Ty)) {
3320
1.95k
        unsigned OldSize = Indices.size();
3321
1.95k
        (void)OldSize;
3322
5.07k
        for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3323
3.11k
             ++Idx) {
3324
3.11k
          assert(Indices.size() == OldSize && "Did not return to the old size");
3325
3.11k
          Indices.push_back(Idx);
3326
3.11k
          GEPIndices.push_back(IRB.getInt32(Idx));
3327
3.11k
          emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3328
3.11k
          GEPIndices.pop_back();
3329
3.11k
          Indices.pop_back();
3330
3.11k
        }
3331
1.95k
        return;
3332
1.95k
      }
3333
0
3334
0
      llvm_unreachable("Only arrays and structs are aggregate loadable types");
3335
0
    }
SROA.cpp:(anonymous namespace)::AggLoadStoreRewriter::OpSplitter<(anonymous namespace)::AggLoadStoreRewriter::StoreOpSplitter>::emitSplitOps(llvm::Type*, llvm::Value*&, llvm::Twine const&)
Line
Count
Source
3297
23.8k
    void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
3298
23.8k
      if (Ty->isSingleValueType()) {
3299
17.7k
        unsigned Offset = DL.getIndexedOffsetInType(BaseTy, GEPIndices);
3300
17.7k
        return static_cast<Derived *>(this)->emitFunc(
3301
17.7k
            Ty, Agg, MinAlign(BaseAlign, Offset), Name);
3302
17.7k
      }
3303
6.10k
3304
6.10k
      if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
3305
5.50k
        unsigned OldSize = Indices.size();
3306
5.50k
        (void)OldSize;
3307
22.1k
        for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
3308
16.6k
             ++Idx) {
3309
16.6k
          assert(Indices.size() == OldSize && "Did not return to the old size");
3310
16.6k
          Indices.push_back(Idx);
3311
16.6k
          GEPIndices.push_back(IRB.getInt32(Idx));
3312
16.6k
          emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
3313
16.6k
          GEPIndices.pop_back();
3314
16.6k
          Indices.pop_back();
3315
16.6k
        }
3316
5.50k
        return;
3317
5.50k
      }
3318
599
3319
599
      if (StructType *STy = dyn_cast<StructType>(Ty)) {
3320
599
        unsigned OldSize = Indices.size();
3321
599
        (void)OldSize;
3322
1.89k
        for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
3323
1.29k
             ++Idx) {
3324
1.29k
          assert(Indices.size() == OldSize && "Did not return to the old size");
3325
1.29k
          Indices.push_back(Idx);
3326
1.29k
          GEPIndices.push_back(IRB.getInt32(Idx));
3327
1.29k
          emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
3328
1.29k
          GEPIndices.pop_back();
3329
1.29k
          Indices.pop_back();
3330
1.29k
        }
3331
599
        return;
3332
599
      }
3333
0
3334
0
      llvm_unreachable("Only arrays and structs are aggregate loadable types");
3335
0
    }
3336
  };
3337
3338
  struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
3339
    AAMDNodes AATags;
3340
3341
    LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3342
                   AAMDNodes AATags, unsigned BaseAlign, const DataLayout &DL)
3343
        : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3344
4.39k
                                     DL), AATags(AATags) {}
3345
3346
    /// Emit a leaf load of a single value. This is called at the leaves of the
3347
    /// recursive emission to actually load values.
3348
11.4k
    void emitFunc(Type *Ty, Value *&Agg, unsigned Align, const Twine &Name) {
3349
11.4k
      assert(Ty->isSingleValueType());
3350
11.4k
      // Load the single value and insert it using the indices.
3351
11.4k
      Value *GEP =
3352
11.4k
          IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
3353
11.4k
      LoadInst *Load = IRB.CreateAlignedLoad(Ty, GEP, Align, Name + ".load");
3354
11.4k
      if (AATags)
3355
84
        Load->setAAMetadata(AATags);
3356
11.4k
      Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
3357
11.4k
      LLVM_DEBUG(dbgs() << "          to: " << *Load << "\n");
3358
11.4k
    }
3359
  };
3360
3361
2.08M
  bool visitLoadInst(LoadInst &LI) {
3362
2.08M
    assert(LI.getPointerOperand() == *U);
3363
2.08M
    if (!LI.isSimple() || 
LI.getType()->isSingleValueType()2.08M
)
3364
2.08M
      return false;
3365
4.39k
3366
4.39k
    // We have an aggregate being loaded, split it apart.
3367
4.39k
    LLVM_DEBUG(dbgs() << "    original: " << LI << "\n");
3368
4.39k
    AAMDNodes AATags;
3369
4.39k
    LI.getAAMetadata(AATags);
3370
4.39k
    LoadOpSplitter Splitter(&LI, *U, LI.getType(), AATags,
3371
4.39k
                            getAdjustedAlignment(&LI, 0, DL), DL);
3372
4.39k
    Value *V = UndefValue::get(LI.getType());
3373
4.39k
    Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
3374
4.39k
    LI.replaceAllUsesWith(V);
3375
4.39k
    LI.eraseFromParent();
3376
4.39k
    return true;
3377
4.39k
  }
3378
3379
  struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
3380
    StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr, Type *BaseTy,
3381
                    AAMDNodes AATags, unsigned BaseAlign, const DataLayout &DL)
3382
        : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr, BaseTy, BaseAlign,
3383
                                      DL),
3384
5.93k
          AATags(AATags) {}
3385
    AAMDNodes AATags;
3386
    /// Emit a leaf store of a single value. This is called at the leaves of the
3387
    /// recursive emission to actually produce stores.
3388
17.7k
    void emitFunc(Type *Ty, Value *&Agg, unsigned Align, const Twine &Name) {
3389
17.7k
      assert(Ty->isSingleValueType());
3390
17.7k
      // Extract the single value and store it using the indices.
3391
17.7k
      //
3392
17.7k
      // The gep and extractvalue values are factored out of the CreateStore
3393
17.7k
      // call to make the output independent of the argument evaluation order.
3394
17.7k
      Value *ExtractValue =
3395
17.7k
          IRB.CreateExtractValue(Agg, Indices, Name + ".extract");
3396
17.7k
      Value *InBoundsGEP =
3397
17.7k
          IRB.CreateInBoundsGEP(BaseTy, Ptr, GEPIndices, Name + ".gep");
3398
17.7k
      StoreInst *Store =
3399
17.7k
          IRB.CreateAlignedStore(ExtractValue, InBoundsGEP, Align);
3400
17.7k
      if (AATags)
3401
104
        Store->setAAMetadata(AATags);
3402
17.7k
      LLVM_DEBUG(dbgs() << "          to: " << *Store << "\n");
3403
17.7k
    }
3404
  };
3405
3406
1.79M
  bool visitStoreInst(StoreInst &SI) {
3407
1.79M
    if (!SI.isSimple() || 
SI.getPointerOperand() != *U1.79M
)
3408
18.7k
      return false;
3409
1.77M
    Value *V = SI.getValueOperand();
3410
1.77M
    if (V->getType()->isSingleValueType())
3411
1.77M
      return false;
3412
5.93k
3413
5.93k
    // We have an aggregate being stored, split it apart.
3414
5.93k
    LLVM_DEBUG(dbgs() << "    original: " << SI << "\n");
3415
5.93k
    AAMDNodes AATags;
3416
5.93k
    SI.getAAMetadata(AATags);
3417
5.93k
    StoreOpSplitter Splitter(&SI, *U, V->getType(), AATags,
3418
5.93k
                             getAdjustedAlignment(&SI, 0, DL), DL);
3419
5.93k
    Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
3420
5.93k
    SI.eraseFromParent();
3421
5.93k
    return true;
3422
5.93k
  }
3423
3424
1.05M
  bool visitBitCastInst(BitCastInst &BC) {
3425
1.05M
    enqueueUsers(BC);
3426
1.05M
    return false;
3427
1.05M
  }
3428
3429
163
  bool visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
3430
163
    enqueueUsers(ASC);
3431
163
    return false;
3432
163
  }
3433
3434
871k
  bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
3435
871k
    enqueueUsers(GEPI);
3436
871k
    return false;
3437
871k
  }
3438
3439
28.8k
  bool visitPHINode(PHINode &PN) {
3440
28.8k
    enqueueUsers(PN);
3441
28.8k
    return false;
3442
28.8k
  }
3443
3444
8.39k
  bool visitSelectInst(SelectInst &SI) {
3445
8.39k
    enqueueUsers(SI);
3446
8.39k
    return false;
3447
8.39k
  }
3448
};
3449
3450
} // end anonymous namespace
3451
3452
/// Strip aggregate type wrapping.
3453
///
3454
/// This removes no-op aggregate types wrapping an underlying type. It will
3455
/// strip as many layers of types as it can without changing either the type
3456
/// size or the allocated size.
3457
23.0k
static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
3458
23.0k
  if (Ty->isSingleValueType())
3459
11.3k
    return Ty;
3460
11.7k
3461
11.7k
  uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3462
11.7k
  uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
3463
11.7k
3464
11.7k
  Type *InnerTy;
3465
11.7k
  if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
3466
3.11k
    InnerTy = ArrTy->getElementType();
3467
8.60k
  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
3468
8.60k
    const StructLayout *SL = DL.getStructLayout(STy);
3469
8.60k
    unsigned Index = SL->getElementContainingOffset(0);
3470
8.60k
    InnerTy = STy->getElementType(Index);
3471
8.60k
  } else {
3472
0
    return Ty;
3473
0
  }
3474
11.7k
3475
11.7k
  if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
3476
11.7k
      
TypeSize > DL.getTypeSizeInBits(InnerTy)5.85k
)
3477
5.86k
    return Ty;
3478
5.85k
3479
5.85k
  return stripAggregateTypeWrapping(DL, InnerTy);
3480
5.85k
}
3481
3482
/// Try to find a partition of the aggregate type passed in for a given
3483
/// offset and size.
3484
///
3485
/// This recurses through the aggregate type and tries to compute a subtype
3486
/// based on the offset and size. When the offset and size span a sub-section
3487
/// of an array, it will even compute a new array type for that sub-section,
3488
/// and the same for structs.
3489
///
3490
/// Note that this routine is very strict and tries to find a partition of the
3491
/// type which produces the *exact* right offset and size. It is not forgiving
3492
/// when the size or offset cause either end of type-based partition to be off.
3493
/// Also, this is a best-effort routine. It is reasonable to give up and not
3494
/// return a type if necessary.
3495
static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
3496
24.2k
                              uint64_t Size) {
3497
24.2k
  if (Offset == 0 && 
DL.getTypeAllocSize(Ty) == Size16.1k
)
3498
15.0k
    return stripAggregateTypeWrapping(DL, Ty);
3499
9.24k
  if (Offset > DL.getTypeAllocSize(Ty) ||
3500
9.24k
      (DL.getTypeAllocSize(Ty) - Offset) < Size)
3501
0
    return nullptr;
3502
9.24k
3503
9.24k
  if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
3504
555
    Type *ElementTy = SeqTy->getElementType();
3505
555
    uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3506
555
    uint64_t NumSkippedElements = Offset / ElementSize;
3507
555
    if (NumSkippedElements >= SeqTy->getNumElements())
3508
5
      return nullptr;
3509
550
    Offset -= NumSkippedElements * ElementSize;
3510
550
3511
550
    // First check if we need to recurse.
3512
550
    if (Offset > 0 || 
Size < ElementSize315
) {
3513
235
      // Bail if the partition ends in a different array element.
3514
235
      if ((Offset + Size) > ElementSize)
3515
30
        return nullptr;
3516
205
      // Recurse through the element type trying to peel off offset bytes.
3517
205
      return getTypePartition(DL, ElementTy, Offset, Size);
3518
205
    }
3519
315
    assert(Offset == 0);
3520
315
3521
315
    if (Size == ElementSize)
3522
242
      return stripAggregateTypeWrapping(DL, ElementTy);
3523
73
    assert(Size > ElementSize);
3524
73
    uint64_t NumElements = Size / ElementSize;
3525
73
    if (NumElements * ElementSize != Size)
3526
0
      return nullptr;
3527
73
    return ArrayType::get(ElementTy, NumElements);
3528
73
  }
3529
8.69k
3530
8.69k
  StructType *STy = dyn_cast<StructType>(Ty);
3531
8.69k
  if (!STy)
3532
702
    return nullptr;
3533
7.99k
3534
7.99k
  const StructLayout *SL = DL.getStructLayout(STy);
3535
7.99k
  if (Offset >= SL->getSizeInBytes())
3536
0
    return nullptr;
3537
7.99k
  uint64_t EndOffset = Offset + Size;
3538
7.99k
  if (EndOffset > SL->getSizeInBytes())
3539
0
    return nullptr;
3540
7.99k
3541
7.99k
  unsigned Index = SL->getElementContainingOffset(Offset);
3542
7.99k
  Offset -= SL->getElementOffset(Index);
3543
7.99k
3544
7.99k
  Type *ElementTy = STy->getElementType(Index);
3545
7.99k
  uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
3546
7.99k
  if (Offset >= ElementSize)
3547
1.06k
    return nullptr; // The offset points into alignment padding.
3548
6.92k
3549
6.92k
  // See if any partition must be contained by the element.
3550
6.92k
  if (Offset > 0 || 
Size < ElementSize3.24k
) {
3551
4.13k
    if ((Offset + Size) > ElementSize)
3552
14
      return nullptr;
3553
4.12k
    return getTypePartition(DL, ElementTy, Offset, Size);
3554
4.12k
  }
3555
2.79k
  assert(Offset == 0);
3556
2.79k
3557
2.79k
  if (Size == ElementSize)
3558
1.98k
    return stripAggregateTypeWrapping(DL, ElementTy);
3559
805
3560
805
  StructType::element_iterator EI = STy->element_begin() + Index,
3561
805
                               EE = STy->element_end();
3562
805
  if (EndOffset < SL->getSizeInBytes()) {
3563
280
    unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
3564
280
    if (Index == EndIndex)
3565
0
      return nullptr; // Within a single element and its padding.
3566
280
3567
280
    // Don't try to form "natural" types if the elements don't line up with the
3568
280
    // expected size.
3569
280
    // FIXME: We could potentially recurse down through the last element in the
3570
280
    // sub-struct to find a natural end point.
3571
280
    if (SL->getElementOffset(EndIndex) != EndOffset)
3572
149
      return nullptr;
3573
131
3574
131
    assert(Index < EndIndex);
3575
131
    EE = STy->element_begin() + EndIndex;
3576
131
  }
3577
805
3578
805
  // Try to build up a sub-structure.
3579
805
  StructType *SubTy =
3580
656
      StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
3581
656
  const StructLayout *SubSL = DL.getStructLayout(SubTy);
3582
656
  if (Size != SubSL->getSizeInBytes())
3583
63
    return nullptr; // The sub-struct doesn't have quite the size needed.
3584
593
3585
593
  return SubTy;
3586
593
}
3587
3588
/// Pre-split loads and stores to simplify rewriting.
3589
///
3590
/// We want to break up the splittable load+store pairs as much as
3591
/// possible. This is important to do as a preprocessing step, as once we
3592
/// start rewriting the accesses to partitions of the alloca we lose the
3593
/// necessary information to correctly split apart paired loads and stores
3594
/// which both point into this alloca. The case to consider is something like
3595
/// the following:
3596
///
3597
///   %a = alloca [12 x i8]
3598
///   %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
3599
///   %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
3600
///   %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
3601
///   %iptr1 = bitcast i8* %gep1 to i64*
3602
///   %iptr2 = bitcast i8* %gep2 to i64*
3603
///   %fptr1 = bitcast i8* %gep1 to float*
3604
///   %fptr2 = bitcast i8* %gep2 to float*
3605
///   %fptr3 = bitcast i8* %gep3 to float*
3606
///   store float 0.0, float* %fptr1
3607
///   store float 1.0, float* %fptr2
3608
///   %v = load i64* %iptr1
3609
///   store i64 %v, i64* %iptr2
3610
///   %f1 = load float* %fptr2
3611
///   %f2 = load float* %fptr3
3612
///
3613
/// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
3614
/// promote everything so we recover the 2 SSA values that should have been
3615
/// there all along.
3616
///
3617
/// \returns true if any changes are made.
3618
879k
bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
3619
879k
  LLVM_DEBUG(dbgs() << "Pre-splitting loads and stores\n");
3620
879k
3621
879k
  // Track the loads and stores which are candidates for pre-splitting here, in
3622
879k
  // the order they first appear during the partition scan. These give stable
3623
879k
  // iteration order and a basis for tracking which loads and stores we
3624
879k
  // actually split.
3625
879k
  SmallVector<LoadInst *, 4> Loads;
3626
879k
  SmallVector<StoreInst *, 4> Stores;
3627
879k
3628
879k
  // We need to accumulate the splits required of each load or store where we
3629
879k
  // can find them via a direct lookup. This is important to cross-check loads
3630
879k
  // and stores against each other. We also track the slice so that we can kill
3631
879k
  // all the slices that end up split.
3632
879k
  struct SplitOffsets {
3633
879k
    Slice *S;
3634
879k
    std::vector<uint64_t> Splits;
3635
879k
  };
3636
879k
  SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
3637
879k
3638
879k
  // Track loads out of this alloca which cannot, for any reason, be pre-split.
3639
879k
  // This is important as we also cannot pre-split stores of those loads!
3640
879k
  // FIXME: This is all pretty gross. It means that we can be more aggressive
3641
879k
  // in pre-splitting when the load feeding the store happens to come from
3642
879k
  // a separate alloca. Put another way, the effectiveness of SROA would be
3643
879k
  // decreased by a frontend which just concatenated all of its local allocas
3644
879k
  // into one big flat alloca. But defeating such patterns is exactly the job
3645
879k
  // SROA is tasked with! Sadly, to not have this discrepancy we would have
3646
879k
  // change store pre-splitting to actually force pre-splitting of the load
3647
879k
  // that feeds it *and all stores*. That makes pre-splitting much harder, but
3648
879k
  // maybe it would make it more principled?
3649
879k
  SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
3650
879k
3651
879k
  LLVM_DEBUG(dbgs() << "  Searching for candidate loads and stores\n");
3652
919k
  for (auto &P : AS.partitions()) {
3653
3.79M
    for (Slice &S : P) {
3654
3.79M
      Instruction *I = cast<Instruction>(S.getUse()->getUser());
3655
3.79M
      if (!S.isSplittable() || 
S.endOffset() <= P.endOffset()2.16M
) {
3656
3.76M
        // If this is a load we have to track that it can't participate in any
3657
3.76M
        // pre-splitting. If this is a store of a load we have to track that
3658
3.76M
        // that load also can't participate in any pre-splitting.
3659
3.76M
        if (auto *LI = dyn_cast<LoadInst>(I))
3660
1.87M
          UnsplittableLoads.insert(LI);
3661
1.89M
        else if (auto *SI = dyn_cast<StoreInst>(I))
3662
1.22M
          if (auto *LI = dyn_cast<LoadInst>(SI->getValueOperand()))
3663
115k
            UnsplittableLoads.insert(LI);
3664
3.76M
        continue;
3665
3.76M
      }
3666
29.3k
      assert(P.endOffset() > S.beginOffset() &&
3667
29.3k
             "Empty or backwards partition!");
3668
29.3k
3669
29.3k
      // Determine if this is a pre-splittable slice.
3670
29.3k
      if (auto *LI = dyn_cast<LoadInst>(I)) {
3671
226
        assert(!LI->isVolatile() && "Cannot split volatile loads!");
3672
226
3673
226
        // The load must be used exclusively to store into other pointers for
3674
226
        // us to be able to arbitrarily pre-split it. The stores must also be
3675
226
        // simple to avoid changing semantics.
3676
226
        auto IsLoadSimplyStored = [](LoadInst *LI) {
3677
235
          for (User *LU : LI->users()) {
3678
235
            auto *SI = dyn_cast<StoreInst>(LU);
3679
235
            if (!SI || 
!SI->isSimple()24
)
3680
211
              return false;
3681
235
          }
3682
226
          
return true15
;
3683
226
        };
3684
226
        if (!IsLoadSimplyStored(LI)) {
3685
211
          UnsplittableLoads.insert(LI);
3686
211
          continue;
3687
211
        }
3688
15
3689
15
        Loads.push_back(LI);
3690
29.1k
      } else if (auto *SI = dyn_cast<StoreInst>(I)) {
3691
62
        if (S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
3692
0
          // Skip stores *of* pointers. FIXME: This shouldn't even be possible!
3693
0
          continue;
3694
62
        auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
3695
62
        if (!StoredLoad || 
!StoredLoad->isSimple()19
)
3696
43
          continue;
3697
19
        assert(!SI->isVolatile() && "Cannot split volatile stores!");
3698
19
3699
19
        Stores.push_back(SI);
3700
29.0k
      } else {
3701
29.0k
        // Other uses cannot be pre-split.
3702
29.0k
        continue;
3703
29.0k
      }
3704
34
3705
34
      // Record the initial split.
3706
34
      LLVM_DEBUG(dbgs() << "    Candidate: " << *I << "\n");
3707
34
      auto &Offsets = SplitOffsetsMap[I];
3708
34
      assert(Offsets.Splits.empty() &&
3709
34
             "Should not have splits the first time we see an instruction!");
3710
34
      Offsets.S = &S;
3711
34
      Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
3712
34
    }
3713
919k
3714
919k
    // Now scan the already split slices, and add a split for any of them which
3715
919k
    // we're going to pre-split.
3716
919k
    for (Slice *S : P.splitSliceTails()) {
3717
82.5k
      auto SplitOffsetsMapI =
3718
82.5k
          SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
3719
82.5k
      if (SplitOffsetsMapI == SplitOffsetsMap.end())
3720
82.5k
        continue;
3721
34
      auto &Offsets = SplitOffsetsMapI->second;
3722
34
3723
34
      assert(Offsets.S == S && "Found a mismatched slice!");
3724
34
      assert(!Offsets.Splits.empty() &&
3725
34
             "Cannot have an empty set of splits on the second partition!");
3726
34
      assert(Offsets.Splits.back() ==
3727
34
                 P.beginOffset() - Offsets.S->beginOffset() &&
3728
34
             "Previous split does not end where this one begins!");
3729
34
3730
34
      // Record each split. The last partition's end isn't needed as the size
3731
34
      // of the slice dictates that.
3732
34
      if (S->endOffset() > P.endOffset())
3733
0
        Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
3734
34
    }
3735
919k
  }
3736
879k
3737
879k
  // We may have split loads where some of their stores are split stores. For
3738
879k
  // such loads and stores, we can only pre-split them if their splits exactly
3739
879k
  // match relative to their starting offset. We have to verify this prior to
3740
879k
  // any rewriting.
3741
879k
  Stores.erase(
3742
879k
      llvm::remove_if(Stores,
3743
879k
                      [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
3744
19
                        // Lookup the load we are storing in our map of split
3745
19
                        // offsets.
3746
19
                        auto *LI = cast<LoadInst>(SI->getValueOperand());
3747
19
                        // If it was completely unsplittable, then we're done,
3748
19
                        // and this store can't be pre-split.
3749
19
                        if (UnsplittableLoads.count(LI))
3750
2
                          return true;
3751
17
3752
17
                        auto LoadOffsetsI = SplitOffsetsMap.find(LI);
3753
17
                        if (LoadOffsetsI == SplitOffsetsMap.end())
3754
11
                          return false; // Unrelated loads are definitely safe.
3755
6
                        auto &LoadOffsets = LoadOffsetsI->second;
3756
6
3757
6
                        // Now lookup the store's offsets.
3758
6
                        auto &StoreOffsets = SplitOffsetsMap[SI];
3759
6
3760
6
                        // If the relative offsets of each split in the load and
3761
6
                        // store match exactly, then we can split them and we
3762
6
                        // don't need to remove them here.
3763
6
                        if (LoadOffsets.Splits == StoreOffsets.Splits)
3764
4
                          return false;
3765
2
3766
2
                        LLVM_DEBUG(
3767
2
                            dbgs()
3768
2
                            << "    Mismatched splits for load and store:\n"
3769
2
                            << "      " << *LI << "\n"
3770
2
                            << "      " << *SI << "\n");
3771
2
3772
2
                        // We've found a store and load that we need to split
3773
2
                        // with mismatched relative splits. Just give up on them
3774
2
                        // and remove both instructions from our list of
3775
2
                        // candidates.
3776
2
                        UnsplittableLoads.insert(LI);
3777
2
                        return true;
3778
2
                      }),
3779
879k
      Stores.end());
3780
879k
  // Now we have to go *back* through all the stores, because a later store may
3781
879k
  // have caused an earlier store's load to become unsplittable and if it is
3782
879k
  // unsplittable for the later store, then we can't rely on it being split in
3783
879k
  // the earlier store either.
3784
879k
  Stores.erase(llvm::remove_if(Stores,
3785
879k
                               [&UnsplittableLoads](StoreInst *SI) {
3786
15
                                 auto *LI =
3787
15
                                     cast<LoadInst>(SI->getValueOperand());
3788
15
                                 return UnsplittableLoads.count(LI);
3789
15
                               }),
3790
879k
               Stores.end());
3791
879k
  // Once we've established all the loads that can't be split for some reason,
3792
879k
  // filter any that made it into our list out.
3793
879k
  Loads.erase(llvm::remove_if(Loads,
3794
879k
                              [&UnsplittableLoads](LoadInst *LI) {
3795
15
                                return UnsplittableLoads.count(LI);
3796
15
                              }),
3797
879k
              Loads.end());
3798
879k
3799
879k
  // If no loads or stores are left, there is no pre-splitting to be done for
3800
879k
  // this alloca.
3801
879k
  if (Loads.empty() && 
Stores.empty()879k
)
3802
879k
    return false;
3803
16
3804
16
  // From here on, we can't fail and will be building new accesses, so rig up
3805
16
  // an IR builder.
3806
16
  IRBuilderTy IRB(&AI);
3807
16
3808
16
  // Collect the new slices which we will merge into the alloca slices.
3809
16
  SmallVector<Slice, 4> NewSlices;
3810
16
3811
16
  // Track any allocas we end up splitting loads and stores for so we iterate
3812
16
  // on them.
3813
16
  SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
3814
16
3815
16
  // At this point, we have collected all of the loads and stores we can
3816
16
  // pre-split, and the specific splits needed for them. We actually do the
3817
16
  // splitting in a specific order in order to handle when one of the loads in
3818
16
  // the value operand to one of the stores.
3819
16
  //
3820
16
  // First, we rewrite all of the split loads, and just accumulate each split
3821
16
  // load in a parallel structure. We also build the slices for them and append
3822
16
  // them to the alloca slices.
3823
16
  SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
3824
16
  std::vector<LoadInst *> SplitLoads;
3825
16
  const DataLayout &DL = AI.getModule()->getDataLayout();
3826
16
  for (LoadInst *LI : Loads) {
3827
11
    SplitLoads.clear();
3828
11
3829
11
    IntegerType *Ty = cast<IntegerType>(LI->getType());
3830
11
    uint64_t LoadSize = Ty->getBitWidth() / 8;
3831
11
    assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
3832
11
3833
11
    auto &Offsets = SplitOffsetsMap[LI];
3834
11
    assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3835
11
           "Slice size should always match load size exactly!");
3836
11
    uint64_t BaseOffset = Offsets.S->beginOffset();
3837
11
    assert(BaseOffset + LoadSize > BaseOffset &&
3838
11
           "Cannot represent alloca access size using 64-bit integers!");
3839
11
3840
11
    Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
3841
11
    IRB.SetInsertPoint(LI);
3842
11
3843
11
    LLVM_DEBUG(dbgs() << "  Splitting load: " << *LI << "\n");
3844
11
3845
11
    uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3846
11
    int Idx = 0, Size = Offsets.Splits.size();
3847
22
    for (;;) {
3848
22
      auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3849
22
      auto AS = LI->getPointerAddressSpace();
3850
22
      auto *PartPtrTy = PartTy->getPointerTo(AS);
3851
22
      LoadInst *PLoad = IRB.CreateAlignedLoad(
3852
22
          PartTy,
3853
22
          getAdjustedPtr(IRB, DL, BasePtr,
3854
22
                         APInt(DL.getIndexSizeInBits(AS), PartOffset),
3855
22
                         PartPtrTy, BasePtr->getName() + "."),
3856
22
          getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
3857
22
          LI->getName());
3858
22
      PLoad->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
3859
22
                                LLVMContext::MD_access_group});
3860
22
3861
22
      // Append this load onto the list of split loads so we can find it later
3862
22
      // to rewrite the stores.
3863
22
      SplitLoads.push_back(PLoad);
3864
22
3865
22
      // Now build a new slice for the alloca.
3866
22
      NewSlices.push_back(
3867
22
          Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
3868
22
                &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
3869
22
                /*IsSplittable*/ false));
3870
22
      LLVM_DEBUG(dbgs() << "    new slice [" << NewSlices.back().beginOffset()
3871
22
                        << ", " << NewSlices.back().endOffset()
3872
22
                        << "): " << *PLoad << "\n");
3873
22
3874
22
      // See if we've handled all the splits.
3875
22
      if (Idx >= Size)
3876
11
        break;
3877
11
3878
11
      // Setup the next partition.
3879
11
      PartOffset = Offsets.Splits[Idx];
3880
11
      ++Idx;
3881
11
      PartSize = (Idx < Size ? 
Offsets.Splits[Idx]0
: LoadSize) - PartOffset;
3882
11
    }
3883
11
3884
11
    // Now that we have the split loads, do the slow walk over all uses of the
3885
11
    // load and rewrite them as split stores, or save the split loads to use
3886
11
    // below if the store is going to be split there anyways.
3887
11
    bool DeferredStores = false;
3888
11
    for (User *LU : LI->users()) {
3889
11
      StoreInst *SI = cast<StoreInst>(LU);
3890
11
      if (!Stores.empty() && 
SplitOffsetsMap.count(SI)6
) {
3891
2
        DeferredStores = true;
3892
2
        LLVM_DEBUG(dbgs() << "    Deferred splitting of store: " << *SI
3893
2
                          << "\n");
3894
2
        continue;
3895
2
      }
3896
9
3897
9
      Value *StoreBasePtr = SI->getPointerOperand();
3898
9
      IRB.SetInsertPoint(SI);
3899
9
3900
9
      LLVM_DEBUG(dbgs() << "    Splitting store of load: " << *SI << "\n");
3901
9
3902
27
      for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; 
++Idx18
) {
3903
18
        LoadInst *PLoad = SplitLoads[Idx];
3904
18
        uint64_t PartOffset = Idx == 0 ? 
09
:
Offsets.Splits[Idx - 1]9
;
3905
18
        auto *PartPtrTy =
3906
18
            PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
3907
18
3908
18
        auto AS = SI->getPointerAddressSpace();
3909
18
        StoreInst *PStore = IRB.CreateAlignedStore(
3910
18
            PLoad,
3911
18
            getAdjustedPtr(IRB, DL, StoreBasePtr,
3912
18
                           APInt(DL.getIndexSizeInBits(AS), PartOffset),
3913
18
                           PartPtrTy, StoreBasePtr->getName() + "."),
3914
18
            getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
3915
18
        PStore->copyMetadata(*LI, {LLVMContext::MD_mem_parallel_loop_access,
3916
18
                                   LLVMContext::MD_access_group});
3917
18
        LLVM_DEBUG(dbgs() << "      +" << PartOffset << ":" << *PStore << "\n");
3918
18
      }
3919
9
3920
9
      // We want to immediately iterate on any allocas impacted by splitting
3921
9
      // this store, and we have to track any promotable alloca (indicated by
3922
9
      // a direct store) as needing to be resplit because it is no longer
3923
9
      // promotable.
3924
9
      if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
3925
2
        ResplitPromotableAllocas.insert(OtherAI);
3926
2
        Worklist.insert(OtherAI);
3927
7
      } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
3928
0
                     StoreBasePtr->stripInBoundsOffsets())) {
3929
0
        Worklist.insert(OtherAI);
3930
0
      }
3931
9
3932
9
      // Mark the original store as dead.
3933
9
      DeadInsts.insert(SI);
3934
9
    }
3935
11
3936
11
    // Save the split loads if there are deferred stores among the users.
3937
11
    if (DeferredStores)
3938
2
      SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
3939
11
3940
11
    // Mark the original load as dead and kill the original slice.
3941
11
    DeadInsts.insert(LI);
3942
11
    Offsets.S->kill();
3943
11
  }
3944
16
3945
16
  // Second, we rewrite all of the split stores. At this point, we know that
3946
16
  // all loads from this alloca have been split already. For stores of such
3947
16
  // loads, we can simply look up the pre-existing split loads. For stores of
3948
16
  // other loads, we split those loads first and then write split stores of
3949
16
  // them.
3950
16
  for (StoreInst *SI : Stores) {
3951
13
    auto *LI = cast<LoadInst>(SI->getValueOperand());
3952
13
    IntegerType *Ty = cast<IntegerType>(LI->getType());
3953
13
    uint64_t StoreSize = Ty->getBitWidth() / 8;
3954
13
    assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
3955
13
3956
13
    auto &Offsets = SplitOffsetsMap[SI];
3957
13
    assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
3958
13
           "Slice size should always match load size exactly!");
3959
13
    uint64_t BaseOffset = Offsets.S->beginOffset();
3960
13
    assert(BaseOffset + StoreSize > BaseOffset &&
3961
13
           "Cannot represent alloca access size using 64-bit integers!");
3962
13
3963
13
    Value *LoadBasePtr = LI->getPointerOperand();
3964
13
    Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
3965
13
3966
13
    LLVM_DEBUG(dbgs() << "  Splitting store: " << *SI << "\n");
3967
13
3968
13
    // Check whether we have an already split load.
3969
13
    auto SplitLoadsMapI = SplitLoadsMap.find(LI);
3970
13
    std::vector<LoadInst *> *SplitLoads = nullptr;
3971
13
    if (SplitLoadsMapI != SplitLoadsMap.end()) {
3972
2
      SplitLoads = &SplitLoadsMapI->second;
3973
2
      assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
3974
2
             "Too few split loads for the number of splits in the store!");
3975
11
    } else {
3976
11
      LLVM_DEBUG(dbgs() << "          of load: " << *LI << "\n");
3977
11
    }
3978
13
3979
13
    uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
3980
13
    int Idx = 0, Size = Offsets.Splits.size();
3981
26
    for (;;) {
3982
26
      auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
3983
26
      auto *LoadPartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
3984
26
      auto *StorePartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
3985
26
3986
26
      // Either lookup a split load or create one.
3987
26
      LoadInst *PLoad;
3988
26
      if (SplitLoads) {
3989
4
        PLoad = (*SplitLoads)[Idx];
3990
22
      } else {
3991
22
        IRB.SetInsertPoint(LI);
3992
22
        auto AS = LI->getPointerAddressSpace();
3993
22
        PLoad = IRB.CreateAlignedLoad(
3994
22
            PartTy,
3995
22
            getAdjustedPtr(IRB, DL, LoadBasePtr,
3996
22
                           APInt(DL.getIndexSizeInBits(AS), PartOffset),
3997
22
                           LoadPartPtrTy, LoadBasePtr->getName() + "."),
3998
22
            getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
3999
22
            LI->getName());
4000
22
      }
4001
26
4002
26
      // And store this partition.
4003
26
      IRB.SetInsertPoint(SI);
4004
26
      auto AS = SI->getPointerAddressSpace();
4005
26
      StoreInst *PStore = IRB.CreateAlignedStore(
4006
26
          PLoad,
4007
26
          getAdjustedPtr(IRB, DL, StoreBasePtr,
4008
26
                         APInt(DL.getIndexSizeInBits(AS), PartOffset),
4009
26
                         StorePartPtrTy, StoreBasePtr->getName() + "."),
4010
26
          getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
4011
26
4012
26
      // Now build a new slice for the alloca.
4013
26
      NewSlices.push_back(
4014
26
          Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
4015
26
                &PStore->getOperandUse(PStore->getPointerOperandIndex()),
4016
26
                /*IsSplittable*/ false));
4017
26
      LLVM_DEBUG(dbgs() << "    new slice [" << NewSlices.back().beginOffset()
4018
26
                        << ", " << NewSlices.back().endOffset()
4019
26
                        << "): " << *PStore << "\n");
4020
26
      if (!SplitLoads) {
4021
22
        LLVM_DEBUG(dbgs() << "      of split load: " << *PLoad << "\n");
4022
22
      }
4023
26
4024
26
      // See if we've finished all the splits.
4025
26
      if (Idx >= Size)
4026
13
        break;
4027
13
4028
13
      // Setup the next partition.
4029
13
      PartOffset = Offsets.Splits[Idx];
4030
13
      ++Idx;
4031
13
      PartSize = (Idx < Size ? 
Offsets.Splits[Idx]0
: StoreSize) - PartOffset;
4032
13
    }
4033
13
4034
13
    // We want to immediately iterate on any allocas impacted by splitting
4035
13
    // this load, which is only relevant if it isn't a load of this alloca and
4036
13
    // thus we didn't already split the loads above. We also have to keep track
4037
13
    // of any promotable allocas we split loads on as they can no longer be
4038
13
    // promoted.
4039
13
    if (!SplitLoads) {
4040
11
      if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
4041
2
        assert(OtherAI != &AI && "We can't re-split our own alloca!");
4042
2
        ResplitPromotableAllocas.insert(OtherAI);
4043
2
        Worklist.insert(OtherAI);
4044
9
      } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
4045
0
                     LoadBasePtr->stripInBoundsOffsets())) {
4046
0
        assert(OtherAI != &AI && "We can't re-split our own alloca!");
4047
0
        Worklist.insert(OtherAI);
4048
0
      }
4049
11
    }
4050
13
4051
13
    // Mark the original store as dead now that we've split it up and kill its
4052
13
    // slice. Note that we leave the original load in place unless this store
4053
13
    // was its only use. It may in turn be split up if it is an alloca load
4054
13
    // for some other alloca, but it may be a normal load. This may introduce
4055
13
    // redundant loads, but where those can be merged the rest of the optimizer
4056
13
    // should handle the merging, and this uncovers SSA splits which is more
4057
13
    // important. In practice, the original loads will almost always be fully
4058
13
    // split and removed eventually, and the splits will be merged by any
4059
13
    // trivial CSE, including instcombine.
4060
13
    if (LI->hasOneUse()) {
4061
13
      assert(*LI->user_begin() == SI && "Single use isn't this store!");
4062
13
      DeadInsts.insert(LI);
4063
13
    }
4064
13
    DeadInsts.insert(SI);
4065
13
    Offsets.S->kill();
4066
13
  }
4067
16
4068
16
  // Remove the killed slices that have ben pre-split.
4069
88
  AS.erase(llvm::remove_if(AS, [](const Slice &S) { return S.isDead(); }),
4070
16
           AS.end());
4071
16
4072
16
  // Insert our new slices. This will sort and merge them into the sorted
4073
16
  // sequence.
4074
16
  AS.insert(NewSlices);
4075
16
4076
16
  LLVM_DEBUG(dbgs() << "  Pre-split slices:\n");
4077
#ifndef NDEBUG
4078
  for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
4079
    LLVM_DEBUG(AS.print(dbgs(), I, "    "));
4080
#endif
4081
4082
16
  // Finally, don't try to promote any allocas that new require re-splitting.
4083
16
  // They have already been added to the worklist above.
4084
16
  PromotableAllocas.erase(
4085
16
      llvm::remove_if(
4086
16
          PromotableAllocas,
4087
30
          [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
4088
16
      PromotableAllocas.end());
4089
16
4090
16
  return true;
4091
16
}
4092
4093
/// Rewrite an alloca partition's users.
4094
///
4095
/// This routine drives both of the rewriting goals of the SROA pass. It tries
4096
/// to rewrite uses of an alloca partition to be conducive for SSA value
4097
/// promotion. If the partition needs a new, more refined alloca, this will
4098
/// build that new alloca, preserving as much type information as possible, and
4099
/// rewrite the uses of the old alloca to point at the new one and have the
4100
/// appropriate new offsets. It also evaluates how successful the rewrite was
4101
/// at enabling promotion and if it was successful queues the alloca to be
4102
/// promoted.
4103
AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
4104
938k
                                   Partition &P) {
4105
938k
  // Try to compute a friendly type for this partition of the alloca. This
4106
938k
  // won't always succeed, in which case we fall back to a legal integer type
4107
938k
  // or an i8 array of an appropriate size.
4108
938k
  Type *SliceTy = nullptr;
4109
938k
  const DataLayout &DL = AI.getModule()->getDataLayout();
4110
938k
  if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
4111
918k
    if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
4112
918k
      SliceTy = CommonUseTy;
4113
938k
  if (!SliceTy)
4114
19.9k
    if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
4115
17.9k
                                                 P.beginOffset(), P.size()))
4116
17.9k
      SliceTy = TypePartitionTy;
4117
938k
  if ((!SliceTy || 
(936k
SliceTy->isArrayTy()936k
&&
4118
936k
                    
SliceTy->getArrayElementType()->isIntegerTy()3.17k
)) &&
4119
938k
      
DL.isLegalInteger(P.size() * 8)5.09k
)
4120
840
    SliceTy = Type::getIntNTy(*C, P.size() * 8);
4121
938k
  if (!SliceTy)
4122
1.46k
    SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
4123
938k
  assert(DL.getTypeAllocSize(SliceTy) >= P.size());
4124
938k
4125
938k
  bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
4126
938k
4127
938k
  VectorType *VecTy =
4128
938k
      IsIntegerPromotable ? 
nullptr834k
:
isVectorPromotionViable(P, DL)103k
;
4129
938k
  if (VecTy)
4130
32.2k
    SliceTy = VecTy;
4131
938k
4132
938k
  // Check for the case where we're going to rewrite to a new alloca of the
4133
938k
  // exact same type as the original, and with the same access offsets. In that
4134
938k
  // case, re-use the existing alloca, but still run through the rewriter to
4135
938k
  // perform phi and select speculation.
4136
938k
  // P.beginOffset() can be non-zero even with the same type in a case with
4137
938k
  // out-of-bounds access (e.g. @PR35657 function in SROA/basictest.ll).
4138
938k
  AllocaInst *NewAI;
4139
938k
  if (SliceTy == AI.getAllocatedType() && 
P.beginOffset() == 0821k
) {
4140
821k
    NewAI = &AI;
4141
821k
    // FIXME: We should be able to bail at this point with "nothing changed".
4142
821k
    // FIXME: We might want to defer PHI speculation until after here.
4143
821k
    // FIXME: return nullptr;
4144
821k
  } else {
4145
116k
    unsigned Alignment = AI.getAlignment();
4146
116k
    if (!Alignment) {
4147
1.44k
      // The minimum alignment which users can rely on when the explicit
4148
1.44k
      // alignment is omitted or zero is that required by the ABI for this
4149
1.44k
      // type.
4150
1.44k
      Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
4151
1.44k
    }
4152
116k
    Alignment = MinAlign(Alignment, P.beginOffset());
4153
116k
    // If we will get at least this much alignment from the type alone, leave
4154
116k
    // the alloca's alignment unconstrained.
4155
116k
    if (Alignment <= DL.getABITypeAlignment(SliceTy))
4156
107k
      Alignment = 0;
4157
116k
    NewAI = new AllocaInst(
4158
116k
      SliceTy, AI.getType()->getAddressSpace(), nullptr, Alignment,
4159
116k
        AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
4160
116k
    // Copy the old AI debug location over to the new one.
4161
116k
    NewAI->setDebugLoc(AI.getDebugLoc());
4162
116k
    ++NumNewAllocas;
4163
116k
  }
4164
938k
4165
938k
  LLVM_DEBUG(dbgs() << "Rewriting alloca partition "
4166
938k
                    << "[" << P.beginOffset() << "," << P.endOffset()
4167
938k
                    << ") to: " << *NewAI << "\n");
4168
938k
4169
938k
  // Track the high watermark on the worklist as it is only relevant for
4170
938k
  // promoted allocas. We will reset it to this point if the alloca is not in
4171
938k
  // fact scheduled for promotion.
4172
938k
  unsigned PPWOldSize = PostPromotionWorklist.size();
4173
938k
  unsigned NumUses = 0;
4174
938k
  SmallSetVector<PHINode *, 8> PHIUsers;
4175
938k
  SmallSetVector<SelectInst *, 8> SelectUsers;
4176
938k
4177
938k
  AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
4178
938k
                               P.endOffset(), IsIntegerPromotable, VecTy,
4179
938k
                               PHIUsers, SelectUsers);
4180
938k
  bool Promotable = true;
4181
938k
  for (Slice *S : P.splitSliceTails()) {
4182
124k
    Promotable &= Rewriter.visit(S);
4183
124k
    ++NumUses;
4184
124k
  }
4185
3.79M
  for (Slice &S : P) {
4186
3.79M
    Promotable &= Rewriter.visit(&S);
4187
3.79M
    ++NumUses;
4188
3.79M
  }
4189
938k
4190
938k
  NumAllocaPartitionUses += NumUses;
4191
938k
  MaxUsesPerAllocaPartition.updateMax(NumUses);
4192
938k
4193
938k
  // Now that we've processed all the slices in the new partition, check if any
4194
938k
  // PHIs or Selects would block promotion.
4195
938k
  for (PHINode *PHI : PHIUsers)
4196
424
    if (!isSafePHIToSpeculate(*PHI)) {
4197
411
      Promotable = false;
4198
411
      PHIUsers.clear();
4199
411
      SelectUsers.clear();
4200
411
      break;
4201
411
    }
4202
938k
4203
938k
  for (SelectInst *Sel : SelectUsers)
4204
1.61k
    if (!isSafeSelectToSpeculate(*Sel)) {
4205
170
      Promotable = false;
4206
170
      PHIUsers.clear();
4207
170
      SelectUsers.clear();
4208
170
      break;
4209
170
    }
4210
938k
4211
938k
  if (Promotable) {
4212
928k
    if (PHIUsers.empty() && 
SelectUsers.empty()928k
) {
4213
927k
      // Promote the alloca.
4214
927k
      PromotableAllocas.push_back(NewAI);
4215
927k
    } else {
4216
1.45k
      // If we have either PHIs or Selects to speculate, add them to those
4217
1.45k
      // worklists and re-queue the new alloca so that we promote in on the
4218
1.45k
      // next iteration.
4219
1.45k
      for (PHINode *PHIUser : PHIUsers)
4220
12
        SpeculatablePHIs.insert(PHIUser);
4221
1.45k
      for (SelectInst *SelectUser : SelectUsers)
4222
1.44k
        SpeculatableSelects.insert(SelectUser);
4223
1.45k
      Worklist.insert(NewAI);
4224
1.45k
    }
4225
928k
  } else {
4226
9.54k
    // Drop any post-promotion work items if promotion didn't happen.
4227
9.55k
    while (PostPromotionWorklist.size() > PPWOldSize)
4228
6
      PostPromotionWorklist.pop_back();
4229
9.54k
4230
9.54k
    // We couldn't promote and we didn't create a new partition, nothing
4231
9.54k
    // happened.
4232
9.54k
    if (NewAI == &AI)
4233
5.13k
      return nullptr;
4234
4.40k
4235
4.40k
    // If we can't promote the alloca, iterate on it to check for new
4236
4.40k
    // refinements exposed by splitting the current alloca. Don't iterate on an
4237
4.40k
    // alloca which didn't actually change and didn't get promoted.
4238
4.40k
    Worklist.insert(NewAI);
4239
4.40k
  }
4240
938k
4241
938k
  
return NewAI933k
;
4242
938k
}
4243
4244
/// Walks the slices of an alloca and form partitions based on them,
4245
/// rewriting each of their uses.
4246
879k
bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
4247
879k
  if (AS.begin() == AS.end())
4248
0
    return false;
4249
879k
4250
879k
  unsigned NumPartitions = 0;
4251
879k
  bool Changed = false;
4252
879k
  const DataLayout &DL = AI.getModule()->getDataLayout();
4253
879k
4254
879k
  // First try to pre-split loads and stores.
4255
879k
  Changed |= presplitLoadsAndStores(AI, AS);
4256
879k
4257
879k
  // Now that we have identified any pre-splitting opportunities,
4258
879k
  // mark loads and stores unsplittable except for the following case.
4259
879k
  // We leave a slice splittable if all other slices are disjoint or fully
4260
879k
  // included in the slice, such as whole-alloca loads and stores.
4261
879k
  // If we fail to split these during pre-splitting, we want to force them
4262
879k
  // to be rewritten into a partition.
4263
879k
  bool IsSorted = true;
4264
879k
4265
879k
  uint64_t AllocaSize = DL.getTypeAllocSize(AI.getAllocatedType());
4266
879k
  const uint64_t MaxBitVectorSize = 1024;
4267
879k
  if (AllocaSize <= MaxBitVectorSize) {
4268
879k
    // If a byte boundary is included in any load or store, a slice starting or
4269
879k
    // ending at the boundary is not splittable.
4270
879k
    SmallBitVector SplittableOffset(AllocaSize + 1, true);
4271
879k
    for (Slice &S : AS)
4272
3.79M
      for (unsigned O = S.beginOffset() + 1;
4273
25.8M
           O < S.endOffset() && 
O < AllocaSize22.0M
;
O++22.0M
)
4274
22.0M
        SplittableOffset.reset(O);
4275
879k
4276
3.79M
    for (Slice &S : AS) {
4277
3.79M
      if (!S.isSplittable())
4278
1.62M
        continue;
4279
2.16M
4280
2.16M
      if ((S.beginOffset() > AllocaSize || SplittableOffset[S.beginOffset()]) &&
4281
2.16M
          
(2.10M
S.endOffset() > AllocaSize2.10M
||
SplittableOffset[S.endOffset()]2.10M
))
4282
2.08M
        continue;
4283
77.0k
4284
77.0k
      if (isa<LoadInst>(S.getUse()->getUser()) ||
4285
77.0k
          
isa<StoreInst>(S.getUse()->getUser())41.6k
) {
4286
74.5k
        S.makeUnsplittable();
4287
74.5k
        IsSorted = false;
4288
74.5k
      }
4289
77.0k
    }
4290
879k
  }
4291
39
  else {
4292
39
    // We only allow whole-alloca splittable loads and stores
4293
39
    // for a large alloca to avoid creating too large BitVector.
4294
146
    for (Slice &S : AS) {
4295
146
      if (!S.isSplittable())
4296
0
        continue;
4297
146
4298
146
      if (S.beginOffset() == 0 && 
S.endOffset() >= AllocaSize129
)
4299
129
        continue;
4300
17
4301
17
      if (isa<LoadInst>(S.getUse()->getUser()) ||
4302
17
          
isa<StoreInst>(S.getUse()->getUser())4
) {
4303
17
        S.makeUnsplittable();
4304
17
        IsSorted = false;
4305
17
      }
4306
17
    }
4307
39
  }
4308
879k
4309
879k
  if (!IsSorted)
4310
15.0k
    llvm::sort(AS);
4311
879k
4312
879k
  /// Describes the allocas introduced by rewritePartition in order to migrate
4313
879k
  /// the debug info.
4314
879k
  struct Fragment {
4315
879k
    AllocaInst *Alloca;
4316
879k
    uint64_t Offset;
4317
879k
    uint64_t Size;
4318
879k
    Fragment(AllocaInst *AI, uint64_t O, uint64_t S)
4319
879k
      : Alloca(AI), Offset(O), Size(S) 
{}116k
4320
879k
  };
4321
879k
  SmallVector<Fragment, 4> Fragments;
4322
879k
4323
879k
  // Rewrite each partition.
4324
938k
  for (auto &P : AS.partitions()) {
4325
938k
    if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
4326
933k
      Changed = true;
4327
933k
      if (NewAI != &AI) {
4328
116k
        uint64_t SizeOfByte = 8;
4329
116k
        uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
4330
116k
        // Don't include any padding.
4331
116k
        uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
4332
116k
        Fragments.push_back(Fragment(NewAI, P.beginOffset() * SizeOfByte, Size));
4333
116k
      }
4334
933k
    }
4335
938k
    ++NumPartitions;
4336
938k
  }
4337
879k
4338
879k
  NumAllocaPartitions += NumPartitions;
4339
879k
  MaxPartitionsPerAlloca.updateMax(NumPartitions);
4340
879k
4341
879k
  // Migrate debug information from the old alloca to the new alloca(s)
4342
879k
  // and the individual partitions.
4343
879k
  TinyPtrVector<DbgVariableIntrinsic *> DbgDeclares = FindDbgAddrUses(&AI);
4344
879k
  if (!DbgDeclares.empty()) {
4345
77
    auto *Var = DbgDeclares.front()->getVariable();
4346
77
    auto *Expr = DbgDeclares.front()->getExpression();
4347
77
    auto VarSize = Var->getSizeInBits();
4348
77
    DIBuilder DIB(*AI.getModule(), /*AllowUnresolved*/ false);
4349
77
    uint64_t AllocaSize = DL.getTypeSizeInBits(AI.getAllocatedType());
4350
77
    for (auto Fragment : Fragments) {
4351
34
      // Create a fragment expression describing the new partition or reuse AI's
4352
34
      // expression if there is only one partition.
4353
34
      auto *FragmentExpr = Expr;
4354
34
      if (Fragment.Size < AllocaSize || 
Expr->isFragment()2
) {
4355
33
        // If this alloca is already a scalar replacement of a larger aggregate,
4356
33
        // Fragment.Offset describes the offset inside the scalar.
4357
33
        auto ExprFragment = Expr->getFragmentInfo();
4358
33
        uint64_t Offset = ExprFragment ? 
ExprFragment->OffsetInBits3
:
030
;
4359
33
        uint64_t Start = Offset + Fragment.Offset;
4360
33
        uint64_t Size = Fragment.Size;
4361
33
        if (ExprFragment) {
4362
3
          uint64_t AbsEnd =
4363
3
              ExprFragment->OffsetInBits + ExprFragment->SizeInBits;
4364
3
          if (Start >= AbsEnd)
4365
0
            // No need to describe a SROAed padding.
4366
0
            continue;
4367
3
          Size = std::min(Size, AbsEnd - Start);
4368
3
        }
4369
33
        // The new, smaller fragment is stenciled out from the old fragment.
4370
33
        if (auto OrigFragment = FragmentExpr->getFragmentInfo()) {
4371
3
          assert(Start >= OrigFragment->OffsetInBits &&
4372
3
                 "new fragment is outside of original fragment");
4373
3
          Start -= OrigFragment->OffsetInBits;
4374
3
        }
4375
33
4376
33
        // The alloca may be larger than the variable.
4377
33
        if (VarSize) {
4378
33
          if (Size > *VarSize)
4379
1
            Size = *VarSize;
4380
33
          if (Size == 0 || Start + Size > *VarSize)
4381
1
            continue;
4382
32
        }
4383
32
4384
32
        // Avoid creating a fragment expression that covers the entire variable.
4385
32
        if (!VarSize || *VarSize != Size) {
4386
30
          if (auto E =
4387
30
                  DIExpression::createFragmentExpression(Expr, Start, Size))
4388
30
            FragmentExpr = *E;
4389
0
          else
4390
0
            continue;
4391
33
        }
4392
32
      }
4393
33
4394
33
      // Remove any existing intrinsics describing the same alloca.
4395
33
      for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(Fragment.Alloca))
4396
0
        OldDII->eraseFromParent();
4397
33
4398
33
      DIB.insertDeclare(Fragment.Alloca, Var, FragmentExpr,
4399
33
                        DbgDeclares.front()->getDebugLoc(), &AI);
4400
33
    }
4401
77
  }
4402
879k
  return Changed;
4403
879k
}
4404
4405
/// Clobber a use with undef, deleting the used value if it becomes dead.
4406
3.66k
void SROA::clobberUse(Use &U) {
4407
3.66k
  Value *OldV = U;
4408
3.66k
  // Replace the use with an undef value.
4409
3.66k
  U = UndefValue::get(OldV->getType());
4410
3.66k
4411
3.66k
  // Check for this making an instruction dead. We have to garbage collect
4412
3.66k
  // all the dead instructions to ensure the uses of any alloca end up being
4413
3.66k
  // minimal.
4414
3.66k
  if (Instruction *OldI = dyn_cast<Instruction>(OldV))
4415
3.14k
    if (isInstructionTriviallyDead(OldI)) {
4416
63
      DeadInsts.insert(OldI);
4417
63
    }
4418
3.66k
}
4419
4420
/// Analyze an alloca for SROA.
4421
///
4422
/// This analyzes the alloca to ensure we can reason about it, builds
4423
/// the slices of the alloca, and then hands it off to be split and
4424
/// rewritten as needed.
4425
1.09M
bool SROA::runOnAlloca(AllocaInst &AI) {
4426
1.09M
  LLVM_DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
4427
1.09M
  ++NumAllocasAnalyzed;
4428
1.09M
4429
1.09M
  // Special case dead allocas, as they're trivial.
4430
1.09M
  if (AI.use_empty()) {
4431
12.3k
    AI.eraseFromParent();
4432
12.3k
    return true;
4433
12.3k
  }
4434
1.08M
  const DataLayout &DL = AI.getModule()->getDataLayout();
4435
1.08M
4436
1.08M
  // Skip alloca forms that this analysis can't handle.
4437
1.08M
  if (AI.isArrayAllocation() || 
!AI.getAllocatedType()->isSized()1.08M
||
4438
1.08M
      
DL.getTypeAllocSize(AI.getAllocatedType()) == 01.08M
)
4439
717
    return false;
4440
1.08M
4441
1.08M
  bool Changed = false;
4442
1.08M
4443
1.08M
  // First, split any FCA loads and stores touching this alloca to promote
4444
1.08M
  // better splitting and promotion opportunities.
4445
1.08M
  AggLoadStoreRewriter AggRewriter(DL);
4446
1.08M
  Changed |= AggRewriter.rewrite(AI);
4447
1.08M
4448
1.08M
  // Build the slices using a recursive instruction-visiting builder.
4449
1.08M
  AllocaSlices AS(DL, AI);
4450
1.08M
  LLVM_DEBUG(AS.print(dbgs()));
4451
1.08M
  if (AS.isEscaped())
4452
201k
    return Changed;
4453
879k
4454
879k
  // Delete all the dead users of this alloca before splitting and rewriting it.
4455
879k
  for (Instruction *DeadUser : AS.getDeadUsers()) {
4456
3.09k
    // Free up everything used by this instruction.
4457
3.09k
    for (Use &DeadOp : DeadUser->operands())
4458
3.65k
      clobberUse(DeadOp);
4459
3.09k
4460
3.09k
    // Now replace the uses of this instruction.
4461
3.09k
    DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
4462
3.09k
4463
3.09k
    // And mark it for deletion.
4464
3.09k
    DeadInsts.insert(DeadUser);
4465
3.09k
    Changed = true;
4466
3.09k
  }
4467
879k
  for (Use *DeadOp : AS.getDeadOperands()) {
4468
3
    clobberUse(*DeadOp);
4469
3
    Changed = true;
4470
3
  }
4471
879k
4472
879k
  // No slices to split. Leave the dead alloca for a later pass to clean up.
4473
879k
  if (AS.begin() == AS.end())
4474
13
    return Changed;
4475
879k
4476
879k
  Changed |= splitAlloca(AI, AS);
4477
879k
4478
879k
  LLVM_DEBUG(dbgs() << "  Speculating PHIs\n");
4479
879k
  while (!SpeculatablePHIs.empty())
4480
9
    speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
4481
879k
4482
879k
  LLVM_DEBUG(dbgs() << "  Speculating Selects\n");
4483
880k
  while (!SpeculatableSelects.empty())
4484
1.43k
    speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
4485
879k
4486
879k
  return Changed;
4487
879k
}
4488
4489
/// Delete the dead instructions accumulated in this run.
4490
///
4491
/// Recursively deletes the dead instructions we've accumulated. This is done
4492
/// at the very end to maximize locality of the recursive delete and to
4493
/// minimize the problems of invalidated instruction pointers as such pointers
4494
/// are used heavily in the intermediate stages of the algorithm.
4495
///
4496
/// We also record the alloca instructions deleted here so that they aren't
4497
/// subsequently handed to mem2reg to promote.
4498
bool SROA::deleteDeadInstructions(
4499
1.09M
    SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
4500
1.09M
  bool Changed = false;
4501
5.83M
  while (!DeadInsts.empty()) {
4502
4.73M
    Instruction *I = DeadInsts.pop_back_val();
4503
4.73M
    LLVM_DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
4504
4.73M
4505
4.73M
    // If the instruction is an alloca, find the possible dbg.declare connected
4506
4.73M
    // to it, and remove it too. We must do this before calling RAUW or we will
4507
4.73M
    // not be able to find it.
4508
4.73M
    if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
4509
57.1k
      DeletedAllocas.insert(AI);
4510
57.1k
      for (DbgVariableIntrinsic *OldDII : FindDbgAddrUses(AI))
4511
17
        OldDII->eraseFromParent();
4512
57.1k
    }
4513
4.73M
4514
4.73M
    I->replaceAllUsesWith(UndefValue::get(I->getType()));
4515
4.73M
4516
4.73M
    for (Use &Operand : I->operands())
4517
7.93M
      if (Instruction *U = dyn_cast<Instruction>(Operand)) {
4518
5.22M
        // Zero out the operand and see if it becomes trivially dead.
4519
5.22M
        Operand = nullptr;
4520
5.22M
        if (isInstructionTriviallyDead(U))
4521
952k
          DeadInsts.insert(U);
4522
5.22M
      }
4523
4.73M
4524
4.73M
    ++NumDeleted;
4525
4.73M
    I->eraseFromParent();
4526
4.73M
    Changed = true;
4527
4.73M
  }
4528
1.09M
  return Changed;
4529
1.09M
}
4530
4531
/// Promote the allocas, using the best available technique.
4532
///
4533
/// This attempts to promote whatever allocas have been identified as viable in
4534
/// the PromotableAllocas list. If that list is empty, there is nothing to do.
4535
/// This function returns whether any promotion occurred.
4536
1.08M
bool SROA::promoteAllocas(Function &F) {
4537
1.08M
  if (PromotableAllocas.empty())
4538
815k
    return false;
4539
274k
4540
274k
  NumPromoted += PromotableAllocas.size();
4541
274k
4542
274k
  LLVM_DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
4543
274k
  PromoteMemToReg(PromotableAllocas, *DT, AC);
4544
274k
  PromotableAllocas.clear();
4545
274k
  return true;
4546
274k
}
4547
4548
PreservedAnalyses SROA::runImpl(Function &F, DominatorTree &RunDT,
4549
1.08M
                                AssumptionCache &RunAC) {
4550
1.08M
  LLVM_DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
4551
1.08M
  C = &F.getContext();
4552
1.08M
  DT = &RunDT;
4553
1.08M
  AC = &RunAC;
4554
1.08M
4555
1.08M
  BasicBlock &EntryBB = F.getEntryBlock();
4556
1.08M
  for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
4557
9.06M
       I != E; 
++I7.97M
) {
4558
7.97M
    if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
4559
1.08M
      Worklist.insert(AI);
4560
7.97M
  }
4561
1.08M
4562
1.08M
  bool Changed = false;
4563
1.08M
  // A set of deleted alloca instruction pointers which should be removed from
4564
1.08M
  // the list of promotable allocas.
4565
1.08M
  SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
4566
1.08M
4567
1.08M
  do {
4568
2.18M
    while (!Worklist.empty()) {
4569
1.09M
      Changed |= runOnAlloca(*Worklist.pop_back_val());
4570
1.09M
      Changed |= deleteDeadInstructions(DeletedAllocas);
4571
1.09M
4572
1.09M
      // Remove the deleted allocas from various lists so that we don't try to
4573
1.09M
      // continue processing them.
4574
1.09M
      if (!DeletedAllocas.empty()) {
4575
1.47M
        auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
4576
57.1k
        Worklist.remove_if(IsInSet);
4577
57.1k
        PostPromotionWorklist.remove_if(IsInSet);
4578
57.1k
        PromotableAllocas.erase(llvm::remove_if(PromotableAllocas, IsInSet),
4579
57.1k
                                PromotableAllocas.end());
4580
57.1k
        DeletedAllocas.clear();
4581
57.1k
      }
4582
1.09M
    }
4583
1.08M
4584
1.08M
    Changed |= promoteAllocas(F);
4585
1.08M
4586
1.08M
    Worklist = PostPromotionWorklist;
4587
1.08M
    PostPromotionWorklist.clear();
4588
1.08M
  } while (!Worklist.empty());
4589
1.08M
4590
1.08M
  if (!Changed)
4591
810k
    return PreservedAnalyses::all();
4592
273k
4593
273k
  PreservedAnalyses PA;
4594
273k
  PA.preserveSet<CFGAnalyses>();
4595
273k
  PA.preserve<GlobalsAA>();
4596
273k
  return PA;
4597
273k
}
4598
4599
2.45k
PreservedAnalyses SROA::run(Function &F, FunctionAnalysisManager &AM) {
4600
2.45k
  return runImpl(F, AM.getResult<DominatorTreeAnalysis>(F),
4601
2.45k
                 AM.getResult<AssumptionAnalysis>(F));
4602
2.45k
}
4603
4604
/// A legacy pass for the legacy pass manager that wraps the \c SROA pass.
4605
///
4606
/// This is in the llvm namespace purely to allow it to be a friend of the \c
4607
/// SROA pass.
4608
class llvm::sroa::SROALegacyPass : public FunctionPass {
4609
  /// The SROA implementation.
4610
  SROA Impl;
4611
4612
public:
4613
  static char ID;
4614
4615
28.9k
  SROALegacyPass() : FunctionPass(ID) {
4616
28.9k
    initializeSROALegacyPassPass(*PassRegistry::getPassRegistry());
4617
28.9k
  }
4618
4619
1.08M
  bool runOnFunction(Function &F) override {
4620
1.08M
    if (skipFunction(F))
4621
95
      return false;
4622
1.08M
4623
1.08M
    auto PA = Impl.runImpl(
4624
1.08M
        F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4625
1.08M
        getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
4626
1.08M
    return !PA.areAllPreserved();
4627
1.08M
  }
4628
4629
28.9k
  void getAnalysisUsage(AnalysisUsage &AU) const override {
4630
28.9k
    AU.addRequired<AssumptionCacheTracker>();
4631
28.9k
    AU.addRequired<DominatorTreeWrapperPass>();
4632
28.9k
    AU.addPreserved<GlobalsAAWrapperPass>();
4633
28.9k
    AU.setPreservesCFG();
4634
28.9k
  }
4635
4636
1.08M
  StringRef getPassName() const override { return "SROA"; }
4637
};
4638
4639
char SROALegacyPass::ID = 0;
4640
4641
28.9k
FunctionPass *llvm::createSROAPass() { return new SROALegacyPass(); }
4642
4643
48.9k
INITIALIZE_PASS_BEGIN(SROALegacyPass, "sroa",
4644
48.9k
                      "Scalar Replacement Of Aggregates", false, false)
4645
48.9k
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4646
48.9k
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
4647
48.9k
INITIALIZE_PASS_END(SROALegacyPass, "sroa", "Scalar Replacement Of Aggregates",
4648
                    false, false)